Profile() got an unexpected keyword argument 'user' - python

Hi i working with Django .
I'm trying to turn my user into a profile with signals
When registering the user through a form
I get the following error :
TypeError at /Registro/ Profile() got an unexpected keyword argument 'user' and
the user is created in 'AUTHENTICATION AND AUTHORIZATION' (ADMIN), but not in profiles.
Models.py
from django.db import models
class Profile(models.Model):
id = models.AutoField(primary_key=True)
nombreUsuario = models.CharField('Nombre usuario : ', max_length=15, null = False, blank=False, unique=True)
email = models.EmailField('Email', null=False, blank=False, unique=True)
password = models.CharField('Contraseña', max_length=25, null=False, blank=False, default='')
#Unique sirve para validar si el usuario existe y sea unico el email y nombre de usuario.
nombres = models.CharField('Nombres', max_length=255, null= True, blank=True)
apellidos = models.CharField('Apellidos', max_length=255, null=True, blank=True)
imagen = models.ImageField(upload_to='img_perfil/',default='batman.png',null=True, blank=True)
fecha_union = models.DateField('Fecha de alta', auto_now = False, auto_now_add = True)
facebook = models.URLField('Facebook', null=True, blank=True)
instagram = models.URLField('Instagram', null=True, blank=True)
def __str__(self):
return f'Perfil de {self.nombreUsuario}'
class Meta:
verbose_name = "Perfil"
verbose_name_plural = "Perfiles"
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.views.generic.edit import FormView
from .models import Profile
from .forms import RegistrationForm
from django.contrib import messages
from django.contrib.auth.models import Group
from django.utils.decorators import method_decorator
def iniciarSesion(request):
return render(request,'social/inicio.html')
def registro(request):
if request.method == 'POST':
fm = RegistrationForm(request.POST)
if fm.is_valid():
user=fm.save()
username = fm.cleaned_data.get('username')
messages.success(request,'Registration Created Successfully')
redirect('feed')
else:
fm = RegistrationForm()
return render(request, 'social/registrarse.html',{'fm':fm})
def feed(request):
return render(request,'social/feed.html')
def profile(request):
return render(request,'social/profile.html')
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class RegistrationForm(UserCreationForm):
class Meta:
model=User
fields=[
'username',
'email',
'first_name',
'last_name',
]
signals.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.contrib.auth.models import Group
from .models import Profile
def create_user_profile(sender, instance, created, **kwargs):
if created:
#group = Group.objects.get(name = 'profile')
#instance.groups.add(group)
Profile.objects.create(
user = instance,
name= instance.username,
)
Profile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
I need help with this code!

Well, what exactly did you expect? Your Profile model doesn't seem to have a fk to user and that's what you are trying to do (twice) in the signal.
Just add user fk to User model and create it once in the signal.

Related

ValueError at /signup/ Cannot assign "<User: prosenjit>": "Referral.parent" must be a "Referral" instance

