I am building a user model and wanna attach it to a modelform as below shown. How can I get the email of each user by shell accessing the mysql database?
I have tried these to get the data by shell, but the previous one said the object has no email attribute and the latter one said the forms.py has no object.
from Project.User.models import UserProfile as p
p.objects.filter(is_active=True).first().email //
from Project.User.forms import ClientProfileForm as p
p.objects.filter(is_active=True).first().email
Code:
models.py:
class UserProfile(BaseModel):
user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE, verbose_name='client')
name = models.CharField('name',max_length=30, null=False, help_text="Name")
gender = models.CharField('sex',max_length=1, help_text="Sex")
class Meta:
verbose_name = 'Client'
verbose_name_plural = 'Client'
def __str__(self):
return 'client:%s' % self.user
forms.py:
class ClientProfileForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = UserProfile
fields = ("user", "name", "gender")
Have you tried using
p.objects.filter(is_active=True).first().user.email
There is no data in form before you send a data to it so you can't get the user and it's email from your shell.
Forms are used to get data from HTML templates for example and validate that data and then add those data to the database.
If you fill a form, you can access the data that has been cleaned from your view like this:
form = ClientProfileForm(request.POST)
if form.is_valid():
print(form.cleaned_data['my_form_field_name'])
Also you can set some default values for forms. Example here:
Django forms initial example on stackoverflow
And finally for your problem:
You are trying to access email from UserProfile which doesn't have a email field but the User model does.
so you can access the email like this:
from Project.User.models import UserProfile as p
# Get the first profile and then get the email from user model
p.objects.filter(is_active=True).first().user.email
from Project.User.forms import UserProfile as p
This line is incorrect because the name of your form is ClientProfileForm and not UserProfile. This is why you are getting the error forms.py has no object
Related
I am building a chat application with django rest framework and I m currently working on messages. This are my models:
from django.db import models
from django.contrib.auth.models import User
class Message(models.Model):
text = models.CharField(max_length=500)
datetime = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE);
I am using the Django auth User model. This is my ModelViewSet for the messages:
class MessageViewSet(ModelViewSet):
queryset = Message.objects.all()
serializer_class = MessageSerializer
And these are my serializers:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['username']
class MessageSerializer(serializers.ModelSerializer):
user = UserSerializer(read_only=True)
class Meta:
model = Message
fields = '__all__'
And this is my API:
The code I've written so far works really well for the GET functionally I want. I want for each message to get the username of the user it belongs to. But now I want the following thing: when I POST a new message, I want to be able to specify which user it belongs to by specifying the user's id. Right now I have only the "text" field in the POST section. I need to add a "user" field which takes in an integer (the user primary key) to specify which user the message belongs to. How should I refactor my code in order to do that?
Because you've overridden the user field and set it to read_only=True, you cannot set a user when you're creating/updating a model.
If you just need the user's username, I'd suggest you to add a username field into MessageSerializer directly instead:
class MessageSerializer(serializers.ModelSerializer):
username = serializers.CharField(source='user.username', read_only=True)
class Meta:
model = Message
fields = '__all__'
Now you'll get this payload instead:
{
"id": 1,
"user": 1,
"username": "timi",
...
And you should be able to set a user id now.
I am new to Django and I am creating a simple 2 page messageboard app (submit page and messageboard page)
I am struggling with the form for my submit page. As I am learning my way around Django I decided not to use the standard user model and opted to rather create a model (Poster) which has a one to one relationship with the message model.
Basically in one form I would like to add a message and a poster(foreign key) which has multiple fields.
Is it possible to achieve what I am trying to do?
Thanks in advance for the help.
I don't really know what to try or what to look for. I have included some code below.
Models
class Poster(models.Model):
full_name = models.CharField(max_length = 50)
phone_number = models.CharField(max_length = 15)
email = models.EmailField()
class Message(models.Model):
message_text = models.CharField(max_length=10000)
created_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(Poster, on_delete=models.CASCADE)
class MessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['full_name', 'phone_number', 'email', 'message_text']
Your mistake is trying to use a ModelForm subclass which is for creating or updating one object (database row) only.
Use a plain forms.Form with the fields you want. You'll have to explicitly code them as CharField, EMailField, etc. Then in form_valid (assuming your view is a FormView) you will do something like
poster = Poster()
poster.full_name = form.cleaned_data['full_name']
# ditto for phone_number and email
poster.save()
message = Message( user=poster,
message_text = form.cleaned_data['message_text'] )
message.save()
I am trying to insert django form data inside the UserProfile model in my app. I tried using the django shell and views.py but I keep getting this error.
Models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
section = models.CharField(max_length=255, blank=True)
year = models.IntegerField(null=True, blank=True)
course = models.CharField(max_length=255, blank=True)
qrcode = models.CharField(max_length=255, blank=True)
present = models.BooleanField(default=False)
def __str__(self):
return self.user.username
views.py
#staticmethod
def generate_qr(request):
if request.method == "POST":
form = MakeAttendance(request.POST)
if form.is_valid():
course = form.cleaned_data.get('courses')
section = form.cleaned_data.get('section')
year = form.cleaned_data.get('year')
profile = UserProfile.objects.get_or_create(user=request.user)
userobj = UserProfile(qrcode=unique_id)
userobj.save().filter(course=course, section=section, year=year)
return redirect('/users/dashboard')
This question has been answered many times here, but none of the solutions worked for me. I tried Creating a user profile with get_or_create method. I tried deleting my entire database and making migrations again. I manually tried to pass the user ID but nothing.
First create a user using user=User.objects.create_user(username=request.user, password='password'), then save it using user.save() and create profile using profile=UserProfile.objects.get_or_create(user=user). The reason this error occours is because the UserProfile looks for a user instance which you did not provide.
The problem is in these two line
userobj = UserProfile(qrcode=unique_id)
userobj.save().filter(course=course, section=section, year=year)
In the first line you created an instance of UserProfile with only qr_code
and in the next line you are trying to save it which will try to insert a new row in the database without the user.
in models.py you should create user object:
from django.conf import settings
User = settings.AUTH_USER_MODEL
before class creating
I want to expand my User Model with a UserProfile model. This UserProfile model includes a ForeignKey Field. In the form, I would like to use a ModelChoiceField to pre-populate this form field.
Whenever I submit the form, I get
ValueError at /accounts/register/
Cannot assign "'13'": "UserProfile.course" must be a "Course" instance.
Any help would be appreciated!
My Code:
models.py
class Course(models.Model):
course_accid = models.CharField(max_length=10)
def __str__(self):
return self.course_accid
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User)
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', blank=True)
course = models.ForeignKey(Course)
def __unicode__(self):
return self.user.username
def user_registered_callback(sender, user, request, **kwargs):
profile = UserProfile(user = user)
profile.website = request.POST["website"]
profile.course = Course.objects.get(pk=request.POST["course"]),
profile.save()
forms.py
class RegistrationForm(RegistrationForm):
course = forms.ModelChoiceField(queryset=Course.objects.all())
website = forms.URLField()
So, the problem that's occurring is that course needs to be set to a course instance with a step before, on forms.py, before it's a ModelChoiceField. The reason why is because querying it, like you're doing with queryset is really just searching for a string that matches, not the actual object.
If you break it up into two steps,
class = [some_method_for_getting_a_class_object]
UserProfile.class = class
Then it should get rid of that error.
I use the default User class from from django.contrib.auth.models import User. In the user creation when the user is created I set the username field to a random hash. When I use the model in ManyToMany field and use it in the Django admin then the random hash is rendered in the select box. Is there a way to specify the field to be taken from the model to be displayed in the select box so that I can specify the model as ManyToMany field and use the email to be rendered in the django admin form.
class TestModel(models.Model):
group = models.ManyToManyField(Group, null=True)
user = models.ManyToManyField(User, null=True)
Is there a field like the display_name that can be passed to the model field so that the appropriate field can be taken from the ManyToMany model for rendering. I am using Django 1.5.5
I think you need to do something like this,
class TestModelAdminForm(forms.ModelForm):
user = forms.MultipleChoiceField(choices=[ (user.id, user.email) for user in User.objects.all()])
class Meta:
model = TestModel
fields = ('user','group')
class TestModelAdmin(admin.ModelAdmin):
form = TestModelAdminForm