Why User model has type string? - django

I have a view that returns data corresponded to the user, but when I try to find the User I get this error:
Type str has no object method
File views.py
from .models import Question, User
#api_view(['POST'])
#renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def answers_view(request, *args, **kwargs):
userstring = request.data["name"]
try:
user0 = User.objects.get(username=userstring)
except ObjectDoesNotExist:
user0 = "NotFound"
print("USER: ", user0, flush = True)
File models.py
from django.db import models
# Create your models here.
import random
from django.conf import settings
from django.db import models
from django.db.models import Q
User = settings.AUTH_USER_MODEL

The AUTH_USER_MODEL setting is a string, this is often used to refer to the user model, for example in a ForeignKey, the advantage of this is that at that moment, the user model does not have to be loaded (yet).
In order to get a reference to the model, you use the get_user_model() function [Django-doc]:
from .models import Question
from django.contrib.auth import get_user_model
#api_view(['POST'])
#renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def answers_view(request, *args, **kwargs):
userstring = request.data['name']
try:
user0 = get_user_model().objects.get(username=userstring)
except ObjectDoesNotExist:
user0 = 'NotFound'
print('USER: ', user0, flush=True)

Related

Django rest framework-delete user but Table doesn't exist

Table AWSIOt.User_set_user doesn't exist
image to show error
Hello, everybody, this is my first post.
I tried to delete a user by using user.delete(). However, it didn;t find user from table auth_user.
It looked for user from project.appname_user. I didn't create model user in my app and i writed "from django.contrib.auth.models import User" in top of my view file.
here are all my code
from django.contrib.auth.models import User
from .head import *
class UserDeleteView(APIView):
def get(self, request):
try:
user_id = self.request.query_params.get('user_id')
user = User.objects.get(id=user_id)
user.delete()
return Response(Return_msg())
except User.DoesNotExist:
return Response(Return_msg(None, True, 'Failed, user does not exist!!!'))
so, how can i fix it???
Frank. Your bug is probably related to the fact you're using wildcard import from .head import *. That might be causing namespace collision with User.
I would recommend you to consider using delete method from APIView as the snippet below:
views.py
from django.contrib.auth.models import User
from rest_framework.response import Response
from rest_framework import status
from django.http import Http404
class UserDetailsView(APIView):
def get_object(self, pk):
try:
return User.objects.get(pk=pk)
except User.DoesNotExist:
raise Http404
def delete(self, request, pk, format=None):
user = self.get_object(pk)
user.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("user/<int:pk>/", views.UserDetailsView.as_view(), name="details_user"),
]

I Want To Add Permissions To User in Django?