After reading a lot of answers similar to this problem I got a specific error in every single case.
In the following, I have attached my mandatory code.
Models.py
import uuid
import enum
from django.db import models
from django.utils import timezone, translation
from django.conf import settings
from django.core.validators import MinValueValidator, MaxValueValidator
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django_numerators.models import NumeratorMixin
from mptt.models import MPTTModel, TreeForeignKey, TreeManager
_ = translation.gettext_lazy
from .utils import generate_ref_code
class Referral(NumeratorMixin, MPTTModel, models.Model):
class Meta:
verbose_name = _('Referral')
verbose_name_plural = _('Referral')
unique_together = ('parent', 'account')
limit = 3
parent = TreeForeignKey(
'self', null=True, blank=True,
on_delete=models.SET_NULL,
related_name='downlines',
verbose_name=_('Up Line'))
account = models.OneToOneField(
get_user_model(),
on_delete=models.CASCADE,
verbose_name=_('account'))
balance = models.DecimalField(
default=0,
max_digits=15,
decimal_places=2,
editable=False,
verbose_name=_("Balance"))
created_at = models.DateTimeField(
default=timezone.now, editable=False)
code = models.CharField(max_length=12, blank=True)
def __str__(self):
return (
self.account.username
if self.account.get_full_name() in ['', None]
else self.account.get_full_name()
)
def update_balance(self, balance):
self.balance = balance
self.save()
def get_referral_limit(self):
return getattr(settings, 'REFERRAL_DOWNLINE_LIMIT', None) or self.limit
def get_uplines(self):
return self.get_ancestors(include_self=False, ascending=True)[:self.get_referral_limit()]
def save(self, *args, **kwargs):
if self.code == "":
code = generate_ref_code()
self.code = code
super().save(*args, **kwargs)
Everything is working well and 100% worked if I add foreignkey instead of TreeForeignKey in the parent field
parent = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name='ref_by')
Instead Of
parent = TreeForeignKey(
'self', null=True, blank=True,
on_delete=models.SET_NULL,
related_name='downlines',
verbose_name=_('Up Line'))
But I need TreeForeignKey because of my multilevel referral system.
utils.py
import uuid
import json
from django.core.serializers.json import DjangoJSONEncoder
from uuid import UUID
import random
def generate_ref_code():
code = str(uuid.uuid4()).replace("-", "")[:12]
return code
signals.py
from .models import Referral
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=User)
def post_save_create_profile(sender, instance, created, *args, **kwargs):
if created:
Referral.objects.create(account=instance)
views.py
#csrf_protect
def signup_view(request):
profile_id = request.session.get('ref_profile')
print('profile_id', profile_id)
form = SignupForm(request.POST or None)
if form.is_valid():
if profile_id is not None:
recommended_by_profile = Referral.objects.get(id=profile_id)
print("recommended_by_profile", recommended_by_profile)
instance = form.save()
print("instance saved", instance)
registered_user = User.objects.get(id=instance.id)
print("registered_user", registered_user)
registered_profile = Referral.objects.get(account=registered_user)
print("registered_profile", registered_profile)
registered_profile.parent = recommended_by_profile.account
print("registered_profile.parent", registered_profile.parent)
# print("registered_profile.user", registered_profile.user)
print("registered_profile.account", registered_profile.account)
print("recommended_by_profile.parent", recommended_by_profile.parent)
# print("recommended_by_profile.user", recommended_by_profile.user)
print("recommended_by_profile.account", recommended_by_profile.account)
registered_profile.save()
print("registered_profile it's saved", registered_profile)
else:
print("Referral not working")
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=password)
login(request, user)
return redirect('main_view')
context = {
'form': form
}
return render(request, 'signup.html', context)
I have also attached the image of the error where you can see the specific one. Here is the main issues with a data type that is not passing on the "parent" field when using "TreeForeignKey".
Any kind of help or suggestion would be appreciated related the question.
Thanks

Django IntegrityError at /accounts/signup/: NOT NULL constraint failed: accounts_subject.gender

