What does it mean for an object to be unscriptable? - django

I don't know what's going on here... I just want to check the value of a model field and then update it accordingly... any help or insight is appreciated!
model:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
beta = models.CharField(max_length=1, blank=True, null=True)
view:
from internal.accounts.models import UserProfile
from django.contrib.auth.models import User
#login_required
def beta_testers(request):
user = User.objects.get(username=request.user.username)
user_profile = user.get_profile()
count = UserProfile.objects.filter(beta='1').count()
if count < 50 and not user_profile['beta']:
user_profile['beta'] = '1'
user_profile.save()
error:
TypeError at /utilities/beta-signup/
'UserProfile' object is unsubscriptable
Request Method: GET
Request URL: http://localhost/utilities/beta-signup/?x=1&y=15
Django Version: 1.2.1
Exception Type: TypeError
Exception Value:
'UserProfile' object is unsubscriptable
Exception Location: C:/django\internal\cms_helper\views.py in beta_testers, line 284

The error is "unSUBscriptable". Your user_profile object isn't a dictionary. Use user_profile.beta, not user_profile['beta'].

Alternatively, you can use a string with getattr:
getattr(user_profile, 'beta', False)
False is the default value; which, in your case would work with checking if the value is set or not. I found this very helpful, so I thought I would post this solution, even though the question was asked years ago. :)

Method One
model_name.object.filter(column_name='value').last
Method Two
This error happens when you tries to insert a model object in text filed

Related

Get Data from Choice field in Django rest framework

