gpt4 book ai didi

jquery - Django - CreateView 不保存带有嵌套表单集的表单

转载 作者:行者123 更新时间:2023-12-03 22:05:50 29 4
gpt4 key购买 nike

我正在尝试采用一种使用 Django-Crispy-Forms 布局功能保存带有主表单的嵌套表单集的方法,但我无法保存它。我正在关注this代码示例项目,但无法验证表单集以保存数据。如果有人能指出我的错误,我将非常感激。我还需要在 EmployeeForm 的同一 View 中添加三个内联。我尝试了 Django-Extra-Views 但无法使其工作。如果您建议为同一 View 添加多个内联(例如大约 5 个),我将不胜感激。我只想实现一个用于创建 Employee 及其内联的页面,例如 Education、Experience、Others。下面是代码:

型号:

class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employees',
null=True, blank=True)
about = models.TextField()
street = models.CharField(max_length=200)
city = models.CharField(max_length=200)
country = models.CharField(max_length=200)
cell_phone = models.PositiveIntegerField()
landline = models.PositiveIntegerField()

def __str__(self):
return '{} {}'.format(self.id, self.user)

def get_absolute_url(self):
return reverse('bars:create', kwargs={'pk':self.pk})

class Education(models.Model):
employee = models.ForeignKey('Employee', on_delete=models.CASCADE, related_name='education')
course_title = models.CharField(max_length=100, null=True, blank=True)
institute_name = models.CharField(max_length=200, null=True, blank=True)
start_year = models.DateTimeField(null=True, blank=True)
end_year = models.DateTimeField(null=True, blank=True)

def __str__(self):
return '{} {}'.format(self.employee, self.course_title)

查看:

class EmployeeCreateView(CreateView):
model = Employee
template_name = 'bars/crt.html'
form_class = EmployeeForm
success_url = None

def get_context_data(self, **kwargs):
data = super(EmployeeCreateView, self).get_context_data(**kwargs)
if self.request.POST:
data['education'] = EducationFormset(self.request.POST)
else:
data['education'] = EducationFormset()
print('This is context data {}'.format(data))
return data


def form_valid(self, form):
context = self.get_context_data()
education = context['education']
print('This is Education {}'.format(education))
with transaction.atomic():
form.instance.employee.user = self.request.user
self.object = form.save()
if education.is_valid():
education.save(commit=False)
education.instance = self.object
education.save()

return super(EmployeeCreateView, self).form_valid(form)

def get_success_url(self):
return reverse_lazy('bars:detail', kwargs={'pk':self.object.pk})

表格:

class EducationForm(forms.ModelForm):
class Meta:
model = Education
exclude = ()
EducationFormset =inlineformset_factory(
Employee, Education, form=EducationForm,
fields=['course_title', 'institute_name'], extra=1,can_delete=True
)

class EmployeeForm(forms.ModelForm):

class Meta:
model = Employee
exclude = ('user', 'role')

def __init__(self, *args, **kwargs):
super(EmployeeForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_tag = True
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-md-3 create-label'
self.helper.field_class = 'col-md-9'
self.helper.layout = Layout(
Div(
Field('about'),
Field('street'),
Field('city'),
Field('cell_phone'),
Field('landline'),
Fieldset('Add Education',
Formset('education')),
HTML("<br>"),
ButtonHolder(Submit('submit', 'save')),
)
)

自定义布局对象示例:

from crispy_forms.layout import LayoutObject, TEMPLATE_PACK
from django.shortcuts import render
from django.template.loader import render_to_string

class Formset(LayoutObject):
template = "bars/formset.html"

def __init__(self, formset_name_in_context, template=None):
self.formset_name_in_context = formset_name_in_context
self.fields = []
if template:
self.template = template

def render(self, form, form_style, context, template_pack=TEMPLATE_PACK):
formset = context[self.formset_name_in_context]
return render_to_string(self.template, {'formset': formset})

表单集.html:

{% load static %}
{% load crispy_forms_tags %}
{% load staticfiles %}

<table>
{{ formset.management_form|crispy }}

{% for form in formset.forms %}
<tr class="{% cycle 'row1' 'row2' %} formset_row-{{ formset.prefix }}">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field|as_crispy_field }}
</td>
{% endfor %}
</tr>
{% endfor %}

</table>
<br>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src="{% static 'js/jquery.formset.js' %}">
</script>
<script type="text/javascript">
$('.formset_row-{{ formset.prefix }}').formset({
addText: 'add another',
deleteText: 'remove',
prefix: '{{ formset.prefix }}',
});
</script>

终端和/或其他方面没有错误。非常感谢您的帮助。

最佳答案

您当前没有在 CreateView 中正确处理表单集。该 View 中的 form_valid 将仅处理父表单,而不处理表单集。您应该做的是重写 post 方法,并且需要验证表单以及附加到它的任何表单集:

def post(self, request, *args, **kwargs):
form = self.get_form()
# Add as many formsets here as you want
education_formset = EducationFormset(request.POST)
# Now validate both the form and any formsets
if form.is_valid() and education_formset.is_valid():
# Note - we are passing the education_formset to form_valid. If you had more formsets
# you would pass these as well.
return self.form_valid(form, education_formset)
else:
return self.form_invalid(form)

然后你像这样修改form_valid:

def form_valid(self, form, education_formset):
with transaction.atomic():
form.instance.employee.user = self.request.user
self.object = form.save()
# Now we process the education formset
educations = education_formset.save(commit=False)
for education in educations:
education.instance = self.object
education.save()
# If you had more formsets, you would accept additional arguments and
# process them as with the one above.
# Don't call the super() method here - you will end up saving the form twice. Instead handle the redirect yourself.
return HttpResponseRedirect(self.get_success_url())

您当前使用的 get_context_data() 方式不正确 - 完全删除该方法。它只能用于获取用于渲染模板的上下文数据。您不应该从 form_valid() 方法中调用它。相反,您需要将表单集从 post() 方法传递给此方法,如上所述。

我在上面的示例代码中留下了一些额外的注释,希望能帮助您解决这个问题。

关于jquery - Django - CreateView 不保存带有嵌套表单集的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60354976/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com