Could someone smart explain me please where I have a bug?
I get this error when I would like to send a profile user form
NOT NULL constraint failed: userprofile_userprofile.godzina_id
I have an app "userprofile"
forms.py
from django import forms
from models import UserProfile
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('imie', 'godzina')
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from forms import UserProfileForm
from django.contrib.auth.decorators import login_required
from django.conf import settings
#login_required
def user_profile(request):
if request.method == 'POST':
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/loggedin')
else:
user = request.user
profile = user.profile
form = UserProfileForm(instance=profile)
args = {}
args.update(csrf(request))
args['form'] = form
return render(request, 'user_profile.html', args)
models.py:
from django.db import models
from django.contrib.auth.models import User
from godzina.models import Godzina
class UserProfile(models.Model):
user = models.OneToOneField(User)
imie = models.CharField(max_length=150)
godzina = models.ForeignKey('godzina.Godzina')
User.profile = property(lambda u:UserProfile.objects.get_or_create(user=u)[0])
You could add null=True to your godzina attribute:
godzina = models.ForeignKey('godzina.Godzina', null=True)
Related
i tried for make Django project and make a local form to stored in django admin here is my "view.py" file code
from django.http import request
from django.shortcuts import render,redirect
from templates.forms import Registrationform
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm
def home(request):
numbers = [1,2,3,4,5]
name = 'max'
args = {'myName': name,'numbers':numbers}
return render(request, 'accounts/home.html',args)
def register(request):
if request.method == 'POST':
form = Registrationform(request.POST)
if form.is_valid():
form.save()
return redirect('/account')
else:
form = Registrationform()
args = {'form':form}
return render(request,'accounts/reg_form.html',args)
def view_profile(request):
args ={'user':request.user}
return render(request,'accounts/profile.html',args)
def edit_profile(request):
if request.method == 'POST':
form = UserChangeForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect('/account/profile')
else:
form = UserChangeForm(instance=request.user)
args={'form':form}
return render(request,'accounts/edit_profile.html')
there is my another file that named forms.py and the errors came with registrationform
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.db import models
from django.db.models import fields
class Registrationform (UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = (
'username',
'first_name',
'last_name',
'email',
'password1',
'password2'
)
def save(self, commit=True):
user = super(Registrationform, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
and another error is: module 'accounts.views' has no attribute 'profile' and sometimes can't import views also!!
Where is your Registrationform? You say it is living inside your 'templates' app/module, but Django can't find 'templates'. If it's inside the same directory as your views.py you can just import it with:
from .forms import Registrationform
I need to register a user and use it's email as Username. I am getting this error (UNIQUE constraint failed: auth_user.username) when trying to register on the page. I AM NEW TO DJANGO AND PYTHON
My Code is
forms.py File
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from phonenumber_field.formfields import PhoneNumberField
from django.db import transaction
from .models import User
class UserRegistrationForm(UserCreationForm):
name = forms.CharField(max_length=60)
# Username = forms.CharField(max_length=15)
email = forms.EmailField()
class Meta(UserCreationForm.Meta):
models = User
fields = ['name','email','password1','password2']
views.py file
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
from .forms import UserRegistrationForm
from django.contrib.auth import get_user_model
def register(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
User = form.save()
else:
form = UserRegistrationForm()
return render(request, 'users/signup.html', {'form': form})
models.py
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
"""docstring for User"""
email = models.EmailField(verbose_name='Email Address', unique=True)
name = models.CharField(max_length=50)
USERNAME_FIELD = 'email'
user_permissions = None
groups = None
REQUIRED_FIELDS = []
def __str__():
return self.name
django.db.utils.IntegrityError UNIQUE constraint failed
sqlite3.IntegrityError: UNIQUE constraint failed: new__users_profile.user_id
The above exception was the direct cause of the following exception:
new__users_profile.user_id
Error occurs when I'm trying to register new user, login to an existing user and when I am trying to migrate. I've tried to delete all migrations and migrate once again but it didn't help
models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
class Media(models.Model):
image_name = models.CharField(max_length=50)
image_description = models.CharField(max_length=80)
image_image = models.ImageField(upload_to='media', default='default.jpg')
views
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .forms import UserRegisterForm, MediaForm
from .models import Media
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'Your account has been created! You are now able to log in')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
#login_required
def profile(request):
if request.method == 'GET':
media_images = Media.objects.all()
context = {
'media_images':media_images,
}
return render(request, 'users/profile.html', context)
#login_required
def add_media(request):
if request.method == 'POST':
form = MediaForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('http://127.0.0.1:8000/')
else:
form = MediaForm()
return render(request, 'users/add_media.html', {'form':form})
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import *
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class MediaForm(forms.ModelForm):
class Meta:
model = Media
fields = ['image_name', 'image_description', 'image_image']
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
#receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
I think you need primary_key=True,
class Profile(models.Model):
user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE, null=True)
In class profile, add primary_key=True and remove null=True
user = models.OneToOneField(User,primary_key=True, on_delete=models.CASCADE)
I hope it will work!
I have a contact form/model in Django that isn't showing up on the admin management page.
I have no idea why it isn't showing up, I have tried to debug by running migrations, and also renaming some of the model variables.
models.py
from django.db import models
class Contact(models.Model):
their_name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
message = models.CharField(max_length=500)
def __str__(self):
return self.name
forms.py
from django import forms
class ContactForm(forms.Form):
their_name = forms.CharField(label='Name', max_length=100)
email = forms.EmailField(label='Email', max_length=100)
message = forms.CharField(label='Message', max_length=500, widget=forms.Textarea(attrs = {'id': 'Message_form'}))
admin.py
from django.contrib import admin
from .models import Contact
admin.register(Contact)
views.py
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from .models import Contact
from .forms import ContactForm
...
def contact(request):
valid_input = 'no input'
if request.method == 'POST':
valid_input = 'invalid input'
TheForm = ContactForm(request.POST)
if TheForm.is_valid():
valid_input = 'valid input'
name = TheForm['name']
email = TheForm['email']
message = TheForm['message']
Contact.objects.create(name=name, email=email, message=message)
else:
TheForm = ContactForm()
return render(request, 'BlogHome/pages/contact.html', {'TheForm': TheForm, 'valid_input': valid_input})
Could this be the way I am importing the model? I have no idea what is causing this problem.
In your admin.py create an admin class for your Contact model and after register this model in admin using that class.
class ContactAdmin(admin.ModelAdmin):
list_display = ('id', 'their_name', 'email', 'message')
admin.site.register(Contact, ContactAdmin)
So I've got this situation.
-models.py
from django.db import models
from django.utils import timezone
from autoslug import AutoSlugField
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', blank=True)
def __unicode__(self):
return self.user.username
-forms.py
from django import forms
from django.forms import ModelForm
from tentagarden.models import UserProfile
from django.contrib.auth.models import User
from parsley.decorators import parsleyfy
#parsleyfy
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password')
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('website', 'picture')
-views.py
from django.shortcuts import render_to_response, render, redirect
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from tentagarden.forms import UserForm, UserProfileForm
def home(request):
context = RequestContext(request)
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'picture' in request.FILES:
profile.picture = request.FILES['picture']
profile.save()
registered = True
else:
print user_form.errors, profile_form.errors
else:
user_form = UserForm()
profile_form = UserProfileForm()
return render_to_response(
'tentagarden/home.html',
{'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
context)
-admin.py
from django.contrib import admin
from .models import File, Post, UserProfile
admin.site.register(File)
admin.site.register(Post)
admin.site.register(UserProfile)
And I'd like to have the User data (so First name, Last name and Email) visualized in "User profiles" (in the Admin page), other than in "Users" only.
What should I do?
Thank you!
Put this is in your admin.py
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('email', 'first_name', 'last_name', 'website')
search_fields = ('user__username', 'user__first_name', 'user__last_name', 'user__email')
# list_filter = ('some_field_to_filter')
readonly_fields = ('email', 'first_name', 'last_name')
def email(self, obj):
return obj.user.email
def first_name(self, obj):
return obj.user.first_name
def last_name(self, obj):
return obj.user.last_name
admin.site.register(UserProfile, UserProfileAdmin)
Use fieldsets to control the order of displayed fields in edit view.