I have searched and tried out all solutions provided for this question in similar problem but they're not working for me. I am getting the following error when trying to get data from an endpoint
Got AttributeError when attempting to get a value for field
hotel_type on serializer HotelDetailSerializer. The serializer
field might be named incorrectly and not match any attribute or key on
the Hotels instance. Original exception text was: 'Hotels' object
has no attribute 'get_hotel_Type_display'.
This is my model field truncated for clarity
class Hotels(models.Model):
HOTEL_TYPE = (
('hotel', "Hotel"),
('apartment', "Apartment"),
('villa', "Villa"),
hotel_Type = models.CharField(
max_length=20,
choices=HOTEL_TYPE,
default='hotel', null=True, blank=True
#property
def hotel_type(self):
return self.get_hotel_Type_display()
This is my serializer class also truncated for clarity
class HotelDetailSerializer(serializers.ModelSerializer):
hotel_type = serializers.Field(source='hotel_type.hotel_Type')
class Meta:
model = Hotels
fields = ("hotel_type" )
This is the apiview
class HotelDetailAPIView(RetrieveAPIView):
"""Display details of a single hotel"""
queryset = Hotels.objects.all()
serializer_class = HotelDetailSerializer
permission_classes = ()
lookup_field = 'slug'
Could anyone kindly assist me figure out why this is not working? Thanks
EDIT
I am editing this question to add more context. I have been doing some debugging in Django shell. This is what i am getting
>>> from hotels.models import Hotels
>>> h = Hotels.objects.all()
>>> for n in h:
... print (n.hotel_Type)
...
(<django.db.models.fields.CharField>,)
>>> for n in h:
... print (n.get_hotel_Type_display())
...
Traceback (most recent call last):
File "<console>", line 2, in <module>
AttributeError: 'Hotels' object has no attribute 'get_hotel_Type_display'
I am following Django's get_FOO_display() tutorial and i still cannot get this work. I am not seeing anything wrong with my Hotels model. Could this be a bug in Django? Kindly assist
This really has eaten me up. I finally found the issue was a misplaced comma on my model field as shown below
class Hotels(models.Model):
HOTEL_TYPE = (
('hotel', "Hotel"),
('apartment', "Apartment"),
('villa', "Villa"),
hotel_Type = models.CharField(
max_length=20,
choices=HOTEL_TYPE,
default='hotel', null=True, blank=True
),# <--------------This comma was the source of my problems
#property
def hotel_type(self):
return self.get_hotel_Type_display()

Django - 'NoneType' object has no attribute 'year'

So every time I try to view someone's profile when they haven't entered a birth day I get this error 'NoneType' object has no attribute 'year'. I followed this post to add the birthday/age to the user profile so no reason to include my code since I got it from here https://stackoverflow.com/a/39761072/12229283.
I tried adding a default to the model but that doesn't seem to work how do I make it so if a user doesn't enter a birthday just skip it and ignore it? Thanks
You need to add an if / else to the return statement in your age method.
If there is no value for date_of_birth (i.e. it is set to None), you will get that error as you are calling dob.year, where dob = date_of_birth = None.
class Profile(models.Model):
date_of_birth = models.DateField()
def age(self):
import datetime
if self.date_of_birth:
dob = self.date_of_birth
tod = datetime.date.today()
my_age = (tod.year - dob.year) - int((tod.month, tod.day) < (dob.month, dob.day))
return my_age
else:
return ''
I had this issue in the admin>LogEntry after Django upgrade to 3.2.4. The issue was in using date_hierarchy.

django: got an unexpected keyword argument while accessing ForeignKey _id-Field in Manager

I have a model which looks like this:
class Mentorship (models.Model):
mentor = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='mentor_user_id')
mentee = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='mentee_user_id')
objects = MentorshipManager()
def clean(self):
print(self.mentor_id) # is set and printed to stdout
print(self.mentee_id) # is set and printed to stdout
if Mentorship.objects.is_mentor(self.mentor_id, self.mentee_id):
raise ValidationError(_('This user is already a mentor.'))
The manager has a function to check if someone is already a mentor of another user, which is called while clean()ing the instance:
def is_mentor_for_goal(self, mentor_id, mentee_id, personal_goal_id):
if self.exists(mentor_id=mentor_id, mentee_id=mentee_id):
return True
else:
return False
However I always get an exception while accessing the mentor_id or mentee_id attribute in exists:
Django Version: 1.6.1
Exception Type: TypeError
Exception Value: exists() got an unexpected keyword argument 'mentor_id'
Is there a reason why I cannot access the _id field within the manager? I just don't understand why the field is accessible in the (unsaved) instance, but not in the manager.
Oh... man... It should be called
if self.filter(mentor_id=mentor_id, mentee_id=mentee_id).exists()
Thanks for your comments
A few things mentor__id will only work in queryset methods, not things like print. You should also use pk instead of id, here is how it would work:
class Mentorship(models.Model):
mentor = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='mentor_user_id')
mentee = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='mentee_user_id')
objects = MentorshipManager()
def clean(self):
print(self.mentor.pk) # is set and printed to stdout
print(self.mentee.pk) # is set and printed to stdout
if Mentorship.objects.filter(mentor=self.mentor).exists():
raise ValidationError(_('This user is already a mentor.'))
def is_mentor_for_goal(self, mentor_id, mentee_id, personal_goal_id):
return self.exists(mentor__pk=mentor_id, mentee__pk=mentee_id)

How can I override the 'unique' error on a ModelForm field?

