Home > Software design >  How can I save a django form
How can I save a django form

Time:01-20

So I want to save a Biographie for each new created User. The user can enter his Bio and it will the it to his Profile.

For this I created a model with OneToOneField

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver


class Profile(models.Model):
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, null=True, blank=True)
    bio = models.CharField(max_length=30)

To create the form I did the following in forms.py:

class BioForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('bio',)

Then I created in the views.py the saving, so the bio will be saved to the specific user:


from .forms import LoginForm, RegisterForm
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.contrib.auth import get_user_model


def test_view(request):
    form = BioForm(request.POST)
    user = get_user_model
    if form.is_valid():
        profile = form.save(commit=False)
        profile.user = request.user
        profile.phone_number = request.phone_number
        profile.save()

    return render(request, 'test.html', {'form': form})

There is something big wrong in the views.py but I don't get it. I can submit the form and the form will be saved (sometimes) but without the user who wrote it I get this error:

ValueError at /test/

Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x00000253B7140D00>>": "Profile.user" must be a "User" instance

CodePudding user response:

Try to assign the user id instead

from .forms import LoginForm, RegisterForm
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.contrib.auth import get_user_model

def test_view(request):
    form = BioForm(request.POST)
    user = get_user_model
    if form.is_valid():
        profile = form.save(commit=False)
        profile.user_id = request.user.id
        profile.phone_number = request.phone_number
        profile.save()

    return render(request, 'test.html', {'form': form})

CodePudding user response:

Your problem is that the user you try to save with, is not an authenticated user that exists in the database. Only authenticated (logged in) users exist in the database and can be used in a relational field

  •  Tags:  
  • Related