У меня есть модели с отношениями как: -
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})
Это просто не сохранит форму. Консоль выдаст ошибку. значит, форма недействительна. так как мне сохранить такие данные? какой подход правильный?