Reputation: 57
My model : I am getting invalid literal for int() with base 10 in Django it is working in perfectly in the shell
class Category(models.Model):
cat_id = models.IntegerField(primary_key=True)
category_name = models.CharField(max_length=1000)
created_at = models.DateField(auto_now=True ,max_length=30)
def __str__(self):
return self.category_name
class Content(models.Model):
content_id = models.AutoField(primary_key=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
content = models.CharField(max_length=5000)
created_at = models.DateField(auto_now=True)
def __str__(self):
return self.content
** my view **
def create_blog(request):
if request.method == 'POST':
title = request.POST['title']
content = request.POST['content']
category = request.POST['category']
object_of_category = Category.objects.get(cat_id = (category))
save_post = Content(category = object_of_category, content =content)
save_post.save()
return redirect(create_blog,{'message':'Post created Successfully!'})
categories = Category.objects.all()
return render(request ,'admin/create_blog.html', {'categories' : categories})
Upvotes: 0
Views: 164
Reputation: 169
First off, you are attempting to get an id(type Integer) of value category(type String) in the following snippet:
object_of_category = Category.objects.get(cat_id = (category))
Also, avoid creating primary key fields unless absolutely necessary as Django does that for you automatically.
Furthermore, Try.. Except
blocks are extremely helpful in such situations as they generate StackTraces that show where your errors stem from.
Upvotes: 0
Reputation: 145
category = request.POST['category']
you should attention that what you have post it it should be int type
because in your Category model:
cat_id = models.IntegerField(primary_key=True)
is integer type
i think all of your code is ok but before
object_of_category = Category.objects.get(cat_id = (category))
check type of the category by:
type(category)
My suggesstion is that use django.form for preventing these complexities.
Upvotes: 1
Reputation: 931
You don't need to add models.AutoField() yourself, it is added by Django automatically, see here https://docs.djangoproject.com/en/3.0/topics/db/models/#automatic-primary-key-fields
you have to remove your custom ID's in both of the tables and change your get query
object_of_category = Category.objects.get(cat_id = (category))
object_of_category = Category.objects.get(id=category)
Upvotes: 1