DoesNotExist at /folder/ Userdata matching query does not exist. DJango Problem - django

When i use my super acc, this error does not shows up, but when I tried to use other acc. this error shows up. where did I do wrong?
The error : DoesNotExist at /voting/
Userdata matching query does not exist.
My Model :
class Userdata(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
faculty = models.ForeignKey(Fakultas, on_delete=models.CASCADE, default=1)
is_voted = models.BooleanField(default=False)
def __str__(self): return self.user.username
My views :
#login_required
def voted(response):
user = Userdata.objects.get(id=response.user.id) # get the username
if user.is_voted:
return render(response, 'Main/voting.html', {'calon': Voting.objects.order_by('id'), 'hasil': 'You Have Voted'})
if response.method == 'POST':
id = response.POST['idcalon']
calon2 = Voting.objects.get(id=id) # get user selection in html
user.is_voted = True
calon2.voters += 1
user.save()
calon2.save()
return render(response, 'Main/voting.html', {'calon': Voting.objects.order_by('id')}) # balik ke sendiri

User and UserData don't have the same primary key. So Userdata.objects.get(id=response.user.id) will not work because there is no such Userdata with the given user's id. But you do not need that, because User and Userdata have OneToOne relation. So simply use this:
user = response.user.userdata

Related

IntegrityError at /apis/addtoCart NOT NULL constraint failed Django and API?

i am trying to insert data into my OrderItem() model:
class OrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
ordered = models.BooleanField(default=False)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
with an api with json data as follows:
{ "username": "admin",
"item": "Kavya",
"quantity": "1"
}
and i my view i am recieving this data and updating like:
class addtoCart(APIView):
# permission_classes=[IsAuthenticated,]
# authentication_classes=[TokenAuthentication,]
def post(self,request):
username=request.data["username"]
itemname=request.data["item"]
quant=request.data["quantity"]
#inserting data to cart
article = OrderItem()
article.User = username
article.Item = itemname
article.quantity=quant
article.save()
query=OrderItem.objects.filter(user=username)
serializers=OrderItemSerializer(query,many=True)
return Response(serializers.data)
but whenever i try to do so i get an error:
IntegrityError at /apis/addtoCart
NOT NULL constraint failed: core_orderitem.item_id
i dont know what causing this error can someone please help <3.
You need to pass an id or other unique constraint in your request body, so that you can identify which Item object to set to the article instance, e.g.:
{
"username": "admin",
"item_id": <id>,
"quantity": "1"
}
and in your post method:
from django.shortcuts import get_object_or_404
def post(self,request):
username = request.data["username"]
item_id = request.data["item_id"]
quant = request.data["quantity"]
# since `user` is also a foreign key reference i would suggest you to query it, too
user = get_object_or_404(User, username=username)
article = OrderItem()
# set the attributes as lowercase
article.user = user
# Django creates an extra field `<foreign_key>_id` for related objects, so that you can set it without querying
article.item_id = item_id
article.quantity = quant
article.save()
# ...
But I would suggest you using DRF Serializers for dealing with request.data.

DJANGO,DRF:request id returning a NONE value instead the user object

i want to create a follower option in django using DRF so here my models.py
class Connect(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, unique = True, related_name = 'rel_from_set',on_delete=models.CASCADE)
following = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name = 'follwed_by')
def __str__(self):
return str(self.following.all().count())
urls.py
url(r'^conn/(?P<id>\d+)', ConnectApi),
serializer.py
class ConnectSerializer(serializers.ModelSerializer):
class Meta:
model=Connect
fields=('user','following')
views.py
#api_view(['GET','POST'])
def ConnectApi(request,id):
user_id=request.POST.get('id')
print(user_id)
# user_id=request.GET['id']
# action=request.POST.get('action')
if user_id :
# if user_id and action:
try:
user1=User.objects.get(id=user_id)
if user1 :
Connect.objects.get_or_create(user=request.user,
following=user1)
else:
Connect.objects.filter(user=request.user,
following=user).delete()
return JsonResponse({'status':'ok'})
except:
return JsonResponse({'status':'ki'})
return JsonResponse({'status':'ko'})
but whenever i fired up the url
http://127.0.0.1:8000/connect/conn/2
this is the response
{"status": "ko"}
and in the terminal i could see "NONE "
for print(user_id) command
i don't understand where i have done the mistake and i dont think if this is the best practice to make followers function if you know one please let me know
You are passing the id through url and it's directly available inside the view function. So, you don't want to query it from somewhere else
So, use this,
#api_view(['GET', 'POST'])
def ConnectApi(request, id):
user_id = id
print(user_id)
# your code

