form.is_valid()始终在views.py中返回false

时间:2017-11-04 17:16:52

标签: django

form.is_valid()始终失败。我尝试了不同的方法来处理它,但每次都失败并返回false。请帮助弄清楚代码中的错误。

models.py看起来像这样 -

class Album(models.Model):
    album_name = models.CharField(max_length=50, primary_key=True)
    place = models.CharField(max_length=50)
    date_pub = models.DateTimeField('date published')

    def __str__(self):
        return self.album_name

class Images(models.Model):
    album_name = models.ForeignKey(Album, db_column='album_name')
    image_name = models.CharField(max_length=40)
    image = models.FileField(null=True, blank=True)
    upload_dt = models.DateTimeField(auto_now=True, auto_now_add=False)
    like_cntr = models.IntegerField(default=0)
    description = models.CharField(max_length=200, null=True)

    def __str__(self):
        return self.image_name

forms.py是 -

class ImagesForm(forms.ModelForm):
    description = forms.CharField(required=False)

    class Meta:
        model = Images
        fields = ('album_name', 'description',)

views.py是 -

class RandomView(TemplateView):
    template_name = 'photos/random.html'

    def get(self, request, album_name):
        images = Images.objects.filter(album_name=album_name)
        context = {'album_name':album_name, 'images' : images}
        return render(request, 'photos/random.html', context)

    def post(self, request, album_name):
        form = ImagesForm(request.POST)
        if form.is_valid():
            form.save(commit=False)
            text = form.cleaned_data['description']
            Images.album_name = album_name
            form.save()
        else: 
            return HttpResponse("Failed to save")

模板是 -

<h3>Album : {{album_name }}</h3>
{% for image in images %}
<img src="{{image.image.url}}" height="400" width="500">
<h4> {{image.image_name }}</h4>

<form method="POST" action=""> {% csrf_token %}
    <span class = "badge">Description</span>
    {% if image.description  %}
        <h4> {{image.description }} </h4>
    {% else %}
        <input type="text" value=" "/>
        <button type="Submit">Submit</button>
    {% endif %}
</form>
{% endfor %}

2 个答案:

答案 0 :(得分:0)

输入标记的必要名称和ID属性在哪里?

<input type="text" name="description" id="id_description"/>

答案 1 :(得分:0)

请尝试上面的{{ form.errors }}&#34;表单&#34;标签。首先检查错误到达的位置。然后根据该错误找到解决方案。如果它有用,请告诉我。