I'm trying to override the 'unique' error message for a Field in my ModelForm. I'm trying to follow the docs for Django 1.6, but I can't get it to work. Pretty simple stuff, I have:
models.py:
class EmailAddress(Model):
"""An email address."""
address = EmailField(unique=True)
def __unicode__(self):
return self.address
views.py:
class EmailAddressForm(ModelForm):
class Meta:
model = EmailAddress
fields = {'address'}
error_messages = {
'address': {
u'unique': _('That address has already been added.'),
}
}
If I enter a duplicate email, I get:
emailaddress_form.errors = {'address': [u'Email address with this Address already exists.']}.`
I've dug around in the source code, and as far as I can tell I'm passing the error_messages dict correctly into where it'll be picked up by the django.forms.models.fields_for_model function called by the Metaclass. Hopefully I'm missing something obvious. Any suggestions?
try This :-
Change address field to :-
address = models.EmailField(unique=True, error_messages={'unique':"That address has already been added."})
Create a method "clean_address" on EmailAddressForm class, hopefully This will resolved your issue.
def clean_address(self):
"""Prevent duplicate email addresses."""
if 'email' in self.changed_data:
if self.Meta.model.all().filter('address =', self.cleaned_data['address']).count():
raise forms.ValidationError('Email address with this Address already exists.: %s.' %
self.cleaned_data['address'])
return self.cleaned_data['address']

Django: invalid literal for int() with base 10

I am new to Django and trying to pass an author's name to a view and filter out quote objects based on the author's name. here are the codes:
models.py
class Author(models.Model):
author_name = models.CharField(max_length=50, default='unknown')
author_info = models.TextField(max_length=1000)
class Quote(models.Model):
author = models.ForeignKey(Author)
quote = models.TextField(max_length=500)
category= models.ForeignKey(Category)
pub_date = models.DateTimeField('date published')
urls.py:
url(r'^quotes/(?P<name>\w+)/$', 'quotes.views.quotesbyauthor'),
views.py
def quotesbyauthor(request, name):
aquotelist = Quote.objects.filter(author__exact = name)
return render_to_response(quotes_by_author.html, {'aquotelist': aquotelist })
However I get this error when I try to get http://127.0.0.1:8000/quotes/you/
('you' is a test author object, already created)
ValueError at /quotes/you/
invalid literal for int() with base 10: 'you'
Request Method: GET
Request URL: http://127.0.0.1:8000/quotes/you/
Django Version: 1.3.1
Exception Type: ValueError
Exception Value:
invalid literal for int() with base 10: 'you'
Exception Location: /home/qliq/djenv/lib/python2.6/site-packages/django/db/models/fields/__init__.py in get_prep_value, line 479
Python Executable: /home/qliq/djenv/bin/python
Python Version: 2.6.6
Python Path:
['/home/qliq/djenv/quoteapp',
'/home/qliq/djenv/lib/python2.6/site-packages/distribute-0.6.10-py2.6.egg',
'/home/qliq/djenv/lib/python2.6/site-packages/pip-0.7.2-py2.6.egg',
'/home/qliq/djenv/lib/python2.6',
'/home/qliq/djenv/lib/python2.6/plat-linux2',
'/home/qliq/djenv/lib/python2.6/lib-tk',
'/home/qliq/djenv/lib/python2.6/lib-old',
'/home/qliq/djenv/lib/python2.6/lib-dynload',
'/usr/lib/python2.6',
'/usr/lib/python2.6/plat-linux2',
'/usr/lib/python2.6/lib-tk',
'/home/qliq/djenv/lib/python2.6/site-packages']
I appreciate your help to resolve this.
You want to search on the author's author_name field, not the id.
Quote.objects.filter(author__author_name=name)
With your current search, author__exact, Django expects name to be the id of the author, so gives an error because you is not an integer.
aquotelist = Quote.objects.filter(author__author_name__exact = name)
Try changing the corresponding line to the above. The way you have it now, you are matching author to the given name, but author is probably considered by its ID here, definitely not by its author_name. The format is as follows:
Quote.objects.filter([model]__[field]__exact = [whatever])
I have faced and solved similar issue,
focus on attribute : author = models.ForeignKey(Author)
django expect that you pass an Instance of Author class to the author field. When you search django want to get a id (a integer number of this Instance):
so to get :
aquotelist = Quote.objects.filter(author__exact = name)
you have to start by :
create obj_Author = Author.objects.get(author_name = name)
aquotelist = Quote.objects.get(author__exact = obj_Author.id)
PS: ( I used get() in my example but if you expect to get multiple record, you can you use filter() and modify something. but main point is that because you work with a "ForeignKey field" so you need to give it a id like obj_Author.id. )
I think you should reset your migrate , you can see this link :
https://stackoverflow.com/a/54768217/9533909
i hope that help you.
I faced this issue and I figured out that I made records in the DB table that in your case is (Quote) before making the foreign key relationship with (Author) then after making the foreign key relationship Django doesn't know what to do to handle the old data in Quote model (to which records in Author should old records be assigned to)
--> The simplest solution is to:
delete your old Quote records: Quote.objects.all().delete inside your shell
recreate and reassign its new records correctly
makemigrations, migrate and runserver ... done
This will fix your problem permanently ::go to your directory
C:\python 37\Lib\site-packages\django\db\models\fields
and edit the file __init__.py and edit line 1807; replace
return int(value)
with
return int()
So just delete the argument value then your program will except all field references.