i want to add user profile section for example superuser and simple_user so i can add permissions
But When I Submit my Registration Form I Get This Error:
AttributeError at /register/
'User' object has no attribute 'register'
How To Fix And Save User Profile Name?
Here is my Views.py
from django.shortcuts import render , get_object_or_404,redirect
from django.utils import timezone
from blog.models import *
from blog.forms import *
from django.contrib.auth.decorators import login_required
from django.urls import reverse_lazy
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.
def user_register(request):
if request.method == "POST":
reg = register(request.POST or None)
if reg.is_valid():
user = reg.save()
user.profile = "simple_user"
user.set_password(user.password)
user.save()
else:
print(register.errors)
else:
reg = register()
return render(request,"registration/register.html",{'reg':reg})
Here is my Models.py
class register(models.Model):
user = models.OneToOneField(User,on_delete="Cascade", related_name="profile")
Here is my Forms.py
class register(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'input-field'}))
class Meta():
model = User
fields = ('username','email','password')
Here is the Error Image:
Any Help Appreciated!
try this
user = reg.save()
p1 = register(user=user, #other colums if have) # register model
p1.save()
# user.profile = "simple_user"
user.set_password(user.password)
user.save()
hope it helps

How can i fetch data from django models(database) using celery(asynchronously) from previously existing data

tasks.py
import string
from django.contrib.auth.models import User
from django.utils.crypto import get_random_string
from celery import shared_task
#shared_task
def create_random_user_accounts(total):
for i in range(total):
username = 'user_{}'.format(get_random_string(10, string.ascii_letters))
email = '{}#example.com'.format(username)
password = get_random_string(50)
User.objects.create_user(username=username, email=email, password=password)
return '{} random users created with success!'.format(total)
views.py
from django.contrib.auth.models import User
from .tasks import create_random_user_accounts
from django.http import JsonResponse
def users(request):
obj = list(User.objects.values())
create_random_user_accounts.delay(20)
return JsonResponse(obj,safe=False)
here i am inserting some random datas to User model using celery
And it is working while fetching same data.
But, i want to fetch 'existing data' from database 'without inseting' them on same request.
Please share me some idea how can i do that.
Method #1 do the insert off a POST and then retrieve via a GET:
from django.contrib.auth.models import User
from .tasks import create_random_user_accounts
from django.http import JsonResponse
from django.views.generic import View
class UserView(View):
def get(self, request, *args, **kwargs):
obj = list(User.objects.values())
return JsonResponse(obj,safe=False)
def post(self, request, *args, **kwargs):
create_random_user_accounts.delay(20)
obj = list(User.objects.values())
return JsonResponse(obj,safe=False)
Method #2 is just to remove the call to create_random_user_accounts, since that is what is creating the accounts:
from django.contrib.auth.models import User
from .tasks import create_random_user_accounts
from django.http import JsonResponse
def users(request):
obj = list(User.objects.values())
# create_random_user_accounts.delay(20)
return JsonResponse(obj,safe=False)

Dynamically remove a product from queryset if added to cart -- django

This is my original thought on how to accomplish this:
products = Product.objects.all()
for product in products:
if product in cart:
products = Product.objects.exclude(product)
My two questions are:
1.) Does this work/ make sense?
2.) Which .py file would I put it in?
views.py
from django.shortcuts import render
from django.shortcuts import HttpResponseRedirect
from django.core.urlresolvers import reverse
from .models import Dropoff, DropoffItem
from products.models import Product
from .forms import AddDropoffItemForm
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth.decorators import login_required
def add_item_dropoff_order(request):
request.session.set_expiry(120000)
try:
user = request.user
the_id = request.session['dropoff_id']
dropoff = Dropoff.objects.get(id=the_id)
except:
user = request.user
new_dropoff_order = Dropoff(user=user)
new_dropoff_order.save()
request.session['dropoff_id'] = new_dropoff_order.id
the_id = new_dropoff_order.id
dropoff = Dropoff.objects.get(id=the_id)
try:
product = Product.objects.get(sku=sku)
except Product.DoesNotExist:
pass
except:
pass
form = AddDropoffItemForm(request.POST or None)
if request.method == "POST":
product_sku = str(request.POST['product'])
dropoff_item = DropoffItem.objects.create(dropoff=dropoff, product_id=product_sku)
dropoff_item.save()
return HttpResponseRedirect('%s'%(reverse('add_item_dropoff_order')))
context = {
"dropoff": dropoff,
"form": form,
}
return render(request, 'dropoffs/add_item_dropoff_order.html', context)
forms.py
from django import forms
from .models import Dropoff, DropoffItem
from products.models import Product
class AddDropoffItemForm(forms.ModelForm):
product = forms.ModelChoiceField(queryset=Product.objects.all(), widget=forms.Select(attrs={'class':'form-control'}))
class Meta:
model = DropoffItem
fields = ["product"]
So basically, once dropoff_item.save() occurs, I want to remove that product from the queryset being called in the forms.py file.
Is it possible to redefine the queryset in the views and then call it again in the forms.py?
No, not really :) I would approach this like:
products = Product.objects.exclude(id__in=cart.product_ids)
Without seeing your application logic, it's impossible to tell you where to put this code, but since you've tagged django views, I'm assuming you want it in a view.

django profile creation, set User profile while using multiple profile types

