Wouter Mellema
Wouter Mellema

Reputation: 3

Django Modelform OneToOneFielld

I'm currently writing a system in Django where I'd like to save a user at the same time i'm creating another model.

Model Code:

class MyModel(models.Model):
    user = models.OneToOneField(User,related_name="profile",primary_key=True)
    custom_field = models.CharField(...)

The model is more elaborate of course, but it shows the setup of the whole thing.

Example form:

First name: [input]
Last name: [input]
Email: [input]
Password: [pass_input]
Custom Text: [text_input]

Is this at all possible using a ModelForm?

Upvotes: 0

Views: 38

Answers (2)

joshlsullivan
joshlsullivan

Reputation: 1500

Yes. In your forms.py file, add this code:

class UserForm(ModelForm):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')

class ProfileForm(ModelForm):
    class Meta:
        model = MyModel
        fields = ('customfield1', 'customfield2')

EDIT Here is a great tutorial on to do this: https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

Upvotes: 0

souldeux
souldeux

Reputation: 3755

Yes; you could create a ModelForm that corresponds to MyModel:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ['custom_field']

Then in your view, you could interrupt the save of this form using commit=False (https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#the-save-method) and set the user value of your new object manually. For example, you could set user = request.user like so:

if form.is_valid():
    instance = form.save(commit = False)
    instance.user = request.user 
    instance.save()
    form.save_m2m() #if your form has any m2m data to save

Upvotes: 1

Related Questions