Answer the question
In order to leave comments, you need to log in
Django. What is the correct way to use formset?
The task before me was to display a form in which two fields should be line by line, in one of which I enter the name of the means of communication (telegram, viber, etc.), and in the other the data by which you can find a person in one means or another. At the same time, it should be possible to delete and add lines with these same fields. Here is what I have already done, based on the official documentation:
models.py
class Extra(models.Model):
extra = models.CharField(max_length=100)
class ExtraContact(models.Model):
claim = models.ForeignKey(Extra)
text = models.CharField(max_length=255)
class ExtraContactForm(ModelForm):
class Meta:
model = ExtraContact
exclude = ()
ExtraContactFormset = inlineformset_factory(Extra, ExtraContact, form=ExtraContactForm, extra=1)
def edit_contacts(request, pk):
extra = get_object_or_404(Extra, pk=pk)
extra1 = ExtraContactFormset(request.POST, instance=extra)
if request.method == 'POST':
if extra1.is_valid():
extra = extra1.save(commit=False)
extra.save()
return redirect('job:list_contacts', pk=extra.pk)
else:
extra1 = ExtraContactFormset(instance=extra)
return render(request, 'job/contacts_form.html', {
'extra1': extra1,
})
{% extends 'job/base.html' %}
{% block content %}
<h1>Контакты:</h1>
<p>{{ extra }}</p>
<a class="btn btn-default" href="{% url 'job:edit_contacts' pk=contact.pk %}"><span class="glyphicon glyphicon-pencil">Изменить</span></a>
{% endblock %}
{% extends 'job/base.html' %}
{% load staticfiles %}
{% block content %}
{% if message %}
<p>{{ message }}</p>
{% endif %}
<h1>Редактирование информации о контактах</h1>
<div class="forms">
<div class="form2">
<h2>Extra</h2>
<form method="POST" class="edit-contacts">{% csrf_token %}
{{ extra1.management_form }}
{{ extra1.as_p }}
<button type="submit" class="save btn btn-default">Сохранить</button>
</form>
</div>
</div>
{% endblock %}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question