简体   繁体   中英

(Django) (Foreign Key Issues) model.person_id May not be NULL

I know this seems to be an over-asked question in the Django circles but I'm afraid to say that i've not yet found the solution to this.

My Model -

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

I've tried overriding the save_model() in the admin definition and also overriding the save() in the Form but nothing seems to work.

If you were to auto add data into a ForeignKey or OneToOneField column to a 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()} 

I got the answer!!! I feel good!

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

This goes into the view much like Ignacio said, only commit = False being a critical statement for it to save an instance without throwing an exception. Thanks all who helped!!
Cheers

In your PersonalForm, you can subclass your save() function, so the appropriate data is added, something like this:

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

    class Meta:
        model = Personal

see this

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

this ok but have problem with sqlite , change it to postgresql its ok. ( its for my code , change it to your status )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM