I am getting this error.Below mentioned code is for forms.py
forms.py
from django import forms
from dappx.models import UserProfileInfo
from django.contrib.auth.models import User
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ['username','password','email']
class UserProfileInfoForm(forms.ModelForm):
class Meta:
model = UserProfileInfo
fields = ['portfolio_site','profile_pic']
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
"""
Form class to register a new user
"""
def __init__(self, *args, **kwargs):
super(UserRegisterForm, self).__init__(*args, **kwargs)
class Meta:
model = User
fields = ['username','password','email']
I found this tutorial a good reading source
Related
[enter image description here][1]I don't know what is causing this error but i couldn't find any solution for this. i checked everything and everything seems to be fine but i don't know why this error is occuring.
Views.py
from django.contrib.auth import get_user_model
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView,FormView
from . import forms
# Create your views here.
def signup(request):
if request.method =='POST':
user_create_form = forms.UserCreateForm(data=request.POST)
user_profile_form = forms.UserProfileInfoForm(data=request.POST)
if user_create_form.is_valid() and user_profile_form.is_valid():
user = user_create_form.save()
user.save()
profile = user_profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
else:
print(user_create_form.errors,user_profile_form.errors)
else:
user_create_form = forms.UserCreateForm()
user_profile_form = forms.UserProfileInfoForm()
return render(request,'accounts/signup.html',{'user_create_form':user_create_form,
'user_profile_form':user_profile_form})
Models.py
from django.db import models
from django.contrib import auth
# Create your models here.
class User(auth.models.User,auth.models.PermissionsMixin):
def __str__(self):
return "#{}".format(self.username)
class UserProfileInfo(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
Contact_number = models.IntegerField(blank=True)
joined_at = models.DateTimeField(auto_now=True)
profile_pic = models.ImageField(upload_to='profiles',blank=True)
def __str__(self):
return self.user.username + ' Profile'
Forms.py
from django.contrib.auth import get_user_model # this gets the model that is in the application
from django import forms
from django.contrib.auth.forms import UserCreationForm
from . import models
class UserCreateForm(UserCreationForm):
class Meta():
fields = ('username','email','password1','password2',)
model = get_user_model()
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].label = 'Display Name' # to set up a custom label for the field
self.fields['email'].label = "Email Address"
class UserProfileInfoForm(forms.ModelForm):
class Meta():
model = models.UserProfileInfo
fields = ('Contact_number','profile_pic')
I am getting this error no matter what i do, i tried referencing other similar questions but couldn't find any solution for this error. pls help me out on this one.
Thanks in Advance !
image of the error
[1]: https://i.stack.imgur.com/HOcmf.png
You can overwrite save() method in your model to return a model instance after saving an object, for example:
class YourModel(models.Model):
name = models.CharField(max_length=20)
def save(self, *args, **kwargs):
super(YourModel, self).save(*args, **kwargs)
return self
your_model_saved_instance = YourModel(name='example').save()
Then you will receive an instance from the user class instead of the form class
user = user.save()
I am getting type error while setting current user to created_by field in my model
forms.py
class MyModelForm(forms.ModelForm):
class Meta:
model = Model
fields = ('name',)
def __init__(self, *args, creator, **kwargs):
super().__init__(*args, **kwargs)
self.creator = creator
def save(self, *args, **kwargs):
self.instance.created_by = self.creator
return super().save(*args, **kwargs)
views.py
class CreatEEView(LoginRequiredMixin, CreateView,):
form_class = ''
template_name = ''
success_url = ''
Models.py
class MYmodel(models.Model):
name = models.CharField()
created_by = models.ForeignKey()
You do not need to use a custom form for that because CreateView is creating ModelForm for you, what you can do is like that:
from django.db import models
class MYmodel(models.Model):
name = models.CharField()
created_by = models.ForeignKey()
Then you can override the form_valid method. This method is called when valid form data has been POSTed.
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import CreateView
from myapp.models import MYmodel
class CreatEEView(LoginRequiredMixin, CreateView):
model = MYmodel
fields = ['name']
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
You can find the same example in Django documents in this Link
I am using Django DRF, and having difficulty in applying SerializerMethodField (https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield)
Following is a simple case of typical model, serializer code, which works perfectly.
serializer.py (before)
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
view.py (before)
#api_view(['GET'])
def GetAllUsers(request):
Users = User.objects.all()
serializer = UserSerializer(Users, many=True)
return Response(serializer.data)
In order to deliver additional information which is not included in the model, I changed serializer
serializer.py (after)
from django.contrib.auth.models import User
from django.utils.timezone import now
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
days_since_joined = serializers.SerializerMethodField()
class Meta:
model = User
def get_days_since_joined(self, obj):
return (now() - obj.date_joined).days
Now I have to find a way to give obj(which has date_joined inside) to serializer, and I think I have to do it in view.py
But I don't know how to do it.
Thanks
You can pass extra context to serializer like this
view.py
#api_view(['GET'])
def GetAllUsers(request):
Users = User.objects.all()
context = {"extra_obj": extra_obj}
serializer = UserSerializer(Users, many=True, context=context)
return Response(serializer.data)
serializer.py
from django.contrib.auth.models import User
from django.utils.timezone import now
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
days_since_joined = serializers.SerializerMethodField()
class Meta:
model = User
def get_days_since_joined(self, obj):
extra_obj = self.context.get("extra_obj")
return (now() - extra_obj.date_joined).days
reference the official document here
You just have to include SerializerMethodField name and other model fields which you want to return to api.
There is no need to change views.py, you just have to change serializer.py.
In your case serializer.py will be like
from django.contrib.auth.models import User
from django.utils.timezone import now
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
days_since_joined = serializers.SerializerMethodField()
class Meta:
model = User
fields = [
'id',
'name',
'days_since_joined',
]
def get_days_since_joined(self, obj):
return (now() - obj.date_joined).days
I am taking online Djago class and have no one to ask for help. I would appreciate to get any help and tips.
I am learning creating forms (login/singup).
So far i did in models.py
from django.db import models
from django.contrib import auth
class User(auth.models.User,auth.models.PermissionsMixin):
def __str__(self):
return "#{}".format(self.username)
In forms.py
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
class UserCreateForm(UserCreationForm):
class Meta:
fields = ('username','email','password1','password2')
model = get_user_model()
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].label = 'Display Name'
self.fields['email'].label = 'Email Address'
I want to add addtional firelds as surname , however when i add 'surname' in class meta in fields (forms.py) i get error, however the online training says i can easily add additional fields. Could you please tell what i am doing wrong and how i can add this field?
when i add those field 'surname' in forms.py:
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
class UserCreateForm(UserCreationForm):
class Meta:
fields = ('username','email','surname','password1','password2')
model = get_user_model()
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].label = 'Display Name'
self.fields['surname'].label = 'Surname'
self.fields['email'].label = 'Email Address'
it give the following error:
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (surname) specified for User
In views.py i ahve:
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView,TemplateView
from . import forms
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy('login')
template_name = 'accounts/signup.html'
# In your forms.py, you need to add new field 'surname'
For Example:-
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
class UserCreateForm(UserCreationForm):
surname = forms.CharField(max_length=20)
class Meta:
fields = ('username','email','surname','password1','password2')
model = get_user_model()
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].label = 'Display Name'
self.fields['surname'].label = 'Surname'
self.fields['email'].label = 'Email Address'
First of all you are using the get_user_model() method but you are working with a custom User model.
In you settings set AUTH_USER_MODEL:
AUTH_USER_MODEL = 'app.User'
Then add the surname field to your User model:
class User(auth.models.User):
surname = models.Charfield()
def __str__(self):
return "#{}".format(self.username)
Run and apply migration. Then you will be able to add the surname field to your form fields
class UserCreateForm(UserCreationForm):
class Meta:
fields = ('username','email','surname','password1','password2')
model = get_user_model()
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].label = 'Display Name'
self.fields['surname'].label = 'Surname'
self.fields['email'].label = 'Email Address'
You need to make following changes to your forms.py file:-
from appname.models import USER
from django.contrib.auth.forms import UserCreationForm
class UserCreateForm(UserCreationForm):
class Meta:
fields = ('username','email','surname','password1','password2')
model = USER
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].label = 'Display Name'
self.fields['surname'].label = 'Surname'
self.fields['email'].label = 'Email Address'
I'm trying to do a login app including registration, authentication etc...
I'm getting this error:
AttributeError: Got AttributeError when attempting to get a value for field 'user' on serializer 'PictureUserSerializer'.
The serializer field might be named incorrectly and not match any attribute or key on the 'User' instance.
Original exception text was: 'User' object has no attribute 'user'.
But, when I check my admin page. The user has been registered with the right informations. I'm not feeling like this error come from nowhere and I must do something wrong. Here is my code:
logginapp/models.py
from django.db import models
from django.contrib.auth.models import User
class PictureUser(models.Model):
user = models.OneToOneField(User) #OneToOne link to the Django's User Model
avatar = models.ImageField(null=True, blank=True, upload_to="avatars/")
def username(self, user):
return user.username
def password(self, user):
return user.password
def email(self, user):
return user.email
loginapp/serializer.py
from django.core.validators import validate_email
from django import forms
from rest_framework import serializers
from loginapp.models import PictureUser
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'password', 'email')
write_only_fields = ('password',)
class PictureUserSerializer(serializers.ModelSerializer):
"""
Serializer to put the PictureUser model into JSON
"""
user = UserSerializer()
class Meta:
model = PictureUser
fields = ('user', 'avatar')
read_only_fields = ('created',)
def create(self, validated_data):
print (validated_data)
return User.objects.create_user(validated_data['user']['username'], validated_data['user']['email'],
validated_data['user']['password']
)
loginapp/view.py
from django.shortcuts import render
from rest_framework import generics
from .serializer import PictureUserSerializer
from .models import PictureUser
class PictureUserCreateView(generics.ListCreateAPIView):
"""
This class define the Create behaviour of a PictureUser
"""
queryset = PictureUser.objects.all()
serializer_class = PictureUserSerializer
def perform_create(self, serializer):
serializer.save()
If you need to create user from PictureUserSerializer, then,
def create(self, validated_data):
user_data = validated_data.pop('user')
user = User.objects.create_user(**user_data)
return PictureUser.objects.create(user = user, **validated_data)
PictureUserSerializer create method needs to return a PictureUser instance, not a User instance.