Как сохранить форму с отношениями в django? - PullRequest
0 голосов
/ 03 августа 2020

У меня есть модели с отношениями как: -

class Address(models.Model):
    street = models.CharField(max_length=100)
    post_box = models.PositiveIntegerField()

    def __str__(self):
        return self.street


class Employee(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField()
    address = models.ForeignKey(Address, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

и форма: -

class EmployeeForm(forms.ModelForm):
    address = forms.ModelChoiceField(Address.objects.all())

    class Meta:
        model = Employee
        fields = "__all__"

    def save(self, commit=True, *args, **kwargs):
        print('saving employee')
        post_box = kwargs['post_box']
        street = kwargs['street']
        address = Address.objects.create(street=street, post_box=post_box)
        employee = Employee.objects.create(address=address, name=kwargs['name'], age=kwargs['age'])
        return employee

, а форма html: -

<form method="post" action="{% url 'employee' %}">
    {% csrf_token %}
    <div class="form-group">
        <label for="exampleInputEmail1">Name</label>
        <input type="text" name="name" class="form-control" id="name" aria-describedby="emailHelp">
        <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
    </div>
    <div class="form-group">
        <label for="age">Age</label>
        <input type="number" name="age" class="form-control" id="age">
    </div>
    <div class="form-group">
        <label for="street">Street</label>
        <input type="text" name="street" class="form-control" id="street">
    </div>
    <div class="form-group">
        <label for="post_box">Post Box</label>
        <input type="text" name="post_box" class="form-control" id="age">
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

Представление будет выглядеть так: -

class EmployeeView(View):

    def get(self, request):
        form = EmployeeForm()
        return render(request, 'employee.html', context={'form': form})

    def post(self, request):
        data = request.POST
        form = EmployeeForm(data=data)
        if form.is_valid():
            form.save()
            messages.success(request, 'A new Employee Created')
            return render(request, 'employee.html')
        else:
            return render(request, 'employee.html', context={'form':form})

Это просто не сохранит форму. Консоль выдаст ошибку. значит, форма недействительна. так как мне сохранить такие данные? какой подход правильный?

1 Ответ

1 голос
/ 03 августа 2020

вы можете сделать это [Отредактировано]

class AddressForm(forms.ModelForm):
    class Meta:
        model = Address
        fields = "__all__"

class EmployeeForm(forms.ModelForm):
    class Meta:
        model = Employee
        fields = ['name', 'age']

def post(self, request):
        data = request.POST

        address_form = AddressForm(data=data) #check address form
        if address_form.is_valid()

            employee_form = EmployeeForm(data=data) #check employee form
            if employee_form.is_valid():

                adress = address_form.save()  # if both form is valid, save the address
                employee = employee_form.save(comit=False) #  no save , get only instance
                employee.address = address   # assing the address
                employee.save()    # save the  employee
                messages.success(request, 'A new Employee Created')
                return render(request, 'employee.html')
            else:
                print(employee_form.errors)
        else:
            print(address_form.errors)
        else:
            return render(request, 'employee.html', context={'form':form})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...