[Python] I want to use the foreign key model as forms in Django forms

Discussão em 'Python' iniciado por Stack, Fevereiro 22, 2025.

  1. Stack

    Stack Membro Participativo

    I have two models in django farmer and tractor and i want to use both the models in single form on webpage so that with all the properties as there inputs like name, phone, email , id, price etc.

    my models.py

    class Farmer(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    phone =models.CharField(max_length=10)
    address = models.TextField(max_length=200)
    email_address = models.EmailField()

    def full_name(self):
    return f"{self.first_name} {self.last_name}"

    def __str__(self):
    return self.full_name()


    class Post(models.Model):
    tractor_price = models.IntegerField(max_length=150)
    implementation = models.CharField(max_length=50)
    purchase_date = models.DateField(auto_now=False)
    slug = models.SlugField(unique=True, db_index=True, null=True,blank=True)
    tractor_company = models.CharField(max_length=50)
    tractor_model = models.CharField(max_length=50)
    description = models.TextField(validators=[MinLengthValidator(10)])
    date = models.DateField(auto_now=False)
    farmer = models.ForeignKey(
    Farmer, on_delete=models.SET_NULL, null=True, related_name="posts")


    forms.py

    from django import forms
    from django.forms import ModelForm
    from .models import Post,Farmer

    class PostForm(ModelForm):
    class Meta:
    model = Post
    fields = ["tractor_price","implementaion","purchase_date","tractor_company","tractor_model","description"]

    class FarmerForm(ModelForm):
    class Meta:
    model = Farmer
    fields = ['first_name','last_name','phone','address','email_address']


    views.py this is only the form function

    def add_post(request):
    submitted = False
    if(request.method == "POST"):
    form1 = FarmerForm(request.POST,prefix="form1")
    form2 = PostForm(request.POST,prefix="form2")

    if form1.is_valid() and form2.is_valid():
    form1.save()
    form2.save()
    return HttpResponseRedirect("/add_post?submitted=True")
    else:
    form1 = FarmerForm(prefix="form1")
    form2 = PostForm(prefix="form2")
    if("submitted" in request.GET):
    submitted = True
    return render(request,"tractor/form.html",{"form1":form1,"form2":form2, "submitted": submitted})




    here is my forms.html

    {% extends "base.html" %} {% block content %}
    <br />
    <h1 style="margin-left: 40px">Add Event</h1>
    <br />
    {% if submitted %}
    <h3 style="margin-left: 40px">Your Form is Submitted</h3>
    {% else %}
    <div class="form-group">
    <form method="POST" action="">
    {% csrf_token %}
    {{ form1.as_p }}
    {{ form2.as_p }}
    <button type='submit'> send data </button>
    </form>
    </div>
    {% endif %} {% endblock %}


    I am able to submit the form but after submission I am not getting details of farmer like phone, email id etc in database. details of tractor are being saved after submitting but detail of farmer is not bieng saved.

    Continue reading...

Compartilhe esta Página