I'm trying to create a page for is_staff folks can create users. The code is below.
views.py
#login_required
def create_new_user(request):
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('jobs:new-user'))
else:
form = CreateUserForm()
return render(request, 'jobs/create_user.html', {'form': form})
forms.py
from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class CreateUserForm(UserCreationForm):
class Meta:
model: User
fields = ['username', 'password1', 'password2']
error output
This is the error I get when I try to access the account creation page.
Traceback:
File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/jobs/views.py" in create_new_user
124. form = CreateUserForm()
File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/contrib/auth/forms.py" in __init__
96. super(UserCreationForm, self).__init__(*args, **kwargs)
File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/forms/models.py" in __init__
275. raise ValueError('ModelForm has no model class specified.')
Exception Type: ValueError at /create_user/
Exception Value: ModelForm has no model class specified.
Any ideas? As always, THANK YOU.
You need to set model equal to User like model = User
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'password1', 'password2']
Related
I am trying to build a user authentication app using django JWT token, when i try to test my user authentication api and validate the password and password2 , it generate the following error:
TypeError: User() got unexpected keyword arguments: 'password2'
My serializers.py is as follows:
from rest_framework import serializers
from account.models import User
class UserRegistrationSerializers(serializers.ModelSerializer):
password2=serializers.CharField(style={'input_type':'password'}, write_only=True)
class Meta:
model = User
fields=['email','name','tc','password','password2']
extra_kwargs={
'password':{'write_only':True}
}
def validate(self, attrs):
password=attrs.get('password')
password2=attrs.get('password2')
if password != password2:
raise serializer.ValidationError("Password and Confirm Password Does not match")
return attrs
def validate_data(self, validate_data):
return User.objects.create_user(**validate_data)
and my views.py is as follows:
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from account.serializers import UserRegistrationSerializers
# Create your views here.
class UserRegistrationView(APIView):
def post(self, request, format=None):
serializer= UserRegistrationSerializers(data=request.data)
if serializer.is_valid(raise_exception=True):
user= serializer.save()
return Response({'msg':'Registration Successful'}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
my models.py file is as follows:
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
# Create your models here.
class UserManager(BaseUserManager):
def create_user(self, email, name, tc, password=None, password2=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
name=name,
tc=tc,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, name, tc, password=None):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(
email,
password=password,
name=name,
tc=tc,
)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='Email',
max_length=255,
unique=True,
)
#date_of_birth = models.DateField()
name= models.CharField(max_length=200)
tc=models.BooleanField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name','tc']
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return self.is_admin
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
#property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
The full traceback is as follows:
Traceback (most recent call last): File
"D:\jwt\lib\site-packages\django\core\handlers\exception.py", line 55,
in inner
response = get_response(request) File "D:\jwt\lib\site-packages\django\core\handlers\base.py", line 197, in
_get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\jwt\lib\site-packages\django\views\decorators\csrf.py", line 54,
in wrapped_view
return view_func(*args, **kwargs) File "D:\jwt\lib\site-packages\django\views\generic\base.py", line 103, in
view
return self.dispatch(request, *args, **kwargs) File "D:\jwt\lib\site-packages\rest_framework\views.py", line 509, in
dispatch
response = self.handle_exception(exc) File "D:\jwt\lib\site-packages\rest_framework\views.py", line 469, in
handle_exception
self.raise_uncaught_exception(exc) File "D:\jwt\lib\site-packages\rest_framework\views.py", line 480, in
raise_uncaught_exception
raise exc File "D:\jwt\lib\site-packages\rest_framework\views.py", line 506, in
dispatch
response = handler(request, *args, **kwargs) File "D:\djangoauthapi1\account\views.py", line 13, in post
user= serializer.save() File "D:\jwt\lib\site-packages\rest_framework\serializers.py", line 212, in
save
self.instance = self.create(validated_data) File "D:\jwt\lib\site-packages\rest_framework\serializers.py", line 981, in
create
raise TypeError(msg) TypeError: Got a TypeError when calling User.objects.create(). This may be because you have a writable field
on the serializer class that is not a valid argument to
User.objects.create(). You may need to make the field read-only, or
override the UserRegistrationSerializers.create() method to handle
this correctly. Original exception was: Traceback (most recent call
last): File
"D:\jwt\lib\site-packages\rest_framework\serializers.py", line 962, in
create
instance = ModelClass._default_manager.create(**validated_data) File "D:\jwt\lib\site-packages\django\db\models\manager.py", line 85,
in manager_method return getattr(self.get_queryset(), name)(*args,
**kwargs) File "D:\jwt\lib\site-packages\django\db\models\query.py", line 669, in create
obj = self.model(**kwargs) File "D:\jwt\lib\site-packages\django\db\models\base.py", line 565, in
init
raise TypeError( TypeError: User() got unexpected keyword arguments: 'password2'
i have figured out each line of code but i am unable to catch what is exactly the error, please needful help is required.
Because your serializer has password2 but User model does not have.
Just pop password2 into validated_data
from rest_framework import serializers
from account.models import User
class UserRegistrationSerializers(serializers.ModelSerializer):
password2=serializers.CharField(style={'input_type':'password'}, write_only=True)
class Meta:
model = User
fields=['email','name','tc','password','password2']
extra_kwargs={
'password':{'write_only':True}
}
def validate(self, attrs):
password=attrs.get('password')
password2=attrs.pop('password2')
if password != password2:
raise serializer.ValidationError("Password and Confirm Password Does not match")
return attrs
def create(self, validate_data):
return User.objects.create_user(**validate_data)
I am using the User model (which is a custom one) in my models.py by import settings and getting it through the AUTH_USER_MODEL but it seems like in my views that the request.user is not recognize as an instance of the user class.
Here is the model
from django.db import models
from django.conf import settings
from django.utils import timezone
User = settings.AUTH_USER_MODEL
class Site(models.Model):
name = models.CharField(
max_length=100,
)
slug = models.SlugField(max_length=20)
admin = models.ForeignKey(
User,
related_name="administrators",
on_delete=models.SET_NULL,
blank=True,
null=True,
)
people = models.ManyToManyField(User)
def __str__(self):
return self.name
HERE is the logic in the views
def create_site(request):
user = request.user
print(user)
form = CreateSiteForm(
request.POST or None,
initial={
"admin": user,
},
)
if form.is_valid():
form.save()
return redirect("projects")
context = {
"form": form,
}
return render(request, "tracking/create-site.html", context)
Here is the error from the terminal
return self.is_bound and not self.errors
File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\forms\forms.py", line 170, in errors
self.full_clean()
File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\forms\forms.py", line 374, in full_clean
self._post_clean()
File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\forms\models.py", line 408, in _post_clean
self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\forms\models.py", line 63, in construct_instance
f.save_form_data(instance, cleaned_data[f.name])
File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\db\models\fields\__init__.py", line 910, in save_form_data
setattr(instance, self.name, data)
File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\db\models\fields\related_descriptors.py", line 215, in __set__
raise ValueError(
ValueError: Cannot assign "'papis'": "Site.admin" must be a "User" instance.
The request.user returns the username of the user. I am wondering what is the problem.
Any help would be appreciated.
Thanks in advance......
use this instead of the User in the models
from django.contrib.auth.models import User
and change your views to this
user=request.user.id
I'm trying to make a follower system using django and have come accross this issue can someone please help me with it, or give me some suggestions regarding making a follower system with django.
the traceback is as following
Traceback:
File "C:\Users\Mustafa
Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py"
in inner
34. response = get_response(request)
File "C:\Users\Mustafa
Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py"
in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Mustafa
Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py"
in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Mustafa
Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py"
in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\Users\Mustafa
Lakhani\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py"
in dispatch
88. return handler(request, *args, **kwargs)
File "D:\sb\blog\views.py" in get
186. if request.user.is_authenticated():
Exception Type: TypeError at /user/mustafalakhani/follow Exception
Value: 'bool' object is not callable
the code is given below
models.py
class Profile(models.Model):
user=models.OneToOneField(User, on_delete=models.CASCADE)
image=models.ImageField(default='default.jpg',upload_to='profile_pics',blank=True)
description=models.TextField(max_length=200, blank=True)
following = models.ManyToManyField(User, related_name='followed_by', blank=True)
def __str__(self):
return f'{self.user.username} Profile'
def saveimg(self):
super().save()
img=Image.open(self.image.path)
if img.height>300 or img.width>300:
output_size=(300,300)
img.thumbnail(output_size)
img.saveimg(self.image.path)
views.py
class UserFollowView(View):
def get(self, request, username, *args, **kwargs):
toggle_user=get_object_or_404(User,username__iexact=username)
if request.user.is_authenticated():
user_profile, created=Profile.objects.get_or_create(request.user)
if toggle_user in user_profile.following.all():
user_profile.following.remove(toggle_user)
else:
user_profile.following.add(toggle_user)
return HttpResponseRedirect(home)
urls.py
path('user/<str:username>/follow', UserFollowView.as_view(),name='follow_user'),
In Django 2, user.is_authenticated is an attribute, so you you need to drop the ()
request.user.is_authenticated
user.is_authenticated is a boolean. That it means it can either be True or False. As it is not a function, nothing is returned when you attempt to call it.
Simply remove the parentheses that indicate that you'd like to call it:
if request.user.is_authenticated:
I'm fairly new to Django REST framework and I've tried to write an API for my mobile application. I'm facing an issue where a PUT request works fine (updates data) apart from the fact it returns response 500 (Internal Server Error). Some guidance towards resolving this would be much appreciated.
views.py:
#csrf_exempt
def category_instance(request, pk):
"""
Returns Category instance
"""
try:
cat = Category.objects.get(pk=pk)
except Category.DoesNotExist:
return HttpResponse("Error: category does not exist", status=404)
if request.method == 'GET':
serializer = CategorySerializer(cat, many=False)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'PUT':
serializer = CategorySerializer(cat, data=request.data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, 200)
return JsonResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
cat.delete()
return HttpResponse(status=204)
else:
return HttpResponse(status=400)
models.py:
class Category(models.Model):
name = models.CharField(max_length=25, blank=False)
class Meta:
ordering = ('id',)
serializers.py:
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'name')
urls.py:
urlpatterns = [
path('category/<int:pk>/', views.category_instance)
]
I've tried to look for similar issues that other people may have had, but I was unable to construct a solution to my problem.
Traceback:
Internal Server Error: /category/1/
Traceback (most recent call last):
File "C:\Users\vaida\Documents\Coding\android-tm-api\venv\lib\site-packages\django\core\handlers\exception.py", line 34,
in inner
response = get_response(request)
File "C:\Users\vaida\Documents\Coding\android-tm-api\venv\lib\site-packages\django\core\handlers\base.py", line 126, in
_get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\vaida\Documents\Coding\android-tm-api\venv\lib\site-packages\django\core\handlers\base.py", line 124, in
_get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\vaida\Documents\Coding\android-tm-api\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, i
n wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\vaida\Documents\Coding\android-tm-api\android_tm_api\api\views.py", line 146, in category_instance
serializer = CategorySerializer(cat, data=request.data)
AttributeError: 'WSGIRequest' object has no attribute 'data'
The issue was resolved by replacing the views with generic class-based views instead.
I am learning Django and I am trying to make my own custom registration forms. I currently ran into this error:
Unknown field(s) (user) specified for User
Here is the traceback:
Traceback:
File "/Users/username/Development/django_tutorial/lib/python2.7/site-packages/Django-1.6.2-py2.7.egg/django/core/handlers/base.py" in get_response
101. resolver_match = resolver.resolve(request.path_info)
File "/Users/username/Development/django_tutorial/lib/python2.7/site-packages/Django-1.6.2-py2.7.egg/django/core/urlresolvers.py" in resolve
320. sub_match = pattern.resolve(new_path)
File "/Users/username/Development/django_tutorial/lib/python2.7/site-packages/Django-1.6.2-py2.7.egg/django/core/urlresolvers.py" in resolve
222. return ResolverMatch(self.callback, args, kwargs, self.name)
File "/Users/username/Development/django_tutorial/lib/python2.7/site-packages/Django-1.6.2-py2.7.egg/django/core/urlresolvers.py" in callback
229. self._callback = get_callable(self._callback_str)
File "/Users/username/Development/django_tutorial/lib/python2.7/site-packages/Django-1.6.2-py2.7.egg/django/utils/functional.py" in wrapper
32. result = func(*args)
File "/Users/username/Development/django_tutorial/lib/python2.7/site-packages/Django-1.6.2-py2.7.egg/django/core/urlresolvers.py" in get_callable
96. mod = import_module(mod_name)
File "/Users/username/Development/django_tutorial/lib/python2.7/site-packages/Django-1.6.2-py2.7.egg/django/utils/importlib.py" in import_module
40. __import__(name)
File "/Users/username/Development/django_tutorial/bin/django_test/django_test/views.py" in <module>
10. from forms import MyRegistrationForm
File "/Users/username/Development/django_tutorial/bin/django_test/django_test/forms.py" in <module>
7. class MyRegistrationForm(UserCreationForm):
File "/Users/username/Development/django_tutorial/lib/python2.7/site-packages/Django-1.6.2-py2.7.egg/django/forms/models.py" in __new__
292. raise FieldError(message)
Exception Type: FieldError at /accounts/register/
Exception Value: Unknown field(s) (user) specified for User
I think the problem resides within this piece of code:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class MyRegistrationForm(UserCreationForm):
email = forms.EmailField(required = True)
# hold anything that isnt a form field (meta data)
class Meta:
model = User
fields = ('user', 'email', 'password1', 'password2')
def save(self, commit = True):
# save(commit = T/F) means save or dont save yet
# calls the super method of this class (UserCreationForm) and calling it's save method with input as false
user = super(MyRegistrationForm, self).save(commit = False)
# cleaned_data makes things save to put in data base
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
I think you mean field "username". Model User haven't field "user".
Right:
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')