1

I am writing a control view function edit_article to update fields of title and content of model table Article:

To update the title and content, I employed article=form.save

def edit_article(request, pk):
    article = Article.objects.get(pk=pk)

    if request.method == "POST":
        form = ArticleForm(data=request.POST)
        print(request.POST)
        if form.is_valid():
           article = form.save()

It reports error when issue submitting

django.db.utils.IntegrityError: (1048, "Column 'owner_id' cannot be null")

I did not change owner_id, just keep it as its previous state.

The problem is solved by explicitly re-assign attribute:

    if form.is_valid():
        # article = form.save()
        article.title = form.cleaned_data['title']
        article.content = form.cleaned_data['content']
        article.save()

The model Article

class Article(models.Model):
    STATUS = (
        (1,  'normal'),
        (0, 'deleted'),
    )
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    block = models.ForeignKey(Block, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    content = models.TextField() # set the widget
    status = models.IntegerField(choices=STATUS)
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ("id",)

    def __str__(self):
        return self.title

Why form.save() failed as a shortcut?

2
  • if that, should manually add article.owner=article.owner_id form.save() @Mate Commented Jul 10, 2018 at 3:14
  • the owner was not changed. Commented Jul 10, 2018 at 3:15

1 Answer 1

2

If you want to update existing record, you should pass instance object of that model to the form.

So your code would change to

if request.method == "POST":
    form = ArticleForm(instance=article, data=request.POST)
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.