Django表单不会保存到数据库,也不会在POST时正确转发

时间:2017-05-31 18:56:54

标签: python django django-models django-forms views

我无法弄清楚为什么我的一张表格在提交时不会保存或转发。

这是模型:

<!-- secondary external storage with path /storage/extSdCard -->
<root-path path="/storage/extSdCard/Android/data/YOUR_PACKAGE/files/" name="extSdCard" />

<!-- secondary external storage with path /storage/sdcard1  -->
<root-path path="/storage/sdcard1/Android/data/YOUR_PACKAGE/files/" name="sdcard1" />

这是表格:

class Offer(models.Model):
    """ local offers traveler to take her out based on the trips listed by traveler """
    local = models.ForeignKey(User, related_name='local_offers_excursion')
    message = models.CharField(max_length=500)
    trip = models.ForeignKey(Excursion, related_name='traveler_trip')
    traveler_approval = models.BooleanField(blank=True)

这是另一个相关模型(Excursion):

class OfferExcursionForm(forms.ModelForm):
    def __init__(self, traveler=None, city=None, **kwargs):
        super(OfferExcursionForm, self).__init__(**kwargs)
        if traveler and city:
            self.fields['trip'].queryset = Excursion.objects.filter(traveler=traveler)
            self.fields['trip'].queryset = Excursion.objects.filter(city=city)
    class Meta:
        model = Offer
        exclude = ('local', 'traveler_approval')

这是观点:

class Excursion(models.Model):
    """traveler lists his trips so local could see them and possibly offer to take him out"""
    traveler = models.ForeignKey(User, related_name='traveler_lists_excursion')
    city = models.ForeignKey(City, related_name='visited_city', blank=True, null=True) #Each excursion is connected to one City.
    city_search_text = models.CharField(blank=True, max_length=300)
    message = models.CharField(max_length=500)#message to all locals of that city "Hey good people of Edinburgh!"
    date = models.DateField()

    def __str__(self):
        return self.traveler.first_name.title() + " " + self.traveler.last_name.title() + "'s trip to " + self.city.name + " on " + str(self.date)

最后这是模板:

def offerexcursion(request, username):
    traveler = User.objects.get(username=username)
    if request.method == 'POST':
        offer_excursion_form = OfferExcursionForm(request.POST)
        if offer_excursion_form.is_valid():
            offer = offer_excursion_form.save(commit=False)
            offer.local = request.user
            offer.traveler_approval = True
            offer.save()
            if 'next' in request.GET:
                return redirect(request.GET['next'])
        else:
            print(offer_excursion_form.errors)
    else:

        offer_excursion_form = OfferExcursionForm(traveler=traveler, city=request.user.profile.city)
    return render(request, '<app_name>/offerexcursion.html', {'offer_excursion_form':offer_excursion_form})

提交表单后,不保存任何Offer对象,而是再次转发到表单而不是仪表板页面。它转发到这个链接:

<h1>Offer an Excursion to a Traveler</h1>

<form method="post" action="?next=/dashboard/" enctype="multipart/form-data">
            {% csrf_token %}

    {{ offer_excursion_form|crispy }}

    <input type="submit" value="Submit" class="btn btn-primary btn-lg "/>

</form>

而不是:

http://127.0.0.1:8000/offerexcursion/<username>/?next=/dashboard/

1 个答案:

答案 0 :(得分:2)

您已更改__init__方法的签名。

def __init__(self, traveler=None, city=None, **kwargs):

因此,如果您有OfferExcursionForm(request.POST),则相当于OfferExcursionForm(traveler=request.POST)

您可以将数据作为关键字参数传递:

if request.method == 'POST':
    OfferExcursionForm(data=request.POST)

但是,您可能希望提供travelercity,否则表单将使用未经过滤的trip查询集进行验证。

if request.method == 'POST':
    offer_excursion_form = OfferExcursionForm(traveler=traveler, city=request.user.profile.city, data=request.POST)

最后,您的第二个查询集会替换第一个查询集,因此您不会在traveler上对其进行过滤。

    if traveler and city:
        self.fields['trip'].queryset = Excursion.objects.filter(traveler=traveler)
        self.fields['trip'].queryset = Excursion.objects.filter(city=city)

你可能想要

if traveler and city:
    self.fields['trip'].queryset = Excursion.objects.filter(city=city, traveler=traveler)