1π
I donβt understand which
get_or_create
does not see that I M on editing an existing instance.
It does see this, but you instruct it the wrong way. What you basically say is:
Create a new article with the given title and content and only if both the title and the content are the same as one in the database, you should get that record.
If the content is thus different, but the title the same, then it will raise an error.
You can however simply get the article if the exists one with the same title, you do this by moving the content
to the defaults=β¦
parameter in the .get_or_create(β¦)
call [Django-doc]:
Article.objects.get_or_create(
title=article_form.cleaned_data['title'],
defaults={'content': article_form.cleaned_data['content']}
)
this will however not update the record. Indeed, if an Article
with the same title already exists, we leave the Article
the way it is. We can use .update_or_create(β¦)
[Django-doc] to update the object in caset the article already exists:
Article.objects.update_or_create(
title=article_form.cleaned_data['title'],
defaults={'content': article_form.cleaned_data['content']}
)
But both do not look what you probably want to do. Imagine that the user wants to rename an article, then with the given logic, it will create a new article, and thus now there are two articles. Furthermore if that person changes the name, and it happens to be that there is already an article with the given name, then they will (accidently) override the content of that article.
What you probably want to do is update the article
, so:
from django.shortcuts import redirect
def Article_Edit(request, articleid):
article = Article.objects.get(pk=articleid)
form = EditForm(instance=article)
if request.method == 'POST':
article_form = CreateForm(request.POST, instance=article)
if article_form.is_valid():
article_form.save()
messages.success(request, 'article successfully added')
return redirect('Article_List')
return render(request, 'wikis/article_create.html', {'form': form})
If the CreateForm
is a ModelForm
, it will normally check the uniqness constraint.