Cannot assign "'1'": "Offers.state must be a "States" instance - python

I have read several answers to this same question, but none have worked for me. Here's my model:
class States(models.Model):
name = models.CharField(max_length=20)
abrev = models.CharField(max_length=3)
def __str__(self):
return self.abrev
class Offers(models.Model):
*other fields*
state = models.ForeignKey(States on_delete=models.PROTECT)
so in views i am doing this:
if request.method == 'POST':
try:
**other fields**
state = States.objects.get(pk=request.POST['state'])
Offers.objects.create(**other fields**, state=state)
except Exception as e:
print ("error in form")
But am always getting the same Error
Cannot assign "'1'": "Offers.state must be a "States" instance.
And as you can see, i am passing an instance, not the id of the element. I use the id that comes from the form just to query the DB and find the instance with this: state = States.objects.get(pk=request.POST['state'])
The form works just fine, and I tried to do it with forms.py and if form.is_valid(), but got the exact same result.
am on:
django 3.2.3
python 3.9.2
EDIT**
It works in the django admin.

In Offers.objects.create(other fields, state=state)
Here other fields is dict type contains all values to the model.
In the dict add
other_fields["created_by"] = state
or
other_fields["created_by_id"] = state.id
Then create,
Offers.objects.create(**other_fields)

Related

'Category' object is not subscriptable Django

