CreateOrUpdateView for Django Models -
in models have foreignkey relationship this:
class question(models.model): question = models.textfield(null=false) class answer(models.model): question = models.foreignkey(question, related_name='answer') user = models.foreignkey(user) class meta: unique_together = (("question", "user"),)
the corresponding url submit answer contains id of question, this:
url(r'^a/(?p<pk>\d+)/$', answerquestion.as_view(), name='answer-question'),
with user coming self.request.user, trying createorupdateview
, allow convenient navigation user , url scheme.
until tried with:
class answerquestion(loginrequiredmixin, createview):
and add initial value, isn't clean because of pk. updateview
run problems because have set default values form.
has done this? i'd rather avoid having create , update view same answer.
the updateview
, createview
not different, difference updateview
sets self.object
self.get_object()
, createview
sets none
.
the easiest way subclass updateview
, override get_object()
:
answerquestionview(loginrequiredmixin, updateview): def get_object(queryset=none): if queryset none: queryset = self.get_queryset() # easy way right question url parameters: question = super(answerquestionview, self).get_object(question.objects.all()) try: obj = queryset.get(user=self.request.user, question=question) except objectdoesnotexist: obj = none return obj
returns right answer if exists, none
if not. of course add attributes need class, model
, form_class
etc.
Comments
Post a Comment