Field Error When Using choices in a Django Model field - python

After adding one of the model fields to select an option from a list, I get a field error. What could possibly be the cause and the solution to this
ERROR:
File "/home/chrisdev/code/work/cw-full/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1481, in names_to_path
raise FieldError("Cannot resolve keyword '%s' into field. "
django.core.exceptions.FieldError: Cannot resolve keyword 'status' into field. Choices are: description, id, image, name, slug
MODEL:
from django.db import models
from django.contrib.auth.models import User
# News Model
class News(models.Model):
DRAFT = 'DRT'
PUBLISHED = 'PUB'
article_publication_choices = [
(DRAFT, 'Draft'),
(PUBLISHED, 'Published'),
]
title = models.CharField('News Title', max_length=200, unique=True, help_text='News Heading')
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.SET_NULL, related_name='news', null=True)
updated_on = models.DateTimeField(auto_now= True)
news_summary = models.CharField('News Summary', max_length=200)
content = models.TextField('News Content')
created_on = models.DateTimeField(auto_now_add=True)
article_publication = models.CharField(max_length=2,
choices=article_publication_choices,
default=PUBLISHED,
)
class Meta:
verbose_name = 'News Updates'
verbose_name_plural = verbose_name
ordering = ['-created_on']
def __str__(self):
return self.title

I found the solution to this, by adding related_name='+', at the field that uses a relationship from other models

Related

django.db.utils.IntegrityError: FOREIGN KEY constraint failed - Django

First, I know there are a lot of answers regarding this error, but I can't understand why this is erroring out in my case. I am learning Django and any help would be highly appreciated.
I have a Ticket model with ForeignKey reference to Category, Type & GHDUser as below
models.py
`
# from accounts/models.py
class GHDUser(AbstractBaseUser, PermissionsMixin):
emp_id = models.IntegerField(primary_key=True)
email = models.EmailField(_('email address'),unique=True)
username = models.CharField(max_length=150, unique=True)
# from ticket/models.py
class Category(models.Model):
name = models.CharField(max_length=100)
class Meta:
verbose_name = 'Category'
verbose_name_plural = 'Categories'
def __str__(self):
return self.name
class Type(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
class Meta:
verbose_name = 'Type'
verbose_name_plural = 'Types'
def __str__(self):
return self.name
class Ticket(models.Model):
status_options = (
('open', 'Open'),
('pending', 'Pending'),
('closed', 'Closed')
)
priority_options = (
('high','High'),
('medium','Medium'),
('low','Low')
)
ticket_no = models.CharField(max_length=10, blank=True)
title = models.CharField(max_length=100)
description = models.TextField(max_length=1000)
category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1)
type = models.ForeignKey(Type, on_delete=models.PROTECT, default=1)
file = models.FileField(upload_to=user_directory_path, blank=True, default='files/Default_Avatar.png')
raised_by_user = models.ForeignKey(GHDUser, on_delete=models.CASCADE, related_name='raised_ticket')
`
Now, I am able to create an instance for Ticket model from Admin Panel, but when I try to do the same via shell / using data from front end, I am getting the below error.
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
Can you please help me understand what I am doing wrong ?

Why is the URL not working after adding foreignkey field to model?

I'm creating a blog application and I added a category for its blog posts. When adding a new category it can be can be done without any problem. But the problem is I can't find posts for a specific category ID and get an error like
Field 'id' expected a number but got 'health'
But before I updated field category charafield to forenkeyfied it worked without any problem.
Here is my code:
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = SummernoteTextField(blank=True, null=True)
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
image = models.ImageField(upload_to='images',null=True, blank=True)
category = models.ForeignKey('blog.category', on_delete=models.SET_NULL, null=True, blank=True)
class category(models.Model):
name = models.CharField(max_length=80)
def __str__(self):
return self.name
views.py
def CategoryView(request, cats):
category_posts = Post.objects.filter(category=cats.replace('-', ' '))
return render(request, 'categories.html', {'cats':cats.replace('-', ' '), 'category_posts':category_posts})
forms.py
class PostForm(forms.ModelForm):
category = forms.ModelChoiceField(queryset=category.objects.all().order_by('name'))
class Meta:
model = Post
fields = ('title', 'category','author', 'content', 'image','status')
You didn't share the full traceback but the error likely is caused by this line
Post.objects.filter(category=cats.replace('-', ' '))
You are filtering against the category foreign key using a string hence the error.
What you intended seems to be to filter against the category name:
Post.objects.filter(category__name=cats.replace('-', ' '))

