I have a ModelForm:
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['url',]
The Article model has a url field which is unique. I want users to enter a URL.
If the Article already exists, it gets reused. Otherwise, a new instance is
created.
And the corresponding view:
1 @login_required
2 def get_article(request):
3 if request.method == 'POST':
4 # Should I get a new instance here?
5 form = ArticleForm(request.POST, instance=None)
6 if form.is_valid():
7 article, created =
Article.objects.get_or_create(url=form.cleaned_data['url'])
9 # Some more work goes here
10 return redirect(reverse('articles:list'))
11 else:
12 form = ArticleForm()
13 return render(request, 'articles/get_article.html', {'form': form})
The form is validating the uniqueness of the model, which is great. The dilemma
I am having is that I would like to bind the form to the existing instance in
line 4. But at that point, the form has not been cleaned, so I wouldn't want to
hit the database with it.
*What's the proper pattern to do this?*
Thanks a lot!
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-users/b9fc0fed-d8f6-44e8-8687-11d94669d2a0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.