Как обрабатывать две формы Django в одном представлении?

У меня есть представление, которое содержит две формы Django. Раньше они работали, но теперь та из них, которая находится под верхней, не работает. Я пробовал менять порядок форм, и та форма, которая находится сверху, работает, а другая ничего не делает после отправки.

Я попробовал изменить свои формы так, чтобы они напоминали этот пример if request.method == "POST" and "selectgenderform" in request.POST:, но это не сработало (формы ничего не сделали).

Кто-нибудь знает, как решить эту проблему?

часть файла views.py

def listing(request, id):
    #gets listing
    listing = get_object_or_404(Listings.objects, pk=id)
    #code for comment and bid forms
    listing_price = listing.bid
    sellar = listing.user
    comment_obj = Comments.objects.filter(listing=listing)
    #types of forms
    comment_form = CommentForm()
    bid_form = BidsForm()

    #code for the bid form
    bid_obj = Bids.objects.filter(listing=listing)
    other_bids = bid_obj.all()
    max_bid =0
    for bid in other_bids:
        if bid.bid > max_bid:
            max_bid = bid.bid
    #checks if request method is post for all the forms
    if request.method == "POST":
        print(request.POST)
        #forms
        comment_form = CommentForm(request.POST)
        bid_form = BidsForm(request.POST)
        #checks if bid form is valid
        if bid_form.is_valid():
            print('!!!!!form is valid')
            #print("bid form is valid")
            print(listing.bid)
            new_bid = float(bid_form.cleaned_data.get("bid"))
            if (new_bid >= listing_price) or (new_bid > max_bid):
                bid = bid_form.save(commit=False)
                bid.listing = listing
                bid.user = request.user
                bid.save()
                print("bid form is saving")
            else: 
                print(bid_form.errors)
                print("bid form is not saving")
                return render(request, "auctions/listing.html",{
                    "auction_listing": listing,
                    "form": comment_form,
                    "comments": comment_obj,
                    "bidForm": bid_form,
                    "bids": bid_obj,
                    "message": "Your bid needs to be equal or greater than the listing price and greater than any other bids."
                })
        else:
            print(bid_form.errors, bid_form.non_field_errors)
            print(bid_form.errors)
            return redirect('listing', id=id)

        #checks if comment form is valid
        if comment_form.is_valid():
            print("comment is valid")
            comment = comment_form.save(commit=False)
            comment.listing = listing
            comment.user = request.user
            comment.save()
        else:
            return redirect('listing', id=id)

В настоящее время форма предложения работает, потому что она находится сверху, но если изменить порядок, то вместо нее будет работать форма комментария, а форма предложения - нет.

forms.py

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comments
        fields = ['comment']
        widgets = {'comment': forms.TextInput(attrs={'placeholder': 'Add a comment about this listing here.', 'class' : 'form-control'})}

class BidsForm(forms.ModelForm):
    class Meta:
        model = Bids
        fields = ['bid']
        widgets = {'title': forms.NumberInput(attrs={'placeholder': 'Add a bid for this listing here.', 'class' : 'form-control'})}

У вас проблема с потоком. Если пользователь отправляет комментарий, то ваша форма bid_form недействительна, и поэтому она переходит в раздел 'else' if bid_form.is_invalid(), который перенаправляет на другую страницу, прежде чем форма комментария будет проверена. К счастью, они оба имеют одинаковый оператор else, поэтому вы можете использовать elif, а не два else...ifs

Предполагая, что за один раз можно отправить только одну форму, попробуйте следующее:

if bid_form.is_valid():
     ... #remove the else: statement
elif comment_form.is_valid():
     ...
else:
    return redirect('listing', id=id)

Если обе формы могут быть отправлены одновременно и должны быть обработаны обе, вам нужно установить флаг, например:

if bid_form.is_valid():
    ...
else:
    redirect_later = True
if comment_form.is_valid():
    ...
else:
    redirect_later = True
if redirect_later:
    return redirect('listing', id=id)
Вернуться на верх