R
R
rumak2017-07-20 14:37:04
Django
rumak, 2017-07-20 14:37:04

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)

forms.py
class ExtraContactForm(ModelForm):
    class Meta:
        model = ExtraContact
        exclude = ()

ExtraContactFormset = inlineformset_factory(Extra, ExtraContact, form=ExtraContactForm, extra=1)

views.py
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,
    })

list_contacts.html
{% 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 %}

contacts_form.html
{% 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 %}

Now, when opening the list_contacts.html page, the error 'ModelBase' object is not iterable ' pops up , and when opening contacts_form.html Page not found .

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dimonchik, 2017-07-20
@rumak

start with examples here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question