Tufan
Tufan

Reputation: 55

How to update data in Django when getting unique field error

first thing first I'm sorry for my bad english. I hope so u can understand me easily. I'm trying to make a blog with django but there's a place I can't solve. I used unique slug field instead of id for url, whenever I want to update the data I get the UNIQUE constraint failed: post_post.url_text error (url_text is slugfield variable name). Here is the my model,

enter image description here

and the Form looks like this,

enter image description here

At first I followed a way to update the data here:

@login_required(login_url='login')
def post_update(request, url_text=None):
post = get_object_or_404(Post, url_text=url_text)
form = PostWrite(request.POST or None, instance=post)

if form.is_valid():
    post_author = request.user
    post_title = form.cleaned_data.get('post_title')
    post_content = form.cleaned_data.get('post_content')
    post_tags = form.cleaned_data.get('tags')
    post = Post(post_author=post_author, post_title=post_title, post_content=post_content, tags=post_tags)
    post.save()
    

context = {
    'post': post,
    'form': form,
}

return render(request, 'post/re_write.html', context)

and I got the error I mentioned at the beginning of the post. Then I found a solution like this in the forums,

if form.is_valid():
    form.save()

This time it does not give any error but does not update the data. Despite hours of research, for some reason I could not find a tangible solution. I wanted to ask you esteemed coders as a last resort and I look forward to your help.

Upvotes: 2

Views: 1258

Answers (1)

schillingt
schillingt

Reputation: 13731

The issue is that you're creating a new post with the following code while this view appears to be an update:

post = Post(post_author=post_author, post_title=post_title, post_content=post_content, tags=post_tags)
post.save()

Instead, you should utilize the modelform you're already using to save the changes to the instance:

if form.is_valid():
    post = form.save()

I'm guessing maybe because you weren't capturing the post from form.save() the rendered template appeared to not have the data updated because the instance passed into the template was from before the changes.

Other issue:

You're overriding the save method, but not always calling super().save. This means that you're only saving the post when the url_text property is not set. Instead always call super().save

def save(self, *args, **kwargs):
    if ...
       # other stuff
    super().save(*args, **kwargs)

Upvotes: 2

Related Questions