(Django) (External key questions) model.person_id Cannot be NULL

I know this seems like a too complicated question in Django circles, but I'm afraid to say that I have not yet found a solution to this.

My model is

from djago.... import User
class InfoPersonal(models.Model):
...
person = models.OneToOneField(User)

I tried to override save_model () in the admin definition and also override save () on the form, but nothing works.

If you were to automatically add data to the ForeignKey or OneToOneField column to the model, how would you do it?

  def profile_creation_personal(request):
    if request.method == 'POST': # If the form has been submitted... 
        form = PersonalForm(request.POST) # A form bound to the POST data 
        # form.person = request.user
        if form.is_valid(): # All validation rules pass 
            # Process the data in form.cleaned_data 
            # ... 
            form.save()
            return HttpResponseRedirect('/done') # Redirect after POST
    else: 
            form = PersonalForm() # An unbound form 
    return render_to_response('info/personal/profile_create.html', { 'form': form,})


class PersonalForm(ModelForm):
    #hometown_id = ModelChoiceField(queryset=InfoReferenceCities.objects.all(),empty_label=None)
    def save(self, *args, **kwargs):
        self.person = request.user
        super(PersonalForm, self).save(*args, **kwargs)
    class Meta:
        model = InfoPersonal
        exclude = ('person',)
        widgets = {'dateofbirth' :  SelectDateWidget()} 
+3
source share
3 answers

I got an answer !!! I feel myself good!

personal = form.save(commit = False)
personal.person = request.user
personal.save()

, , commit = False - . , !

+1

PersonalForm save(), , :

class PersonalForm(ModelForm):
    def save(self, *args, **kwargs):
        self.person = request.user
        super(PersonalForm, self).save(*args, **kwargs)

    class Meta:
        model = Personal
0

see this

parent = models.ForeignKey('self', blank=True, null=True, verbose_name=_("parent"))

this is normal, but the problem is with sqlite, change it to postgresql, this is normal. (its for my code, change it to your status)

0
source

All Articles