Django API ManyToMany on existing databse not working

at the moment I try to get recipes from my API. I have a Database with two tables one is with recipes and their ids but without the ingredients, the other table contains the ingredients and also the recipe id. Now I cant find a way that the API "combines" those. Maybe its because I added in my ingredient model to the recipe id the related name, but I had to do this because otherwise, this error occurred:
ERRORS:
recipes.Ingredients.recipeid: (fields.E303) Reverse query name for 'Ingredients.recipeid' clashes with field name 'Recipe.ingredients'.
HINT: Rename field 'Recipe.ingredients', or add/change a related_name argument to the definition for field 'Ingredients.recipeid'.
Models
from django.db import models
class Ingredients(models.Model):
ingredientid = models.AutoField(db_column='IngredientID', primary_key=True, blank=True)
recipeid = models.ForeignKey('Recipe', models.DO_NOTHING, db_column='recipeid', blank=True, null=True, related_name='+')
amount = models.CharField(blank=True, null=True, max_length=100)
unit = models.CharField(blank=True, null=True, max_length=100)
unit2 = models.CharField(blank=True, null=True, max_length=100)
ingredient = models.CharField(db_column='Ingredient', blank=True, null=True, max_length=255)
class Meta:
managed = False
db_table = 'Ingredients'
class Recipe(models.Model):
recipeid = models.AutoField(db_column='RecipeID', primary_key=True, blank=True) # Field name made lowercase.
title = models.CharField(db_column='Title', blank=True, null=True, max_length=255) # Field name made lowercase.
preperation = models.TextField(db_column='Preperation', blank=True, null=True) # Field name made lowercase.
images = models.CharField(db_column='Images', blank=True, null=True, max_length=255) # Field name made lowercase.
#ingredients = models.ManyToManyField(Ingredients)
ingredients = models.ManyToManyField(Ingredients, related_name='recipes')
class Meta:
managed = True
db_table = 'Recipes'
When there is no issue it has to be in the serializer or in the view.
Serializer
class IngredientsSerializer(serializers.ModelSerializer):
# ingredients = serializers.CharField(source='ingredients__ingredients')
class Meta:
model = Ingredients
fields = ['ingredient','recipeid']
class FullRecipeSerializer(serializers.ModelSerializer):
ingredients = IngredientsSerializer(many=True)
class Meta:
model = Recipe
fields = ['title','ingredients']
View
class FullRecipesView(generics.ListCreateAPIView):
serializer_class = FullRecipeSerializer
permission_classes = [
permissions.AllowAny
]
queryset = Recipe.objects.all()
This is at the moment my output
But I want e.g. the recipe with id 0 and all the ingredients which have also recipe id 0.
I really hope that you can help me. Thank you so much!
Rename ingredients to some other name in FullRecipeSerializer. It conflicts with ingredients in Recipe model. This should solve your issue. For example
class FullRecipeSerializer(serializers.ModelSerializer):
ingredients_recipe = IngredientsSerializer(many=True, source= 'ingredientid')
class Meta:
model = Recipe
fields = ['title','ingredients_recipe']

Django Rest Serializer validate gives Invalid pk

