I keep getting this error: "NOT NULL constraint failed: users_userprofile.user_id" when I try to submit the form
from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model):
This is form.py: from django import forms from user.models import UserProfile from django.contrib.auth.models import User
class UserForm(forms.ModelForm): password = forms.CharField(min_length=6,label='', widget=forms.PasswordInput(attrs={'placeholder': 'Password','required':'true','class':"form-control"})) username = forms.CharField(label='', min_length=6, widget=forms.TextInput(attrs={'placeholder': 'Username','required':'true','class':"form-control",'autofocus':'true'})) email = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Email','required':'true','class':"form-control"})) class Meta: model = User fields = ('username', 'email', 'password') class UserProfileForm(forms.ModelForm): about_me = forms.CharField(label='', widget=forms.Textarea(attrs={'placeholder': 'Sobre mi','required':'true','class':"form-control"})) first_name = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Nombre','required':'true','class':"form-control"})) last_name = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Apellidos','required':'true','class':"form-control"})) experience = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Experiencia','required':'true','class':"form-control"})) offers = forms.CharField(label='', widget=forms.Textarea(attrs={'placeholder': 'Mensaje','required':'true','class':"form-control"})) class Meta: model = UserProfile fields =('first_name','last_name','about_me','experience','offers')
This is the template:
{%extends 'base.html'%} {%block content%} {% if user.is_authenticated %} <h1>Edita tu perfil</h1> <form id='profile' method='post' action='/edit_profile/'> {% csrf_token %} {{profile.as_p}} <button type='submit'>Editar</button> </form> {%endif%} {%endblock%}
Thanks for the hand
EDIT:
The error was in the views.py view. I needed to add an instance to the form, for example:
form = UserProfileForm(data=request.POST, instance=profile)
This is my full views.py:
def edit_profile(request): try: profile = request.user.userprofile except UserProfile.DoesNotExist: profile = UserProfile(user=request.user) if request.method == 'POST': form = UserProfileForm(data=request.POST, instance=profile) if form.is_valid(): form.save() return HttpResponse("Exito!") else: form = UserProfileForm(instance=profile) else: form = UserProfileForm() return render(request, 'editprof.html', { 'form': form})