Django' unicode'对象没有属性'字段'

时间:2014-07-04 02:31:28

标签: django django-forms django-crispy-forms

我最近在我的django项目中添加了crispy_forms,这导致我出现'unicode' object has no attribute 'field'错误。无法弄清楚原因。

models.py

class Trip(models.Model):
    location_name = models.CharField(max_length=60)
    trip_date = models.DateField()
    trip_rating = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)])
    fishing_vehicle = models.ForeignKey(FishingVehicle)
    water_body = models.ForeignKey(WaterBody)
    user = models.ForeignKey(User)
    def __unicode__(self):
        return self.location_name

views.py

@login_required
def logtrip(request):
    if request.method == 'POST':
        form = forms.TripForm(request.POST)
        if form.is_valid():
            trip = form.save(commit=False)
            trip.user = request.user
            trip.save()
            return redirect('home')
        else:
            print form.errors
    else:
        form = forms.TripForm()
    return render_to_response('logtrip.html', {'form': form}, context_instance=RequestContext(request))

forms.py

class TripForm(ModelForm):
    CHOICES = (('1', 'None',), ('2', 'Below Average Amount',), ('3', 'Average Amount',), ('4', 'Above Average Amount',), ('5', 'A Lot/Limited Out',))
    trip_rating = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES, label='Fish Caught')
    class Meta:
        model = Trip
        exclude = ['user']
        widgets = {'trip_date': forms.DateInput(attrs={'class':'datepicker'})}

logtrip.html

{% extends "base.html" %}

{% load crispy_forms_tags %}

{% block content %}

<div class="container">
  <!-- Example row of columns -->
  <div class="row">
    <div class="col-md-4">
      <form action="/logtrip/" method="post">
        {% csrf_token %}
        {{ form.as_p|crispy }}
        <input type="submit" value="Submit" />
      </form>
    </div>
  </div>
</div>

{% endblock %}

删除|crispy过滤器后,一切正常。

1 个答案:

答案 0 :(得分:10)

对于其他任何人收到此错误,我的问题已通过将{{ form.as_p|crispy }}更改为{{ form|crispy }}来解决。