TransWikia.com

Не сохраняются поля в форме Django

Stack Overflow на русском Asked by mila on August 3, 2020

views.py

from .models import Visitor, Worker, Documentation


def visitor_edit(request, pk):
    visitor = get_object_or_404(Visitor, pk=pk)

    if request.method == "POST":
    #передаём экземпляр visitor в качестве instance форме и при сохранении…
        form = VisitorForm(request.POST, instance=visitor)
        pform = WorkerForm(request.POST)
        dform = DocumentationForm(request.POST)
        if form.is_valid() and pform.is_valid() and dform.is_valid():
            visitor = form.save(commit=False)
            worker = pform.save(commit = False)
            documentation = dform.save(commit = False)
            #visitor.author = request.user
            #visitor.published_date = timezone.now()
            visitor.save()
            worker.save()
            documentation.save()
            return redirect('visitor_detail', pk=visitor.pk)
    else:
    # и когда мы открываем форму для редактирования:
        form = VisitorForm(instance=visitor)
        pform = WorkerForm()
        dform = DocumentationForm()
    return render(request, 'bl/visitor_edit.html', {'form': form, 'pform' : pform, 'dform' : dform})


def visitor_new(request):   
if request.method == "POST":
    form = VisitorForm(request.POST, prefix='form')
    pform = WorkerForm(request.POST, prefix='pform')
    dform = DocumentationForm(request.POST, prefix='dform')

    if form.is_valid() and pform.is_valid() and dform.is_valid():
        visitor = form.save(commit=False)
        worker = pform.save(commit = False)
        documentation = dform.save(commit = False)
        #visitor.author = request.user
        #visitor.published_date = timezone.now()
        visitor.save()
        worker.save()
        documentation.save()
        return redirect('visitor_detail', pk=visitor.pk)
else:

    form = VisitorForm(prefix='form')
    pform = WorkerForm(prefix='pform')
    dform = DocumentationForm(prefix='dform')

    return render(request, 'bl/visitor_edit.html', {'form': form, 'pform' : pform, 'dform' : dform})

visitor_edit.html

{% block content %}
    <h1>Новый посетитель</h1>
    <form method="POST" class="post-form">{% csrf_token %}
        {{ form.as_p }}
        {{ pform.as_p }}
        {{ dform.as_p }}
        <button type="submit" class="save btn btn-default">Сохранить</button>
    </form>
{% endblock %}

forms.py

from django import forms

from .models import Visitor, Worker, Documentation

class VisitorForm(forms.ModelForm):

    class Meta:
        model = Visitor
        fields = ('name_visitor', 'surname_visitor', 'phone', 'address', 'entry_time', 'time_out')



class WorkerForm(forms.ModelForm):

    class Meta:
        model = Worker
        fields = ('name_worker', 'surname_worker' , 'position_worker')


class DocumentationForm(forms.ModelForm):

    class Meta:
        model = Documentation
        fields = ('document_type', 'document_number')

При заполнении формы в итоге сохраняются только поля, которые относятся к модели Visitor и соответственно VisitorForm.
Подскажите, что изменить, чтобы сохранялись поля во всех формах?

One Answer

Вы не провели валидацию форм WorkerForm и DocumentationForm.

Вам нужно проверять каждую форму на is_valid(), а не только VisitorForm.

Так-же добавим префикс к каждой форме.

Код view будет выглядеть примерно следующим образом:

from .models import Visitor, Worker, Documentation

def visitor_new(request):   
    if request.method == "POST":
        form = VisitorForm(request.POST, prefix='form')
        pform = WorkerForm(request.POST, prefixt='pform')
        dform = DocumentationForm(request.POST, prefix='dform')

        if form.is_valid() and pform.is_valid() and dform.is_valid():
            visitor = form.save(commit=False)
            worker = pform.save(commit = False)
            documentation = dform.save(commit = False)
            #visitor.author = request.user
            #visitor.published_date = timezone.now()
            visitor.save()
            worker.save()
            documentation.save()
            return redirect('visitor_detail', pk=visitor.pk)
    else:

        form = VisitorForm(prefix='form')
        pform = WorkerForm(prefixt='pform')
        dform = DocumentationForm(prefix='dform')

    return render(request, 'bl/visitor_edit.html', {'form': form, 'pform' : pform, 'dform' : dform})

Answered by Сергей Чабаненко on August 3, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP