Good day.

The task is: Add a check that the name entered for the new post is unique.

What and where to add? Searching the internet does not help.

Here is the function itself:

def create_post(request): if not request.user.is_anonymous(): if request.method == "POST": form = { 'text': request.POST["text"], 'title': request.POST["title"] } if form['text'] and form['title']: Article.objects.create(text=form['text'], title=form['title'], author=request.user) article = Article.objects.get(title=form['title']) return redirect('get_article', article_id=article.id) else: form['errors'] = u'Не все поля заполнены' return render(request, 'create_post.html', {'form': form}) else: return render(request, 'create_post.html', {}) else: raise Http404 

upd: yes, I use an application that django uses; sqlite3 is connected as a database; as I understood, the task is that if the name is non-unique, then display a phrase like "There is already such an article, try again"; I will not be able to provide links from the Internet, since I have not found anything suitable; and, to be honest, I don’t even know what might be appropriate - this is a task from the curriculum and besides this, nothing else is given there

I tried using get_or_create, but I got an error (get (); I returned 2! Lookup parameters were {'title': u'1 '})

1 answer 1

The uniqueness of the field is best organized at the model and database

 #models.py class Article(models.Model): title = models.CharField(max_length=300, unique=True) #forms.py class ArticleForm(form.ModelForm) class Meta: model = Article fields = ['title', ] 

http://djbook.ru/rel1.9/topics/forms/modelforms.html http://djbook.ru/rel1.9/ref/models/fields.html#unique