IntegrityError when using .save() on OneToOneField in Django

I have 2 models
class User(models.Model):
email = models.CharField(max_length = 100)
password = models.CharField(max_length = 100)
class Authentication(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
token = models.CharField(max_length =50, null = True)
Here is the code I use for login in views.py
from user.models import User, Authentication
import uuid
from django.db.utils import IntegrityError
user = User.objects.get(pk = request.user.id)
token = uuid.uuid4().hex
try:
Authentication.objects.create(user = user, token = token)
except IntegrityError:
user.authentication.token = token
user.authentication.save()
return JsonResponse({'token':token})
The problem I meet here is everytime a user login, I will generate a new token and save in the database. The error appears at the line
user.authentication.save()
The error is: django.db.utils.IntegrityError: (1062, "Duplicate entry '30' for key 'user_id' ")
The 30 is the user_id existed in Authentication models when login in the second time ( the first time login is always succeed).
I solved this problem by using these codes:
except IntegrityError:
au = Authentication.objects.get(user = user)
au.token = token
au.save()
But I dont know why i got this bug. I used to do the first approach many times but not got no bugs at all. Anyone has faced to this problem can show me the way to solve this? Thank you
The problem is that you are trying to create a new token to a user who already have one, and since you've defined a OneToOneField it is not possible. I suggest you to try the get_or_create() instead of create() method.
Alternatively, you can modify the create method:
try:
auth = Authentication.objects.create(user = request.user)
except Exception as e:
#do something
return JsonResponse({'token': auth.token})
In models.py
from user.managers import MyManager
class Authentication(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
token = models.CharField(max_length =50, null = True)
objects = MyManager()
Then create a file 'managers.py' and put this in it:
from django.db import models
import uuid
class MyManager(models.Manager):
def create(self, user):
token = uuid.uuid4().hex
if user.authentication:
user.authentication.token = token
user.authentication.save()
return user.authentication
else:
auth = self.model(user=user, token=token)
auth.save(using=self._db)
return auth
Now if you use Authentication.objects.create(user=request.user) the create method in MyManager will be invoked. This also helps to separate token generation from views.py
Cheers!
You should have look at django builtin auth system. For your approach
try:
obj = Authentication.objects.get(user=user)
obj.token = token
obj.save()
except Authentication.DoesNotExist:
Authentication.objects.create(user = user, token = token)

Slugfield URL implementation in Django

So, I am having some difficulty trying to slugify a title field in my model and still have it return the proper information.
Currently, a user can follow the url, if the list in their account exists under this regular expression:
url(r'^user/(?P<username>\w+)/list/(?P<listname>\w+)/$', mylistpage, name='lists'),
The issue I face is that the user can have a list containing spaces, but the regex bases their url off their list name. I am wanting to implement a slug url, but still have it retrieve the correct model/object information.
I am trying to have a slug field and then pre-populate it based on the list name, but I am lost at how this implementation is supposed to work. Much appreciation in advance from any insight.
Model
class newlist(models.Model):
user = models.ForeignKey(User)
list_name = models.CharField(max_length = 100,)
picture = models.ImageField(upload_to='profiles/', default = "/media/profiles/default.jpg")
slugurl = models.SlugField(default = slugurl(self))
def __str__(self):
return self.list_name
def slugurl(self):
return slugify(self.list_name)
Views
def mylistpage(request, username, listname):
context = RequestContext(request)
#make sure that the user is authenticated
if username == request.user.username:
#If the user is authenticated, then perform the following functions to the page
if request.user.is_authenticated():
#Store the current user request object into a variable
user = User.objects.get(username=username)
#Store the list name to the item that starts with the url input
listname = request.user.newlist_set.filter(list_name__iexact=listname)
listitems = request.user.newlist_set.all()
if not listname:
return redirect('/notfound')
else:
return redirect('/notfound')
return render_to_response('listview.html', {'lista': listname}, context)
I have used django-autoslug to great success. You can find a live example here.
SlugField is just a char field with a little syntactic sugar.
You will want to name your slug just slug so django can find it automatically in the URL resolution and passes the right parameter to views.
Your amended code would look like:
from autoslug import AutoSlugField
from django.db import models
class Newlist(models.Model): # Classes start with uppercase names by default
user = models.ForeignKey(User)
list_name = models.CharField(max_length = 100,)
picture = models.ImageField(upload_to='profiles/', default = "/media/profiles/default.jpg")
slug = AutoSlugField(populate_from='list_name')
def __str__(self):
return self.list_name
Your View:
def mylistpage(request,username, slug):
context = RequestContext(request)
#make sure that the user is authenticated
if username == request.user.username:
#If the user is authenticated, then perform the following functions to the page
if request.user.is_authenticated():
#Store the current user request object into a variable
user = User.objects.get(username=username)
#Store the list name to the item that starts with the url input
listname = request.user.newlist_set.filter(slug=slug)
listitems = request.user.newlist_set.all()
if not listname:
return redirect('/notfound')
else:
return redirect('/notfound')
return render_to_response('listview.html', {'lista': listname}, context)
urls.py
url(r'^user/(?P<username>\w+)/list/(?P<slug>[\w-]+)/$', mylistpage, name='lists'),

django form use excluded field

with django 1.5.1 I try to use the django form for one of my models.
I dont want to add the "user" field (Foreignkey) somewhere in the code instead of letting the user deceide whoes new character it is.
My Code:
Model:
class Character(models.Model):
user = models.ForeignKey(User)
creation = models.DateTimeField(auto_now_add=True, verbose_name='Creation Date')
name = models.CharField(max_length=32)
portrait = models.ForeignKey(Portrait)
faction = models.ForeignKey(Faction)
origin = models.ForeignKey(Origin)
The form:
class CreateCharacterForm(forms.ModelForm):
class Meta:
model = Character
fields = ['name', 'portrait', 'faction', 'origin']
The view:
def create_character(request, user_id):
user = User.objects.get(id=user_id)
if request.POST:
new_char_form = CreateCharacterForm(request.POST)
if new_char_form.is_valid():
new_char_form.save()
return HttpResponseRedirect('%s/characters/' % user_id)
else:
return render_to_response('create.html',
{'user': user, 'create_char':new_char_form},
context_instance=RequestContext(request))
else:
create_char = CreateCharacterForm
return render_to_response('create.html',
{'user': user, 'create_char': create_char},
context_instance=RequestContext(request))
I have tried to use a instance to incluse the userid already. i've tried to save the userid to the form before saving it, or changing the save() from my form.
I keep getting the error that character.user cant be null
I have to tell that im pretty new to django and im sure one way or another it should be possible
Can someone please help me out?
Its explained well in document model form selecting fields to use
You have to do something like this in your view
...
if request.POST:
new_char_form = CreateCharacterForm(request.POST)
if new_char_form.is_valid():
#save form with commit=False
new_char_obj = new_char_form.save(commit=False)
#set user and save
new_char_obj.user = user
new_char_obj.save()
return HttpResponseRedirect('%s/characters/' % user_id)
else:
...