I have made a signup page using built in UserCreationForm of django.
signup.html
class UserCreationForm(UserCreationForm):
email = EmailField(label=_("Email address"), required=True, help_text=_("Required."))
class Meta:
model = User
fields = ("username", "email", "password1", "password2")
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user
But I also need to make other tables in models.py. So if in another table category I need to make a foreign key of the primary key of this built in User of UserCreationForm. What is the primary key in this?
models.py
class category(models.Model):
uid = models.ForeignKey(#)
cname = models.CharField(max_length=20)
def __unicode__(self):
return u"{} {}".format(self.uid, self.cname)
class Meta:
db_table = "category"
What do I write in place of # ??
Just point to the User model:
from django.contrib.auth import User
uid = models.ForeignKey(User)
or better, in case you might want to customise the User model:
from django.conf import settings
uid = models.ForeignKey(settings.AUTH_USER_MODEL)
Related
I want to implement django signals on User model for create user profile. I want to create user profile when any user will be registered. here is my code for create user profile though signals:
from django.contrib.auth.models import User
#receiver(post_save, sender=User)
def user_is_created_or_save(sender,instance,created,**kwargs):
user = instance.user
first_name = instance.first_name
last_name = instance.last_name
if created:
UserProfile.objects.create(user=user)
I am not understanding why user profile not creating when any user registered?
#updated question
I am using Abstract user model. here is my user mdoel:
class UserManagement(AbstractUser):
is_blog_author = models.BooleanField(default=False)
is_editor = models.BooleanField(default=False)
is_subscriber = models.BooleanField(default=False)
is_customer = models.BooleanField(default=False)
class Subscriber(models.Model):
user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True)
email = models.EmailField(max_length=1000)
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
is_subscriber = models.BooleanField(default=False)
class UserProfile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile")
Since a custom user model has been defined, you can't use from django.contrib.auth.models import User. It is also not a recommended way to reference the user model.
As described in the docs if you have properly setup your custom user model, you can use settings.AUTH_USER_MODEL to reference your custom user model as the sender:
from django.conf import settings
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def user_is_created_or_save(sender, instance, created, **kwargs):
...
Thanks in advance, i'm learning Django and can't figure how to override all auth forms. Quick explanation first, I have a custom user model
class PersoUser(AbstractBaseUser):
email = models.EmailField(
verbose_name="Email Adress", max_length=200, unique=True)
username = models.CharField(
verbose_name="username", max_length=200, unique=True)
first_name = models.CharField(verbose_name="firstname", max_length=200)
last_name = models.CharField(verbose_name="lastname", max_length=200)
date_of_birth = models.DateField(verbose_name="birthday")
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
objects = PersoUserManager()
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["date_of_birth", "username"]
....
and I would want to add date_of_birth field to my signup page, so I followed the official doc to override the specif form used by all auth SignupView https://django-allauth.readthedocs.io/en/latest/forms.html#signup-allauth-account-forms-signupform
which leads to ( in Book_store/forms.py )
from all auth.account.forms import SignupForm from users. models import PersoUser
class PersoUserRegisterForm(SignupForm):
class Meta:
model = PersoUser
fields = ["username", "email", "first_name",
"last_name", "date_of_birth", "password1", "password2"]
def save(self, request):
# Ensure you call the parent class's save.
# .save() returns a User object.
user = super(PersoUserRegisterForm, self).save(request)
# Add your processing here.
# You must return the original result.
return user
in my settings/base.py
ACCOUNT_FORMS = {'signup': 'Book_store.forms.PersoUserRegisterForm'}
My account/signup.html template just refers to {{form.as_p}} and it doesn't display the extra fields specified in PersouserRegisterForm just the default ones
I don't see what I'm missing, Thanks for reading
EDIT: And Signing up fail because it violates not-null constraint for date_of_birth
You are overriding the save method but not saving user with the date_of_birth field .
def save(self, request):
user = super(PersoUserRegisterForm, self).save(request)
user.date_of_birth = self.cleaned_data['date_of_birth']
user.save()
return user
The error I get is: extend user to a custom form, the "user_id" field is my custom form is the "property", which is linked to the table "auth_user" is not saved, and I need both tables relate to make use my custom form attributes and shape of the User of django.
my models.py
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
Matricula = models.CharField(max_length=25)
forms.py
class SignupForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('first_name', 'last_name', 'Matricula')
#Saving user data
def signup(self, request, user):
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.Matricula = self.cleaned_data['Matricula']
user.save()
##Save profile
profile = Profile()
Profile.user = user
profile.Matricula = self.cleaned_data['Matricula']
profile.save()
i tried:
user = models.OneToOneField(User, on_delete=models.CASCADE)
but I get an error:
Error
You believe that ForeignKey can be used or correct use OneToOneField?
You should be careful with your capitalisation. You've assigned the user value to the class, not the instance. It should be:
profile = Profile()
profile.user = user
Or better:
profile = Profile(user=user)
You are not setting user to that instance of Profile:
profile = Profile()
profile.user = user # Notice the case of Profile
I want a foreign key relation in my model with the username field in the User table(that stores the user created with django.contrib.auth.forms.UserCreationForm).
This how my model looks:
class Blog(models.Model):
username = models.CharField(max_length=200) // this should be a foreign key
blog_title = models.CharField(max_length=200)
blog_content = models.TextField()
The username field should be the foreign key.The Foreign Key should be with this field
Unless I'm missing something, you can have a ForeignKey to a specific field:
class Blog(models.Model):
username = models.ForeignKey(User, to_field='username')
https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ForeignKey.to_field
You can't have an ForeignKey to a field, but you can to a row.
You want username which is available through the User model
So:
blog.user.username
If you insist on having blog.username you can define a property like this:
from django.db import models
from django.contrib.auth.models import User
class Blog(models.Model):
user = models.ForeignKey(User)
Then to access the field you want use:
blog.user.username
If you insist on having blog.username you can define a property like this:
from django.db import models
from django.contrib.auth.models import User
class Blog(models.Model):
user = models.ForeignKey(User)
#property
def username(self):
return self.user.username
With that property, you can access username through blog.username.
Note on how to import User
user = ForeignKey('auth.User')
or
from django.contrib.auth.models import User
user = ForeignKey(User)
or the more recommended
from django.conf import settings
user = ForeignKey(settings.AUTH_USER_MODEL)
I'm trying to create and manage a custom user in django.
I saw there are two possibilities, and i've chosen to extend (not create a new auth).
Models
models.py
class Artists(models.Model):
user = models.OneToOneField(User)
artist_image = models.ImageField(null=True, blank=True, upload_to="/artist_image/")
def __str__(self):
return 'Profil de {0}'.format(self.username)
def get_absolute_url(self):
return reverse('artist-details', kwargs={'pk': self.pk})
As i read in doc, I just make a OneToOne field with the User class of django auth models, so I can access method and properties, such as username, email, on my own user (here Artists).
form.py
class CreateArtistForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email')
def save(self, commit=True):
user = super(CreateArtistForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
Here I extend UserCreationForm to prepare a form a little different (I want to have email field on my register form).
But here is my question : I first tried with
class Meta:
model = Artists
fields = ('user.username', 'user.email')
But I the error fields unknown in model Artist.
So I tried just with username and email and same error.
So I changed the model = Artists to User, and it works fine.
But now how i register my Artist Object when the user is saved?
Do I have to make something like (in save()):
artist = Artists()
artist.user = user
artist.save()
Or override create_user()?
I'm quite lost here and i'm looking docs and questions not able to find something because most of example people define their own auth.
Thanks in advance
Besta
edit : i'm using django 1.8.2 and python 3.4