trying to create a model that has an artist and song and lets you know what user name typed it in.
so far I have in my models.py
from django.contrib.auth.models import User
class Song(models.Model):
uesrname = models.ForeignKey(User,on_delete=models.CASCADE)
artist = models.CharField(max_length=30)
song=models.CharField(max_length=30)
I added a form that works with user input data but the form lets me select one of all exciting Users and input artist, song
forms.py
class NewSong(forms.ModelForm):
class Meta:
model=Song
exclude = ['username']
how can I change it so I will have only my own loged in user in the form?
You can exclude username field as exclude = ['username'] on your forms.py file and set username to request.user on form's save method. For more information: selecting fields
Related
I am using the default User model in Django and a OneToOneField in a Profile model where extra info such as user bio is stored.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
I am able to create basic forms for the two models independently
from django.contrib.auth.models import User
class UserForm(ModelForm):
class Meta:
model = User
fields = ['username', 'email']
class ProfileForm(ModelForm):
class Meta:
model = Profile
fields = ['bio']
What is the best method to create a page where a user can edit fields of either model?
So a User can edit Username,Email or Bio on the same page?
You can put the 2 forms in one template and Django will manage filling forms with the right fields (only exception is the same field name in 2 forms)
def view(request):
if request.method == "GET":
context["userform"]=UserForm()
context["profileform"] =ProfileForm()
else:
userform = UserForm(request.POST)
profileform=ProfileForm(request.POST)
I'm trying to create my own User class called Customer which extends the AbstractUser model and has an additional field called address. When I register, I see the user has been created in Django admin and all the fields (username, first name, last name and email) are seen in the django admin screen but I see no value in the "address" field. How do I know if the address is being saved and how can I display it in the admin site?
Below is my code for the models.py
class Customer(AbstractUser):
username = models.CharField(unique=True, max_length=20)
deladdress = models.CharField(max_length=100)
views.py
def signupPage(request):
signForm = CreateCustomer()
if request.method=='POST':
signForm = CreateCustomer(request.POST)
if signForm.is_valid():
signForm.save()
return render(request, 'trial_app/signup.html', {'signForm':signForm})
forms.py
class CreateCustomer(UserCreationForm):
address = forms.CharField(widget=forms.Textarea)
class Meta:
model = Customer
fields = ['username','first_name','last_name','email','address','password1','password2']
def save(self, commit=True):
user = super(CreateCustomer, self).save(commit=False)
user.address = self.cleaned_data["address"]
if commit:
user.save()
return user
Here are some pictures that are the input to my html form and the value in the admin site
It seems like when you save a form in its save method you use
user.address = self.cleaned_data["address"], however, Customer model does not have address field, it has deladdress, so try to rename a field, or use user.deladdress in your save method of CreateCustomer form.
I have a doubt about authentification with my own Model. In my project I have a Pacient Model and I need that to be saved on the Users panel in the Admin site.
Basically I recover the data from a HTML form (they're generated in a , it was a request for the test)
(Do not worry about the validations)
models.py
class Pacient(models.Model):
name = models.CharField()
birthday = models.DateField()
email = models.EmailField()
password = models.CharField()
confirmPass = models.CharField()
In the forms.py file
class PacientForm(forms.ModelForm):
name = forms.CharField
birthday = forms.DateField
email = forms.EmailField
password = forms.CharField
confirmPass = forms.CharField
class Meta:
model = Pacient
fields =('name','birthday','email','password','confirmPass')
Using those fields I can save data in the table Pacient. It can be seen in the admin site but separated from the Groups and Users under the project name.
So, my question is this. How can I made the Pacient Model to be recognized as the User (in the admin site) and login using the "email" as the username?
You should look at the AbstractBaseUser model:
from django.contrib.auth.models import AbstractBaseUser
This Base model can be inherited by your Pacient model, then in settings.py file you can set:
AUTH_USER_MODEL = 'yourapp.Pacient'
This will tell django to use your model for auth purposes.
More infos here : https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#django.contrib.auth.models.CustomUser
please help to solve this problem
I expanded in django1.6 User model as follows:
class UserProfile(User):
......
......
family = models.CharField(
max_length=30,
blank=True,
)
skype = models.CharField(
max_length=50,
blank=False,
)
email_address = models.EmailField(
max_length=50,
blank=True,
)
.....
....
objects = UserManager()
resulting in adminpanel appeared a form with the above fields. after filling the data is stored in the database table "app_userprofile". This table is linked to the table "auth_user" using the foreign key.
the problem is that the table "auth_user" fields "username" and "password" empty . but each user needed.
please tell me how to do so after the new user registration ( of the admin panel and from the site ) data "username" and "password" fell into the table "auth_user"
I think you need to use AbstractUser model. If you inherit UserProfile from User model you will get 2 tables with same fields, and when you fill app.UserProfile password field - value doesn`t appear in auth.User table.
Of course you can do like this: https://stackoverflow.com/a/23390975/1761844 but better way - create your own custom user:
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
... your custom fields ...
and add to your settings.py
AUTH_USER_MODEL = 'app.CustomUser'
after this you will get user model with your custom fields. You can import it in your apps like this:
from django.contrib.auth import get_user_model
User = get_user_model()
and make foreign keys like this:
owner = models.OneToOneField(settings.AUTH_USER_MODEL)
Link to django documentation: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-django-s-default-user
Use a one to one field, User.profile will create the Profile object the first time user.profile it is accessed:
from django.contrib.auth.models import User
from django.db import models
class Profile(models.Model):
user = models.OneToOneField(User, unique=True)
User.profile = property(lambda u: Profile.objects.get_or_create(user=u)[0])
First, change UserProfile, like it was mentioned in the previous answer. After that, check this answer: https://stackoverflow.com/a/4565957 as it explains how to combine user and user profile forms on a single admin page. Then you will be able to add both user and his/her profile with a single save.
There is also other way to solve your problem: you can define a custom user model with all the fields you need, combining username, password, family and other data in a single table. Check out this page for reference: https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#specifying-a-custom-user-model.
Let's say you have a django model with a OneToOne / Unique ForeignKey relationship with a User, as show on the Django documentation on how to create a UserProfile.:
Now let's say you have a view method that takes a request you can get a user from. What is the best way to query for the profile associated with that user?
from django.contrib.auth.models import User
# sample user profile model associated with user
class UserProfile(models.Model):
likes_spam = models.BooleanField()
user = models.OneToOneField(User)
#view method
def forward_to_practice_home(request):
user = request.user
profile_for_user = #insert code here that would get the profile for that user
related_names are very helpful. If you change your user profile definition to:
class UserProfile(models.Model):
likes_spam = models.BooleanField()
user = models.OneToOneField(User, related_name='profile')
then you can use profile as follows:
def forward_to_practice_home(request):
user = request.user
profile_for_user = user.profile
UserProfile.objects.get(user=user)
You may use a special method called get_profile()
profile_for_user = user.get_profile()
Be reminded that you have to set the AUTH_PROFILE_MODULE in the settings.py
However, this is deprecated in Django 1.5 because it adds the support of user model customization