Basically I am trying to create a user registration form with a few more fields than the default User model apparently brings. So I created another model with a 1 to 1 relationship with the Model User and this works (in django admin I can create Subjects (that's what I call this class "extended") related to some user).
When I use my registration form, the idea is that a User is created (with its usual attributes: username, email, password) and also a Subject related to that User that has the rest of the attributes that I want to save (gender, level of studies, year of birth, etc)
But, when using it only the User is saved in the database (the Subject is not saved) and I get the following error:
IntegrityError at /accounts/signup/
NOT NULL constraint failed: accounts_subject.gender
Here is my code:
models.py:
from django.db import models
import uuid
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Subject(models.Model):
GENDER_CHOICES = (
('M', 'Masculino'),
('F', 'Femenina'),
)
EDUCATIONLEVEL_CHOICES = (
('P', 'Primaria'),
('S', 'Secundaria'),
('T', 'Terciaria'),
('U', 'Universitaria'),
)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
gender = models.CharField(max_length=20, choices=GENDER_CHOICES, default=None)
education_level = models.CharField(max_length=20, choices=EDUCATIONLEVEL_CHOICES, default='P')
email = models.EmailField(max_length=50)
nationality = models.CharField(max_length=100, default='Argentina')
country_of_residence = models.CharField(max_length=100, default='Argentina')
year_of_birth = models.IntegerField(default=None)
experiment = models.ManyToManyField(Experiment, default=None)
points = models.IntegerField(default=0)
def __str__(self):
return self.email
#receiver(post_save, sender=User)
def update_profile_signal(sender, instance, created, **kwargs):
print(instance, type(instance))
if created:
try:
Subject.objects.create(user=instance)
instance.subject.save()
except Subject.DoesNotExist:
print("No se pudo crear un sujeto para este usuario")
forms.py:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class SignUpForm(UserCreationForm):
GENDER_CHOICES = (
('M', 'Masculino'),
('F', 'Femenina'),
)
EDUCATIONLEVEL_CHOICES = (
('P', 'Primaria'),
('S', 'Secundaria'),
('T', 'Terciaria'),
('U', 'Universitaria'),
)
username = forms.CharField(max_length=30, help_text='Nombre de usuario', required=True)
gender = forms.TypedChoiceField(initial=1, choices=GENDER_CHOICES, help_text='Genero', required=False)
education_level = forms.TypedChoiceField(initial=1, choices=EDUCATIONLEVEL_CHOICES, help_text='Maximo nivel educativo alcanzado', required=False)
email = forms.EmailField(max_length=50, help_text='Email', required=False)
nationality = forms.CharField(max_length=100, help_text='Nacionalidad', required=False)
country_of_residence = forms.CharField(max_length=100, help_text='Pais de residencia', required=False)
year_of_birth = forms.IntegerField(help_text='Año de nacimiento', required=False)
class Meta:
model = User
fields = ('username', 'gender', 'education_level', 'email', 'nationality', 'country_of_residence', 'year_of_birth', 'password1', 'password2', )
views.py:
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
from .forms import SignUpForm
def signup_view(request):
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db()
user.subject.gender = form.cleaned_data.get('gender')
user.subject.education_level = form.cleaned_data.get('education_level')
user.subject.email = form.cleaned_data.get('email')
user.subject.nationality = form.cleaned_data.get('nationality')
user.subject.country_of_residence = form.cleaned_data.get('country_of_residence')
user.subject.year_of_birth = form.cleaned_data.get('year_of_birth')
user.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=password)
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
If I write in the attribute gender null = True the error does not occur, but even if I put information in my form for that field, it is not saved in the database.
I was looking for a solution to this problem on stackoverflow and tried to follow some tips but with no success yet.
Thank you so much for the help!

Django: Signal not automatically not creating attribute to User

I have a problem using Djangos Signals while creating a User and a Profile.
I'm trying to create a Profile upon creating a User, but I keep getting the error:
AttributeError at /user/create/
'User' object has no attribute 'profile'
So here is my User Model:
from django.db import models
from django.contrib.auth.models import AbstractUser
from django_countries.fields import CountryField
class User(AbstractUser):
"""auth/login-related fields"""
is_a = models.BooleanField('a status', default=False)
is_o = models.BooleanField('o status', default=False)
def _str_(self):
return "{} {}".format(self.first_name, self.last_name)
and here is my Profile Model:
from django.db import models
from django_countries.fields import CountryField
from django.contrib.auth import get_user_model
User = get_user_model()
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
"""non-auth-related/cosmetic fields"""
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='Profile')
birth_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True)
nationality = CountryField(null=True)
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True)
def __str__(self):
return f'{self.user.username} Profile'
My User Serializer:
from rest_framework import serializers
from django.contrib.auth import get_user_model
from ..models.model_user import *
class UserIndexSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = [
'id',
'username',
'password',
'first_name',
'last_name',
'email',
'is_a',
'is_o'
]
class UserCreateSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = [
'username',
'password',
'first_name',
'last_name',
'email',
'is_a',
'is_o'
]
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User(
username=validated_data['username'],
password=validated_data['password'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
email=validated_data['email'],
is_a=validated_data['is_a'],
is_o=validated_data['is_o']
)
user.set_password(validated_data['password'])
user.save()
return user
class UserDetailsSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
My signals.py:
from django.db.models.signals import post_save
from django.contrib.auth import get_user_model
User = get_user_model()
from django.dispatch import receiver
from .models.model_profile import *
"""receivers to add a Profile for newly created users"""
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
And when I'm using Postman to post a User:
{
"username":"16",
"password":"12345678",
"first_name":"Al",
"last_name":"Pongvf",
"email":"ahgj#live.fr",
"is_a":"False",
"is_o":"False"
}
It gives me this error message:
AttributeError at /user/create/
'User' object has no attribute 'profile'
I've searched for a solution, but I didn't get lucky:
StackOverflow
1
StackOverflow
2
Medium
Does anyone know what am I missing? or doing wrong?
Thanks!
Your related_name="Profile" on the Proflile model is Profile with a capital. You need to reference it with a capital to use it. I would recommend you rename it to lowercase and make new migrations.
For example:
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.Profile.save()
But really you should change this:
class Profile(models.Model):
"""non-auth-related/cosmetic fields"""
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')

Django - Logged in User Not Populating in admin.py

I’m trying to create a form to when the current logged in user makes a submission the user column in admin.py gets populated with the logged in user.
My problem:
The user column gets populated when a new user gets created using the CustomUserCreationForm however when the newly created user makes a form submission with the form listed below, the user column doesn’t get populated.
The Custom User Model that I'm trying to get the username from is located in from users.models import CustomUser so I’m not sure why this isn’t working.
How do I get the current logged in user to populate in admin.py in the users column with the form listed below?
Any help i gladly appreciated, thanks.
Code Below:
user_profile/models
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import AbstractUser, UserManager
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from users.forms import CustomUserCreationForm, CustomUserChangeForm
from users.models import CustomUser
class Listing (models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True)
created = models.DateTimeField(auto_now_add=True, null=True)
updated = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
zip_code = models.CharField(max_length=100)
mobile_number = models.CharField(max_length=100)
cc_number = models.CharField(max_length=100)
cc_expiration = models.CharField(max_length=100)
cc_cvv = models.CharField(max_length=100)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = Listing.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=CustomUser)
user_profile/admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from user_profile.forms import HomeForm
from users.forms import CustomUserCreationForm, CustomUserChangeForm
from user_profile.models import Listing
from users.models import CustomUser
# Register models here.
class UserProfileAdmin(admin.ModelAdmin):
list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'user']
list_filter = ['name', 'zip_code', 'created', 'updated', 'user']
admin.site.register(Listing, UserProfileAdmin)
user_profile/views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.conf import settings
from .forms import HomeForm
from users.forms import CustomUserCreationForm, CustomUserChangeForm
from .models import Listing
from users.models import CustomUser
from django.urls import reverse_lazy
# add to your views
def change_view(request):
form = HomeForm(request.POST or None)
user_profile = Listing.objects.all
if form.is_valid():
form.save()
form = HomeForm()
context = {
'form': form, 'user_profile': user_profile
}
return render(request, "myaccount.html", context)
user_profile/forms.py
import os
from django import forms
from django.forms import ModelForm
from django.forms import widgets
from django.utils import six
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import filesizeformat
from avatar.conf import settings
from avatar.models import Avatar
from .models import Listing
class HomeForm(forms.ModelForm):
user = forms.CharField(required=False, label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'CVV', 'class': 'form-control'}))
username = forms.CharField(required=False, label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'CVV', 'class': 'form-control'}))
created = forms.CharField(required=False, label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'CVV', 'class': 'form-control'}))
name = forms.CharField(required=False, label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Full Name', 'class': 'form-control'}))
address = forms.CharField(required=False, label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Address', 'class': 'form-control'}))
zip_code = forms.CharField(required=False, label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Zipcode', 'class': 'form-control'}))
mobile_number = forms.CharField(required=False, label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Mobile Number', 'class': 'form-control'}))
cc_number = forms.CharField(required=False, label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Credit Card', 'class': 'form-control'}))
cc_expiration = forms.CharField(required=False, label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Expiration Date', 'class': 'form-control'}))
cc_cvv = forms.CharField(required=False, label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'CVV', 'class': 'form-control'}))
class Meta:
model = Listing
fields = '__all__'
settings.py
AUTH_USER_MODEL = 'users.CustomUser'
Try this
forms.py
import os
from django import forms
from django.forms import ModelForm
from django.forms import widgets
from django.utils import six
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import filesizeformat
from avatar.conf import settings
from avatar.models import Avatar
from .models import Listing
class HomeForm(forms.ModelForm):
class Meta:
model = Listing
fields = ('name', 'address', 'zip_code', 'mobile_number', 'cc_number', 'cc_number', 'cc_expiration', 'cc_cvv')
Add in models file
class ListingManager(models.Manager):
def save_from_object(self, request, obj):
obj.user = request.user
obj.save()
Add Update your Listing Model with objects as new manager
class Listing (models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True)
created = models.DateTimeField(auto_now_add=True, null=True)
updated = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
zip_code = models.CharField(max_length=100)
mobile_number = models.CharField(max_length=100)
cc_number = models.CharField(max_length=100)
cc_expiration = models.CharField(max_length=100)
cc_cvv = models.CharField(max_length=100)
objects = ListingManager()
This should work, Also I am not sure about your idea of keeping user as OneToOneField (This will not allow having multiple records with same user instance), I think you need to change it to ForeignKey. Refer What's the difference between django OneToOneField and ForeignKey?

django rest framework add user and create data in db

every one,I now using django rest framework(3.4) on my project(django 1.8+),I can create new user but I can not use new user to create data in db(I can do it in forms ok), however,I can create data in db by admin. I have to make the new user to create data in db,how can I do that?thanks for any one who reply.
models.py
class ProductsTbl(models.Model):
model_number = models.CharField(
max_length=255,
blank=True,
unique=True,
error_messages={
'unique': "這 model number 已經被註冊了 ."
}
)
name = models.CharField(max_length=255, blank=True, null=True)
material = models.CharField(max_length=255, blank=True, null=True)
color = models.CharField(max_length=255, blank=True, null=True)
feature = models.TextField(blank=True, null=True)
created = models.DateTimeField(editable=False)
modified = models.DateTimeField(auto_now=True)
release = models.DateTimeField(blank=True, null=True)
twtime = models.DateTimeField(blank=True, null=True)
hktime = models.DateTimeField(blank=True, null=True)
shtime = models.DateTimeField(blank=True, null=True)
jptime = models.DateTimeField(blank=True, null=True)
suggest = models.TextField(blank=True, null=True)
description = models.TextField(blank=True, null=True)
cataloggroup = models.ManyToManyField(CatalogGroup)
place = models.ManyToManyField(Place)
scale = models.ManyToManyField(Scale)
slug = models.SlugField(unique=True)
user = models.ForeignKey(User, blank=True, null=True)
useredit = models.CharField(max_length=32, blank=True, null=True)
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created = timezone.now()
return super(ProductsTbl, self).save(*args, **kwargs)
api/serializers.py
from rest_framework import serializers
from ..models import *
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
UserModel = get_user_model()
class ProductsTblSerializer(serializers.ModelSerializer):
class Meta:
model = ProductsTbl
fields = ('model_number',
'created',
'name',
'release',
'twtime',
'hktime',
'shtime',
'jptime',
'feature',
'material',
'suggest',
'description',
'cataloggroup',
'place',
'scale',
'slug',
'user')
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
def create(self, validated_data):
user = UserModel.objects.create(
username=validated_data['username']
)
user.set_password(validated_data['password'])
user.save()
return user
class Meta:
model = UserModel
api/urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^productsTbls/$', views.ProductsTblListView.as_view(), name='productsTbls_list'),
url(r'^productsTbls/(?P<pk>\d+)/$', views.ProductsTblDetailView.as_view(), name='productsTbls_detail'),
url(r'^productsTbls/pdelete/(?P<id>[-\w]+)/$',views.api_delete_product,name='api_delete_p'),
url(r'^productsTbls/register/$', views.CreateUserView.as_view(), name='productsTbls_register'),
]
api/views.py
from rest_framework import generics
from ..models import *
from .serializers import ProductsTblSerializer
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponse
from django.shortcuts import render, redirect
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from django.views.decorators.csrf import csrf_exempt
from django.forms import modelformset_factory
from django.template.defaultfilters import slugify
from rest_framework import permissions
from rest_framework.generics import CreateAPIView
from django.contrib.auth import get_user_model
from .serializers import UserSerializer
class ProductsTblListView(generics.ListCreateAPIView):
queryset = ProductsTbl.objects.order_by('-created')
serializer_class = ProductsTblSerializer
class ProductsTblDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = ProductsTbl.objects.all()
serializer_class = ProductsTblSerializer
class CreateUserView(CreateAPIView):
model = get_user_model()
permission_classes = [
permissions.AllowAny # Or anon users can't register
]
serializer_class = UserSerializer
#csrf_exempt
#login_required
def api_delete_product(request, id):
# grab the image
dp = ProductsTbl.objects.get(id=id)
# security check
if dp.user != request.user:
raise Http404
# delete the image
dp.delete()
# refresh the edit page
return redirect('/api/productsTbls/')
settings.py
........
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
I changed the settings.py then it can work
settings.py
......
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
#'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
I think from admin portal you need to provide permissions to user you have created for each method PUT,POST,GET or provide AllowAny permission(Which will give access to all your created user for any request). For more details refer this

Categories