I am stuck at user registration, I actually intends to have different profile types. While registration I am unable to set UserProfile while creating a user. I am using UserCreationForm. code in my files are as following.
from django.contrib.auth.forms import UserCreationForm
from registration.forms import RegistrationForm
from django import forms
from django.contrib.auth.models import User
from accounts.models import UserProfile
from django.utils.translation import ugettext_lazy as _
from person.models import Person
from pprint import pprint
class UserRegistrationForm(UserCreationForm):
#email = forms.EmailField(label = "Email")
fullname = forms.CharField(label = "Full name")
class Meta:
model = User
fields = ("email","fullname","password1","password2" )
def __init__(self, *args, **kwargs):
super(UserRegistrationForm, self).__init__(*args, **kwargs)
del self.fields['username']
def clean_email(self):
"""
Validate that the supplied email address is unique for the
site.
"""
if User.objects.filter(email__iexact=self.cleaned_data['email']):
raise forms.ValidationError(_("This email address is already in use. Please supply a different email address."))
return self.cleaned_data['email']
def save(self, commit=True):
user = super(UserRegistrationForm, self).save(commit=False)
#user_profile=user.set_profile(profile_type="Person")
UserProfile.profile.person.full_name = self.cleaned_data["fullname"]
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user
class CompanyRegistrationForm(UserCreationForm):
email=forms.EmailField(label="Email")
class UserProfileForm(forms.ModelForm):
class Meta:
model=UserProfile
exclude=('user',)
accounts/models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user=models.OneToOneField(User)
meta_keywords=models.CharField("Meta Keywords",max_length=255,
help_text="Comma delimited set of keywords of meta tag")
meta_description=models.CharField("Meta Description",max_length=255,
help_text='Content for description meta tag')
def __unicode__(self):
return "User Profile for: "+self.username
class Meta:
ordering=['-id']
views.py
from django.contrib.auth.forms import UserCreationForm
from django.template import RequestContext
from django.shortcuts import render_to_response,get_object_or_404
from django.core import urlresolvers
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from accounts.forms import UserRegistrationForm, UserProfileForm
#from accounts.forms import UserProfile
def register(request,template_name="account/register.html"):
if request.method=='POST':
postdata=request.POST.copy()
form=UserRegistrationForm(postdata)
user_profile=UserProfileForm(postdata)
if form.is_valid():
form.save()
un=postdata.get('username','')
pw=postdata.get('password','')
from django.contrib.auth import login,authenticate
new_user=authenticate(username=un,password=pw)
if new_user and new_user.is_active:
login(request,new_user)
url=urlresolvers.reverse('dashboard')
return HttpResponseRedirect(url)
else:
form=UserRegistrationForm()
page_title="User Registration"
return render_to_response(template_name,locals(),context_instance=RequestContext(request))
#login_required
def dashboard(request):
pass
#login_required
def settings(request):
pass
As I am using multiple profiles so following is code of one of those profiles' models.py:
from django.db import models
from django.contrib.auth.models import User
from accounts.models import UserProfile
class Person(UserProfile):
skills=models.CharField(max_length=100)
fullname=models.CharField(max_length=50)
short_description=models.CharField(max_length=255)
is_online=models.BooleanField(default=False)
tags=models.CharField(max_length=50)
profile_pic=models.ImageField(upload_to="person_profile_images/")
profile_url=models.URLField()
date_of_birth=models.DateField()
is_student=models.BooleanField(default=False)
current_designation=models.CharField(max_length=50)
is_active_jobseeker=models.BooleanField(default=True)
current_education=models.BooleanField(default=True)
class Meta:
db_table='person'
My profile auth in settings.py
AUTH_PROFILE_MODULE='accounts.UserProfile'
Here is a file that also I used after looking at some other place, profile.py:
from accounts.models import UserProfile
from accounts.forms import UserProfileForm
from person.models import Person
from company.models import Company
def retrieve(request,profile_type):
try:
profile=request.user.get_profile()
except UserProfile.DoesNotExist:
if profile_type=='Person':
profile=Person.objects.create(user=request.user)
else:
profile=Company.objects.create(user=request.user)
profile.save()
return profile
def set(request,profile_type):
profile=retrieve(request,profile_type)
profile_form=UserProfileForm(request.POST,instance=profile)
profile_form.save()
I am new and confuse, have seen documentation also. Also saw other solutions at stackoverflow.com but didn't find any solution of my problem. So please tell if you find anything helpful for me. It doesn't seems to be a big problem but as I am new to it so it is a problem for me.
Multiple profile types won't work with the OneToOne relation that is required by Django profile mechanism. I suggest you keep a single profile class containing data common to all profile types and you store type-specific data in a separate set of classes that you link to your profile class using a generic relation.
EDIT:
Thanks for the clarification. Looking at your code again today it seems that you might indeed be able to accomplish what your trying to do with model inheritance. I think the problem is in the save() method of UserRegistrationForm. Try something like this:
def save(self, commit=True):
user = super(UserRegistrationForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
if commit:
user.save()
person = Person(user=user)
person.full_name = self.cleaned_data["fullname"]
person.save()
return user