I have this situation:
Model Handling
class Handling(models.Model):
STATUS = (
('Active', 'Active'),
('Archived', 'Archived'),
)
entdate = models.DateTimeField(auto_now_add=True, null=True)
extdate = models.DateTimeField(auto_now_add=True, null=True)
kpallet = models.ForeignKey(Pallet, related_name='kpallet', null=True, on_delete= models.PROTECT)
kitem = models.ForeignKey(Item,related_name='kitems', null=True, on_delete= models.PROTECT, limit_choices_to={'kstatus': 'Active'})
quantity = models.SmallIntegerField(null=True)
kstatus = models.CharField(max_length=20, null=True, choices=STATUS)
def __str__(self):
return str(self.kpallet)
Model Item:
class Item(models.Model):
STATUS = (
('Active', 'Active'),
('Disabled', 'Disabled'),
('Archived', 'Archived'),
)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=50, null=True)
description = models.CharField(max_length=200, null=True)
kdimension = models.ForeignKey(Dimension, null=True, on_delete= models.PROTECT)
kclient = models.ForeignKey(Client, null=True, on_delete= models.PROTECT)
kstatus = models.CharField(max_length=20, null=True, choices=STATUS)
def __str__(self):
return self.name
Serializer:
class HandlingSerializer(serializers.ModelSerializer):
class Meta:
model = Handling
fields = '__all__'
Api:
#api_view(['POST'])
#permission_classes((permissions.AllowAny,))
def handlingCreate(request):
serializer = HandlingSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
else:
print(serializer.errors);
return Response("Error Handling not created")
return Response("Handling Created")
I get this error and i don't understand how to move on:
{'kitem': [ErrorDetail(string='Invalid pk "958c2fd2-bbb6-42d6-8bfe-fbe035e9ceb5" - object does not exist.', code='does_not_exist')]}
I've checked the pk and the object exists so I don't understand where the issue could be.
Thanks for your help in advance.
Fixed thanks to Blackdoor for the input.
This is the correct serializer:
class HandlingSerializer(serializers.ModelSerializer):
kitem = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all(), pk_field=serializers.UUIDField(format='hex_verbose'))
class Meta:
model = Handling
fields = '__all__'
use pk_field=UUIDField for PrimaryKeyRelatedField
class HandlingSerializer(serializers.ModelSerializer):
kitem = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all(), pk_field=UUIDField(format='hex'))
class Meta:
model = Handling
fields = '__all__'

How do I return data from a related model in Django Tastypie?

How do I bring in the information from another model?
I have two models Article, and ArticleBody
Article containing the main info and ArticleBody containing a loop of body and image information
class Article(models.Model):
author = models.ForeignKey(User)
title = models.CharField(max_length=100)
excerpt = models.CharField(max_length=140, null=True, blank=True, help_text='A description no longer than 140 characters that explains what the article is about, important for SEO')
category = models.ManyToManyField(Category)
date_published = models.DateTimeField()
slug = models.SlugField(null=True)
status = models.CharField(choices=STATUS, max_length=2, default='DR')
tags = TagField(default='', null=True, blank=True, help_text='Just add a comma between the tags i.e. "My very important name, Hunting, Scope, Rifle"')
source_name = models.CharField(default='', blank=True, null=True, help_text='Outdoor Magazine', max_length=100)
source_url = models.URLField(verify_exists=False, max_length=200, null=True, blank=True, help_text='http://www.source.com/2011/01/long-name/')
class ArticleBody(ImageModel):
article = models.ForeignKey(Article)
body = models.TextField(verbose_name='', blank=True, null=True)
image = models.ImageField(storage=cloudfiles_storage, upload_to='articles', default='avatar-blank.jpg', verbose_name='', blank=True, null=True)
caption = models.CharField(max_length=80, null=True, blank=True)
In my api resources.py file I am trying to get the ArticleBody information into my NewsResource...
This is what I have so far.
class NewsBodyResource(ModelResource):
class Meta:
queryset = ArticleBody.objects.all()
resource_name = 'article_body'
class NewsResource(ModelResource):
class Meta:
queryset = Article.objects.filter(status='PU', date_published__lt=datetime.datetime.now).order_by('-date_published')
resource_name = 'news'
What is the correct TastyPIE way, of making changes so I can get a loop of ArticleBody into my NewsResource?
class NewsBodyResource(ModelResource):
class Meta:
queryset = ArticleBody.objects.all()
resource_name = 'article_body'
class NewsResource(ModelResource):
newsbodies = fields.ToManyField('yourapp.api.resources.NewsBodyResource', 'articlebody_set', full=True)
class Meta:
queryset = Article.objects.filter(status='PU', date_published__lt=datetime.datetime.now).order_by('-date_published')
resource_name = 'news'
The parameters to ToManyField represent the following respectively:
project-relative import path to the resource representing the set
the name of field if it's on the parent model or the related_name
attribute of the field if it's on the child model
whether or not to embed
the full data of each child into the feed (True) or just resource
links to each child (False)

Categories