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

血红的双手。 提交于 2019-12-05 02:20:18

问题


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()} 

回答1:


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




回答2:


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



回答3:


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 )



来源:https://stackoverflow.com/questions/5281935/django-foreign-key-issues-model-person-id-may-not-be-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!