简体   繁体   中英

Django not saving form data

I've made a simple test django project that's a simple list of posts. And I'm trying to add functionality to update a post. Everything seems to be working, except the edits aren't saved to the database.

I've checked the cleaned data to see if the updated data is coming through, and it is, but the save() function doesn't seem to actually do anything.

models.py

class Block(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(unique=True, max_length=140, null=True, blank=True)
    content = models.TextField()

    def save(self, *args, **kwargs):
        if self.slug is None:
            self.slug = get_unique_slug(self, 'title', 'slug')
            super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse("bulkapp:one_view", kwargs={"slug_id": self.slug})

    def __str__(self):
        return self.title

views.py

def edit_block_view(request, slug_id):
    single_block_query = get_object_or_404(Block, slug=slug_id)
    update_form_query = BlockForm(request.POST or None, instance=single_block_query)
    if update_form_query.is_valid():
        update_form_query.save()
        return redirect('bulkapp:one_view', slug_id=slug_id)
    return render(request, 'bulkapp/update.html', {'update_form': update_form_query})
<form class="form-container" method="POST">
  {% csrf_token %}
  {{update_form.as_p}}
  <input type="submit" value="Edit">
</form>

Edit:

forms.py

class BlockForm(forms.ModelForm):
    class Meta:
        model = Block
        fields = [
            "title",
            "slug",
            "content",
        ]

The redirect fires as expected, but no changes are saved, and no error messages are written to the console. Any help would be much appreciated.

问题是我的save()函数中的super().save(*args, **kwargs)的缩进,如果该段不为null,则缩进不会执行。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM