Django表单无法显示

时间:2013-04-29 22:01:34

标签: django forms django-forms

我有一个简单的Django表单通过视图传递给它应该显示的模板,但是,由于我 - 在5小时后 - 未能推断出来的原因,它没有。任何和所有的想法都欢迎,我很想解决这个令人厌烦的问题。

我有以下Django表单:

class BandAddToCartForm(forms.Form):
    LENGTH_CHOICES = ( ('XS', 'XS'),
                       ('S', 'S'),
                       ('M', 'M') )
    length = forms.Select(choices=LENGTH_CHOICES)
    quantity = forms.IntegerField(widget=forms.HiddenInput())
    band_sku = forms.CharField(widget=forms.HiddenInput())

    # override the default __init__ so we can set the request
    def __init__(self, request=None, *args, **kwargs):
        self.request = request
        super(BandAddToCartForm, self).__init__(*args, **kwargs)

    # custom validation to check for cookies
    def clean(self):
        if self.request:
            if not self.request.session.test_cookie_worked():
                raise forms.ValidationError("Cookies must be enabled.")
        return self.cleaned_data

通过以下视图传递给模板:

def show_custom_watches(request,
                        template_name="catalog/custom_watches.html"):
    bands = Band.objects.all()
    page_title = "Custom Watches"
    meta_keywords = "custom, watches, beaded"
    meta_description = "Custom beaded watches for every occassion."
    return render_to_response(template_name, 
                              locals(), 
                              context_instance=RequestContext(request))
    # need to evaluate the HTTP method
    if request.method == 'POST':
        #add to cart, create bound form
        postdata = request.POST.copy()
        form = BandAddToCartForm(request, postdata)
        #check if posted data is valid
        if form.is_valid():
            #add to cart and redirect to cart page
            cart.add_band_to_cart(request)
            # if test cookie worked, get rid of it
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            url = urlresolvers.reverse('show_cart')
            return HttpResponseRedirect(url)
    else:
        # it's a GET, create the unbound form. Note request as a kwarg
        band_form = BandAddToCartForm(request=request, label_suffix=':')

        # set the test cookie on our first GET request
        request.session.set_test_cookie()
        return render_to_response("catalog/custom_watches.html",
                                  locals(), 
                                  context_instance=RequestContext(request))

最后,这里是模板的相关位,表单无法显示:

{% for b in bands %}
    <div class="watch_list_item">
        <img class="" src="{{ MEDIA_URL }}images/bands/thumbnails/{{ b.image }}" alt="{{ b.name }}" />
        <div class="watch_form_area">
            <p>{{ b.name }}</p>
            <form method="post" action="." class="cart">{% csrf_token %}
                {{ band_form.as_p }}
                <input type="submit" value="Add To Cart" name="add_product" alt="Add To Cart" class="add_to_cart_button" id="add_only_product" />
            </form>
        </div>
    </div>
{% endfor %}

“添加到购物车”按钮按预期显示,但长度选择器完全无法显示。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

第一个

return render_to_response(template_name, 
                          locals(), 
                          context_instance=RequestContext(request))

总是在您初始化表单之前发生,删除它并且它应该有效。