I am learning Django. I wrote a simple model and some views method in Django rest framework so that I can modify some particular attributes when needed to all the records that need that. Here is the model:
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=255)
isActive = models.BooleanField(default=True)
def __str__(self):
return self.name
Then, I created this view to modify the isActive session when I call it:
class CategoriesChangeActiveView(views.APIView):
def post(self, request, format=None):
try:
categories = request.data.get('categories')
for category in categories:
category = Category.objects.get(id=category['id'])
category.isActive = category['isActive']
category.save()
except Exception as e:
return Response({'error': 'Bad request'}, status=status.HTTP_400_BAD_REQUEST)
return Response({'success': 'Active changed'}, status=status.HTTP_200_OK)
Even when the format of my request is correct ( I debugged each line ) when it comes to the line category.isActive = category['isActive']it throws the error that'Category' object is not subscriptable`. I don't know why or how to fix it.
I saw in the official documentation, on older StackOverflow questions that this is doable, but I don't understand why I can't.
Can someone please suggest what I am doing wrong? Thank you
it's a simple mistake.
Simply change it as follows and it should be fixed:
categories = request.data.get('categories')
for category in categories:
category_obj = Category.objects.get(id=category['id'])
category_obj.isActive = category['isActive']
category_obj.save()
What you're doing is changing what the variable category is. You for loop and the unpacked variable is category, but then you get the model object and set the variable as category
So initially, the category variable is in fact a dictionary object, but you change it to be a django model object instance.
Specifically, the issue is here:
category = Category.objects.get(id=category['id'])
category.isActive = category['isActive']
You set category to be an instance of the Category model (which in this case corresponds to a db record, but that bit is a little irrelevant).
Accessing attributes on a class instance is not done by the square bracket notation, but rather dot notation.
So instead of category['isActive'] use category.isActive
If category was a dictionary, eg.
category = {
"name": "cat",
"isActive": True,
}
Then you would use the square bracket notation as category["isActive"] to get that value.
As it is, it's not a dict, so python thinks you are trying to subscript the instance somehow, which will not work.

KeyError at /shops/profile/mannu

Hello django developers !. I hope you all are fine.. :)
Well here i want to get the shop_owner from shop detail view to the get context data function so i can count the total products of that particular shop..
models.py
class ShopProfile(models.Model):
shop_owner = models.OneToOneField(User, related_name='shop_profile', on_delete=models.CASCADE)
shop_address = models.CharField(_("shop address"), max_length=255)
views.py
class ShopProfileDetailView(DetailView):
model = ShopProfile
template_name='shops/shop_profile.html'
def get_context_data(self,*args, **kwargs):
context = super(ShopProfileDetailView, self).get_context_data(*args, **kwargs)
user = context['shop_owner'] #getting error here
context["products_count"] = Product.objects.filter(product_owner=user).count()
return context
If the KeyError is raised from a failed dictionary key lookup in your own code, you can use . get() to return either the value found at the specified key or a default value.
Well I fixed it, By printing the context variable above the error line, in my case
print('context data',context)
user = context['shop_owner'] #getting error here
It will return some fields in the terminal then You can simply get any data from that context. :)

Message Object has no attribute 'fields' when updating model field across apps

I have two apps menu and table. In app table, I have this model:
class Table(models.Model):
available = models.BooleanField(verbose_name="Availability", default=True)
def set_availability(self, avail=False):
self.fields['available'] = avail
self.save()
def __str__(self):
return "Table " + str(self.id_num)
In one of the views of app menu, I have the following call:
from table.models import Table
def menu_category_view(request, table_pk):
table = Table.objects.get(pk=table_pk)
if table.available:
table.set_availability(False)
...
return render(request,
...)
When my template calls this view, I receive this error message 'Table' object has no attribute 'fields'. Here, I am trying to update the value of field available of the instance being called (from True to False). And I got this implementation suggested from a book. Is this the right way to update model instance field value? Thanks.
Just set the attribute.
def set_availability(self, avail=False):
self.available = avail
self.save()
Though, it's questionable whether or not set_<field> methods like this are particularly useful. You could work with the object almost as easily:
if table.available:
table.available = False
table.save()

Django REST API query on related field

I have 3 models, Run, RunParameter, RunValue:
class Run(models.Model):
start_time = models.DateTimeField(db_index=True)
end_time = models.DateTimeField()
class RunParameter(models.Model):
parameter = models.ForeignKey(Parameter, on_delete=models.CASCADE)
class RunValue(models.Model):
run = models.ForeignKey(Run, on_delete=models.CASCADE)
run_parameter = models.ForeignKey(RunParameter, on_delete=models.CASCADE)
value = models.FloatField(default=0)
class Meta:
unique_together=(('run','run_parameter'),)
A Run can have a RunValue, which is a float value with the value's name coming from RunParameter (which is basically a table containing names), for example:
A RunValue could be AverageTime, or MaximumTemperature
A Run could then have RunValue = RunParameter:AverageTime with value X.
Another Run instance could have RunValue = RunParameter:MaximumTemperature with value Y, etc.
I created an endpoint to query my API, but I only have the RunParameter ID (because of the way you can select which parameter you want to graph), not the RunValue ID directly. I basically show a list of all RunParameter and a list of all Run instances, because if I showed all instances of RunValue the list would be too long and confusing, as instead of seeing "Maximum Temperature" you would see:
"Maximum Temperature for Run X"
"Maximum Temperature for Run Y"
"Maximum Temperature for Run Z", etc. (repeat 50+ times).
My API view looks like this:
class RunValuesDetailAPIView(RetrieveAPIView):
queryset = RunValue.objects.all()
serializer_class = RunValuesDetailSerializer
permission_classes = [IsOwnerOrReadOnly]]
And the serializer for that looks like this:
class RunValuesDetailSerializer(ModelSerializer):
run = SerializerMethodField()
class Meta:
model = RunValue
fields = [
'id',
'run',
'run_parameter',
'value'
]
def get_run(self, obj):
return str(obj.run)
And the URL just in case it's relevant:
url(r'^run-values/(?P<pk>\d+)/$', RunValuesDetailAPIView.as_view(), name='values_list_detail'),
Since I'm new to REST API, so far I've only dealt with having the ID of the model API view I am querying directly, but never an ID of a related field. I'm not sure where to modify my queryset to pass it an ID to get the appropriate model instance from a related field.
At the point I make the API query, I have the Run instance ID and the RunParameter ID. I would need the queryset to be:
run_value = RunValue.objects.get(run=run_id, run_parameter_id=param_id)
While so far I've only ever had to do something like:
run_value = RunValue.objects.get(id=value_id) # I don't have this ID
If I understand correctly, you're trying to get an instance of RunValue with only the Run id and the RunParameter id, i.e. query based on related fields.
The queryset can be achieved with the following:
run_value = RunValue.objects.get(
run__id=run_id,
run_parameter__id=run_parameter_id
)
Providing that a RunValue instance only ever has 1 related Run and RunParameter, this will return the instance of RunValue you're after.
Let me know if that's not what you mean.
The double underscore allows you to access those related instance fields in your query.
Well its pretty simple, all you have to do is override the get_object method, for example(copy pasted from documentation):
# view
from django.shortcuts import get_object_or_404
class RunValuesDetailAPIView(RetrieveAPIView):
queryset = RunValue.objects.all()
serializer_class = RunValuesDetailSerializer
permission_classes = [IsOwnerOrReadOnly]]
lookup_fields = ["run_id", "run_parameter_id"]
def get_object(self):
queryset = self.get_queryset() # Get the base queryset
queryset = self.filter_queryset(queryset) # Apply any filter backends
filter = {}
for field in self.lookup_fields:
if self.kwargs[field]: # Ignore empty fields.
filter[field] = self.kwargs[field]
obj = get_object_or_404(queryset, **filter) # Lookup the object
self.check_object_permissions(self.request, obj)
return obj
# url
url(r'^run-values/(?P<run_id>\d+)/(?P<run_parameter_id>\d+)/$', RunValuesDetailAPIView.as_view(), name='values_list_detail'),
But one big thing you need to be careful, is not to have duplicate entries with same run_id and run_parameter_id, then it will throw errors. To avoid it, either use unique_together=['run', 'run_parameter'] or you can use queryset.filter(**filter).first() instead of get_object_or_404 in the view. But second option will produce wrong results when duplicate entries are created.

Get Foreign Key parent of object - Django

Suppose I got two models like this:
class Article(models.Model):
article_title = models.CharField(max_length=100)
class EventRecord(models.Model):
article = models.ForeignKey(Article)
In a view, I select a certain EventRecord and want to show the Title of the Article it is related to as well. The following does not work:
def classify(request, pk):
event = get_object_or_404(EventRecord, pk=pk)
article_id = event.article
article = get_object_or_404(Article, pk=article_id)
How do I make this work?
Any help is really appreciated!
Django automatically handles this for you. For example:
>>> record = EventRecord.objects.get(...)
>>> isinstance(record.article, Article)
True
>>> record.article.article_title
u'title here'
This is one of the magical things Django does (nothing is magic but anyway...). Please keep in mind that in order for this work Django will usually execute some extra database queries. To eliminate them, you can use select_related method. Below is a snippet which eliminates extra queries and does what you want:
def classify(request, pk):
record = EventRecord.objects.filter(pk=pk).select_related()
# the above returns queryset hence you have to extract the record manually
if not len(record):
raise Http404()
else:
record = record[0]
# now use record as usual and no extra queries will be executed
title = record.article.article_title
...
event.article returns the actual Article object, not the primary key, so you don't need to do another database query.
def classify(request, pk):
event = get_object_or_404(EventRecord, pk=pk)
if not event.article:
raise Http404
print event.article.article_title

Categories