views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import UploadDocument
from .models import Document
def upload_document(request):
if request.method == 'POST':
form = UploadDocument(request.POST, request.FILES)
if form.is_valid():
# file is saved
instance = Document(passport=request.FILES['passport'])
instance.save()
instance = Document(id_license=request.FILES['id_license'])
instance.save()
instance = Document(User=request.user)
instance.save()
# needs to add instance of User from cache
return HttpResponseRedirect('/success/url/')
else:
form = UploadDocument()
return render(request, 'verification/verificate.html', {'form': form})
forms.py
from django import forms
class UploadDocument(forms.Form):
passport = forms.ImageField()
id_license = forms.ImageField()
models.py
from django.conf import settings
from django.db import models
class Document(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,)
passport = models.ImageField()
id_license = models.ImageField()
Exception Value: NOT NULL constraint failed:
verification_document.user_id
I want to create a form that allows uploading documents, for verification purpose. How to attach a loged in User?
try this code:
views.py
def upload_document(request):
if request.method == 'POST':
form = UploadDocument(request.POST, request.FILES)
if form.is_valid():
instance=Document()
instance.passport=request.FILES['passport']
instance.id_license=request.FILES['id_license']
instance.User=request.user
instance.save()
return HttpResponseRedirect('/success/url/')
else:
form = UploadDocument()
return render(request, 'verification/verificate.html', {'form': form})
Related
IntegrityError at /
NOT NULL constraint failed: pages_profile.username
Request Method: POST
Request URL: http://127.0.0.1:8000/
Django Version: 3.2.9
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: pages_profile.username
How do I update an abstractuser from a post request using a form that's already signed in?
from django.shortcuts import redirect, render
from .forms import UserProfileForm
from .models import Profile
def index(request):
context = {}
if request.method == "POST":
print(request.POST)
form = UserProfileForm(request.POST, request.FILES)
if form.is_valid():
img = form.cleaned_data.get("avatar")
obj, created = Profile.objects.update_or_create(
username=form.cleaned_data.get('username'),
defaults={'avatar': img},
)
obj.save()
print(obj)
return redirect('home')
else:
form = UserProfileForm()
context['form']= form
return render(request, "home.html", context)
urls.py
from django.urls import path
from pages.views import index
urlpatterns = [
path('', index, name='home'),
]
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class Profile(AbstractUser):
avatar = models.ImageField(default='default.png', upload_to='',null=True, blank=True )
forms.py
from django import forms
from django.core.files.images import get_image_dimensions
from pages.models import Profile
class UserProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('avatar',)
from django.shortcuts import redirect, render
from .forms import UserProfileForm
from .models import Profile
def index(request):
context = {}
if request.method == "POST":
print(request.POST)
form = UserProfileForm(request.POST or None, request.FILES or None,instance=request.user)
if form.is_valid():
"""
img = form.cleaned_data.get("avatar")
print(img)
print(form.cleaned_data.get('username'))
print(request.user)
obj, created = Profile.objects.update_or_create(
username=form.cleaned_data.get('username'),
defaults={'avatar': img},
)
obj.save()
print(obj)
"""
form.save()
return redirect('home')
else:
form = UserProfileForm(instance=request.user)
context['form']= form
return render(request, "home.html", context)
I swapped it to this and it just works but it doesn't delete the old photo in the s3 bucket yet. It was instance=request.user which was needed.
hello guys i am working on form i didint find how to get instance in the form. This is not a model form
def form(request):
if request.method == 'POST':
form = Form(request.POST)
if form.is_valid():
else:
form = Form()
return render(request, 'app/form.html', {'form': form})
You should have a form class something like below:
forms.py
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
Now To handle the form we need to instantiate it in the view for the URL where we want it to be published:
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import NameForm
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
# process the data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
Refer the Django documentation for more details.
https://docs.djangoproject.com/en/3.0/topics/forms/
I am new to django, I migrated my models, the database is working fine, i can see the data that I added by the manage.py shell. But I cant add Data from my webApp. When I wrote text on the fields and press the submit button it gave me this error NOT NULL constraint failed: sms_post.author_id
Thanks for helping..
models.py files
from django.db import models
from django.contrib.auth.models import User
THE_GENDER = [
("Monsieur", "Monsieur"),
("Madame", "Madame")
]
class Post(models.Model):
name = models.CharField(max_length=100)
email = models.CharField(max_length=100)
gender = models.CharField(max_length=8, choices=THE_GENDER)
number = models.CharField(max_length=100)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.name
forms.py files
from django import forms
from .models import Post
from crispy_forms.helper import FormHelper
class post_form(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(post_form, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
class Meta:
model = Post
fields = ["name", "email", "gender", "number"]
views.py files
from django.shortcuts import render
from django.http import HttpResponse
from .forms import post_form
from django.contrib.auth.decorators import login_required
#login_required
def home(request):
form = post_form(request.POST or None)
if form.is_valid():
form.save()
context = {
"form": form
}
return render(request, "sms/home.html", context)
You did not set the author of the instance in your for to a User object. You can do this with:
from django.shortcuts import redirect
#login_required
def home(request):
if request.method == 'POST':
form = post_form(request.POST)
if form.is_valid():
form.instance.author = request.user
form.save()
return redirect('name-of-view')
else:
form = post_form()
context = {
'form': form
}
return render(request, 'sms/home.html', context)
In order to implement the Post/Redirect/Get pattern [wiki], in case of a successful POST request, you should make a redirect, for example to the same view. You thus can here replace 'name-of-view' with the name of a view to redirect to.
I was just watching a tutorial in youtube and i was just following what was indicated buti still got those errors.
Forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(max_length = 50)
class Meta:
model : User
fields = ['username', 'password1', 'password2']
views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}!')
return redirect('home')
else:
form = UserRegisterForm()
return render (request, 'users/register.html', {'form':form})
I have a model named Profile which is created to extend the User auth model. I have created two forms one is UserForm and ProfileForm. In register.html template I show this two forms and wish to save in the database through the user.
But it constantly shows the exception: Integrity Error
NOT NULL constraint failed: core_profile.user_id
whenever I try to submit the post filling out all the fields and hit submit button.
Here are my models:
from __future__ import unicode_literals
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)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
#receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
And here is my view for posting the forms:
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect
from .forms import SignUpForm, ProfileForm
#login_required
def home(request):
return render(request, 'home.html')
def signup(request):
if request.method == 'POST':
user_form = SignUpForm(request.POST)
profile_form = ProfileForm(request.POST)
if user_form.is_valid():
user = user_form.save()
profile_form.save()
user.refresh_from_db() # load the profile instance created by the signal
user.profile.birth_date = user_form.cleaned_data.get('birth_date')
user.save()
raw_password = user_form.cleaned_data.get('password1')
user = authenticate(username=user.username, password=raw_password)
login(request, user)
return redirect('home')
else:
user_form = SignUpForm()
profile_form = ProfileForm()
return render(request, 'signup.html', {'user_form': user_form, 'profile_form': profile_form})
And here are the forms:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Profile
class SignUpForm(UserCreationForm):
birth_date = forms.DateField(help_text='Required. Format: YYYY-MM-DD')
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'birth_date')
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('bio', 'location')
Thank you,
When you are trying to save the profile_form, it doesn't know to which user it is related to. And in your case, when you save the user form, it will create the profile, and what you need to do is just update the profile of you saved user, so I suggest something like:
def signup(request):
if request.method == 'POST':
user_form = SignUpForm(request.POST)
profile_form = ProfileForm(request.POST)
if user_form.is_valid():
user = user_form.save()
user.profile.bio = profile_form.cleaned_data.get('bio')
user.profile.location = profile_form.cleaned_data.get('location')
user.profile.save()
...
In addition to #Gagik Sukiasyan's answer: I added some additional things to reduce errors / ease your life:
transaction.atomic -> if errors occur, the database is being rolled back
and profile_form.is_valid() makes sure profile_form is validated
instead of going through the profile attributes manually I added a loop
Modified Code:
from django.db import transaction
#transaction.atomic
def register(request):
""" register a new user view """
if request.method == 'POST':
user_form = UserRegisterForm(request.POST)
profile_form = ProfileForm(request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
for field in profile_form.changed_data:
setattr(user.profile, field, profile_form.cleaned_data.get(field))
user.profile.save()