如何在form_valid中保存父对象

时间:2016-04-02 14:54:09

标签: django django-models django-forms

我有一个基于类的视图。我试图用它的关联保存一个对象。我有以下错误:

NOT NULL constraint failed: boxes_suggestion.box_id

更多解释:我有一个SuggestionBox(模型),每个参与者都可以添加评论。它是一种涂鸦克隆。

detail.html

        <h3>{{box.title}}</h3>

<form action="." method="post">{% csrf_token %}
    {{ form.as_p }}
     <input id="box_id_value" type="hidden" name="box_id_value" value='{{box.id}}' />
    <input type="submit" class="btn btn-info" value="Add suggies 1" />
</form>

views.py

class SuggiesForm(FormView):
    '''
    Display the form
    Otherwise
    Process the form
        1-Get the suggestion_box_id
        2-Save the comment associated with that suggestion box.
    '''
    template_name = 'boxes/detail.html'
    form_class = SuggestionForm
    success_url = '/boxes/success'
    box_instance = ''

    def get_context_data(self, **kwargs):
       '''
       Retrieve the id of the Suggestion Box
       '''
       context = super(SuggiesForm, self).get_context_data(**kwargs)
       #Find The appropriate Box so that user can add Suggies
       context['box'] = Box.objects.get(pk=self.kwargs['pk'])
       box_instance = context['box']
       return context

    def form_valid(self, form):
        '''

        '''
        form.save(commit=False)
        #box = box_instance  
        form.box = Box.objects.first()
        form.participant = Suggestion.objects.first()
        form.save()
        return super(SuggiesForm, self).form_valid(form)

models.py

@python_2_unicode_compatible
class Box(models.Model):
    """
    Box model
    """
    def __str__(self):
        return self.title
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)     
    title = models.CharField(max_length=40, blank=True, null=True)
    identify = models.BooleanField(default=False)
    activate = models.BooleanField(default=False)
    created_at = models.DateField(auto_now_add=True)
    updated_at = models.DateField(auto_now=True)
    #expiration_date = models.DateField(auto=Date in Future, blank=True, null=False)
    #slug = AutoSlugField(_('slug'), populate_from="id")
    #url(slug)

@python_2_unicode_compatible
class Participant(models.Model):
    """
    Participant Model
    """
    def __str__(self):
        return  self.email

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)     
    email = models.EmailField(blank=True, null=True, default='anonymous@email.com')
    username = models.CharField(max_length=40, blank=True, null=True)
    box = models.ForeignKey(Box, on_delete=models.CASCADE)
    created_at = models.DateField(auto_now_add=True)
    updated_at = models.DateField(auto_now=True)

@python_2_unicode_compatible
class Suggestion(models.Model):
    """
    For adding comments (or suggestions)
    """
    def __str__(self):
        return self.comment[0:10]

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)     
    comment = models.CharField("",max_length=250, blank=True, null=True)
    box = models.ForeignKey(Participant, on_delete=models.CASCADE)
    created_at = models.DateField(auto_now_add=True)
    updated_at = models.DateField(auto_now=True)

1 个答案:

答案 0 :(得分:1)

您正确使用了commit=False,但随后将属性添加到表单对象本身而不是从保存返回的对象。它应该是:

    object = form.save(commit=False)
    object.box = Box.objects.first()
    object.participant = Suggestion.objects.first()
    object.save()