Invalid literal for int() with base 10: 'marlm' - python

I have to create a view which returns me the posts of a particular owner/author
This error in coming from view bellow. I know this is a simple thing that I am missing. Please help me on this: (marlm is the ID I created to test)
def view_by_owner(request):
user = request.user.username
posts_owner = Post.objects.filter(owner=user)
return render_to_response('view_post.html',{'view_owner':posts_owner})
Models:
from django.db import models
from django.db.models import permalink
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
datposted = models.DateTimeField('date posted')
category = models.ForeignKey('Category')
owner = models.ForeignKey('UserProfile')
def __str__(self):
return '%s' % self.title
class Category(models.Model):
title = models.CharField(max_length=100)
def __str__(self):
return self.title
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User)
# The additional attributes we wish to include.
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', null=True)
# Override the __unicode__() method to return out something
def __unicode__(self):
return self.user.username
class Logout(User):
force_logout_date = models.DateTimeField(null=True, blank=True)

The problem is that owner is a foreign key to User, not the value of the user name. To lookup by that, you will need to span that relationship, like so:
posts_owner = Post.objects.filter(owner__user__username=user)
Or, more simply, you could do this:
posts_owner = Post.objects.filter(owner__user=request.user)

Related

Value Error: Cannot query "post": Must be "UserProfile" instance

I am getting the Value Error: Cannot query "post": Must be "UserProfile" instance when I make a get request to call PostListView.as_view().
Here is my model.py :
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
username = models.CharField(max_length=30)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField()
password = models.CharField(max_length=100)
def __str__(self):
return self.user.username
class Post(models.Model):
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
text = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
views.py :
class PostListView(ListAPIView):
serializer_class = PostSerializer
permission_classes = [AllowAny]
def get_queryset(self):
"""Returns only the object related to current user"""
user = self.request.user
return Post.objects.filter(user=user)
Also, I want a Foreign key relationship exists between User and Post on Model-level, not on the Database level.
user is UserProfile instance but request.user is a User instance
change this line like that to refernece to userprofile
user = self.request.user.userprofile

How to show foreignkey attributes django admin fields?

This question is similar with others but it is a different one actually ! So, I have 3 models such as (I have deleted some unnecessary things for shorter code):
class Category(models.Model):
category_title = models.CharField(max_length=200)
category_content = models.TextField()
category_slug = models.CharField(max_length=200)
def __str__(self):
return self.category_title
class Classes(models.Model):
classes_title = models.CharField(max_length=200)
classes_content = models.TextField()
classes_category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT)
def __str__(self):
return self.classes_title
class Subjects(models.Model):
subject_title = models.CharField(max_length=200)
subject_content = models.TextField()
subject_class = models.ForeignKey(Classes, on_delete=models.SET_DEFAULT)
def __str__(self):
return self.subject_title
So let me give an example. I can have 2 categories and in those categories I can have "same named" classes. Lets think about maths is a class for both categories. When I want to add a new subject to maths I see 2 same named maths in admin page. So I want to know which one belongs to which category in admin page. So I can add my subject to right class.
class SubjectAdmin(admin.ModelAdmin):
fields = ('subject_title', 'subject_content', 'subject_class',)
So in this picture (Subjects = Konular) I am adding a new subject. I will have a foreign key to Class. However I have same name for classes that are coming from different categories. So in this dropdown how can I know which class belongs to which category ?
Try this...
class KonularAdmin(admin.ModelAdmin):
fields = ('subject_title', 'subject_content', 'subject_class', 'get_classes_category_title')
def get_classes_category_title(self, obj):
subject_object = Subjects.objects.get(id=obj.subject_class)
return str(subject_object.classes_category.category_title)
It returns the category title name
If I understood you correctly, This should work.
class Classes(models.Model):
classes_title = models.CharField(max_length=200)
classes_content = models.TextField()
classes_category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT)
def __str__(self):
return self.title
class Subjects(models.Model):
subject_title = models.CharField(max_length=200)
subject_content = models.TextField()
subject_class = models.ForeignKey(Classes, on_delete=models.SET_DEFAULT)
def __str__(self):
return f"{self.subject_title} - {str(self.subject_class)}"
You can use __str__() method to change the string representation of an object:
class Subjects(models.Model):
subject_title = models.CharField(max_length=200)
subject_content = models.TextField()
subject_class = models.ForeignKey(Classes, on_delete=models.SET_DEFAULT)
def __str__(self):
return f"{self.subject_title} - {self.subject_content} - {self.subject_class}"
# shorter version:
# return f"{self.subject_title[:10]} - {self.subject_content[:10]} - {self.subject_class[:10]}"
Check it with:
>>> print(Subjects.objects.first())

Django Queryset with annotate

I am writing one method in Django Manager model.
I want to write method that finds out number of all sold copies (books) per author.
I have two models and method written in Manager.
My problem is that method should also be chainable from any Author queryset, for example something like
Author.objects.filter(...).exlucde(...).total_copies_sold()
should also work.
Example:
author = Author.objects.create(...)
Book.objects.create(..., author=author, copies_sold=10)
Book.objects.create(..., author=author, copies_sold=20)
author_total_books = Author.objects.total_copies_sold().first()
>>> author_total_books.copies
30
Below my code. It works like in example above, but then I try something like:
author_books = Author.objects.filter(id=2).total_copies_sold()
I got
'QuerySet' object has no attribute 'annotate'
class AuthorManager(models.Manager):
def total_copies_sold(self):
return self.get_queryset().annotate(copies=Sum('book__copies_sold')
class Author(models.Model):
first_name = models.CharField(max_length=120)
last_name = models.CharField(max_length=120)
objects = AuthorManager()
class Book(models.Model):
title = models.CharField(max_length=120)
copies_sold = models.PositiveIntegerField()
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
[Edited]
Thank you schillingt for reply. I added:
class AuthorQueryset(models.QuerySet):
def total_copies_sold(self):
return self.annotate(copies=Sum('books__copies_sold'))
I tried something like:
author_books = Author.objects.filter(id=2).total_copies_sold()
>>> author_books.copies
I got
'AuthorQueryset' object has no attribute 'copies'
What you are lookig for is :
from django.db import models
from django.db.models import Sum
from django.db.models.functions import Coalesce
class AuthorManager(models.Manager):
def get_queryset(self):
return AuthorQuerySet(self.model, using=self._db)
def annotate_with_copies_sold(self):
return self.get_queryset().annotate_with_copies_sold()
class AuthorQuerySet(models.QuerySet):
def annotate_with_copies_sold(self):
return self.annotate(copies_sold=Sum('books__copies_sold'))
class Author(models.Model):
objects = AuthorManager()
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
class Book(models.Model):
title = models.CharField(max_length=30)
copies_sold = models.PositiveIntegerField()
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
Now it is possible to chain queries e.g.:
author_total_books = Author.objects.total_copies_sold().first()
However you will no be able to use it on QuerySet object like:
author_books = Author.objects.filter(id=2).total_copies_sold()
That is because you are annotating Author object, not a QuerySet. To obtain that result you should execute:
Author.objects.annotate_with_copies_sold().get(id=2)
author.copies_sold
15
You need to use Manager.from_queryset to set your manager. Here are the docs.
class AuthorQueryset(models.QuerySet):
def total_copies_sold(self):
...
class Author(models.Model):
objects = models.Manager.from_queryset(AuthorQueryset)()
from django.db import models
from django.db.models import Sum
from django.db.models.functions import Coalesce
class AuthorManager(models.Manager):
def get_queryset(self):
return AuthorQuerySet(self.model, using=self._db)
def annotate_with_copies_sold(self):
return self.get_queryset().annotate_with_copies_sold()
class AuthorQuerySet(models.QuerySet):
def annotate_with_copies_sold(self):
# Write your solution here
return self.annotate(copies_sold=Coalesce(Sum('books__copies_sold'), 0))
class Author(models.Model):
# Make sure this manager is available.
objects = AuthorManager()
# objects = models.Manager.from_queryset(AuthorQuerySet)()
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
class Book(models.Model):
title = models.CharField(max_length=30)
copies_sold = models.PositiveIntegerField()
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
enter code here
class AuthorManager(models.Manager):
def get_queryset(self):
return AuthorQuerySet(self.model, using=self._db)
def annotate_with_copies_sold(self):
return self.get_queryset().annotate_with_copies_sold()
class AuthorQuerySet(models.QuerySet):
def annotate_with_copies_sold(self):
return self.annotate(copies_sold=Sum('Book_Author__copies_sold'))
class Author(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
objects = AuthorManager()
class Meta:
verbose_name_plural = "Author"
verbose_name = 'Author'
ordering = ('first_name','last_name')
class Book(models.Model):
title = models.CharField(max_length=250, unique=True)
copies_sold = models.PositiveIntegerField(default=0)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='Book_Author')
class Meta:
verbose_name_plural = "Book"
verbose_name = 'Book'
ordering = ('title','copies_sold')
from vehicles.models import Author, Book
try:
author = Author.objects.get(first_name='Mark', last_name='Twain')
except Author.DoesNotExist:
author = Author.objects.create(first_name='Mark', last_name='Twain')
try:
book = Book.objects.get(author=author, title='Adventrure of Huckleberry Finn', copies_sold=7)
except Book.DoesNotExist:
book = Book.objects.create(author=author, title='Adventrure of Huckleberry Finn', copies_sold=7)
pass
try:
book = Book.objects.get(author=author, title='Adventrure of Tomm Saywer', copies_sold=4)
except Book.DoesNotExist:
book = Book.objects.create(author=author, title='Adventrure of Tomm Saywer', copies_sold=4)
pass
author = Author.objects.annotate_with_copies_sold().first()
print(author.copies_sold)
11
1.Create AuthorManager, AuthorQuerySet classes from Author and Books
2.Create Author, Book models
3.Prepare Test Data and use model manager to filter the queryset
Count books sold by authors using Django ORM
Wihtout writing custom manager you can use "AuthorQueryset" in Author Manager
Just a menthion AuthorQueryset.as_manager() in Author models, that's it.
Here are the Django Docs
from django.db import models
from django.db.models import Sum, Value
from django.db.models.functions import Coalesce
# Create your models here.
class AuthorQuerySet(models.QuerySet):
def annotate_with_copies_sold(self):
return self.annotate(copies_sold=Coalesce(Sum('books__copies_sold'),Value(0)))
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
objects = AuthorQuerySet.as_manager()
class Book(models.Model):
title = models.CharField(max_length=30)
copies_sold = models.PositiveIntegerField()
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books")

Django show only the values in the selected field

So in my models.py I have this:
class Profesie(models.Model):
titlu = models.CharField(max_length=100)
def __str__(self):
return self.titlu
class Domeniu(models.Model):
profesie = models.ForeignKey(Profesie)
titlu = models.CharField(max_length=100)
def __str__(self):
return self.titlu
class Anunt(models.Model):
titlu = models.CharField(max_length=150)
user = models.ForeignKey('auth.User', related_name='anunturi')
profesie = models.ForeignKey(Profesie)
domeniu = models.ForeignKey(Domeniu)
In the form when the user selects the field profesie, and then domeniu, for the domeniu field it should only display the values that are in the Profesie table. How can I accomplish that?

Django: Product attributes and custom fields form in product page

I just start to learn Django and I want to create a Product model with attributes, custom fields and custom field options. Custom field options exemple:
Line 1: [YOUR TEXT] | Custom field options: [FONT] [FONT SIZE] [...]
Line 2: [YOUR TEXT] | Custom field options: [FONT] [FONT SIZE] [...]
So I've created this models:
from django.db import models
from django.utils import timezone
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
sku = models.CharField(max_length=100)
slug = models.CharField(max_length=100)
price = models.DecimalField(max_digits=6, decimal_places=2)
active = models.BooleanField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
class ProductMeta(models.Model):
product = models.OneToOneField('Product')
title = models.CharField(max_length=100)
description = models.TextField(max_length=250)
class ProductImage(models.Model):
def upload_path(self, filename):
return 'static/uploads/images/%s%s' % (timezone.now().strftime('%Y/%m/%d/%Y%m%d_'), filename)
product = models.ForeignKey('Product')
name = models.CharField(max_length=100)
default = models.BooleanField()
image = models.ImageField(upload_to=upload_path)
def __unicode__(self):
return self.name
class ProductCharacteristic(models.Model):
product = models.ForeignKey('Product', related_name="characteristics")
name = models.CharField(max_length=100)
value = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductAttribute(models.Model):
category = models.ForeignKey('ProductAttributeCategory')
products = models.ManyToManyField('Product', related_name="attributes")
name = models.CharField(max_length=100)
ordering = ['-category']
def __unicode__(self):
return u'%s : %s' % (self.category, self.name)
class ProductAttributeCategory(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductAttributeValue(models.Model):
attribute = models.ForeignKey('ProductAttribute', related_name="values")
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductCustomField(models.Model):
product = models.ForeignKey('Product', related_name="custom_fields")
name = models.CharField(max_length=100)
description = models.TextField(max_length=250)
def __unicode__(self):
return self.name
class ProductCustomFieldOption(models.Model):
fields = models.ManyToManyField('ProductCustomField', related_name="options")
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductCustomFieldOptionValue(models.Model):
option = models.ForeignKey('ProductCustomFieldOption', related_name="values")
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
But now I don't know how to create the form in product details page in which the user can choose the product attributes (color, size...) and the product custom fields (and custom fields options). I've tried a lot of things but no results.
Can you help me please? :)
your question is unclear to me and your even more confusing. However see this if it helps
In your models.py
from django.db import models
from model_utils import Choices
colour_choices = ('Blue', 'Green')
class Product(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
reuturn self.name
class ProductAttributes(models.Model):
product = models.Foreignkey(Product, related_name='products')
colour = models.CharField(choices=Choices(*colour_choices))
In your forms.py
from django import forms
from .models import Product, ProductAttributes
class ProductForm(forms.ModelForm):
class Meta:
model = Product
class ProdductAttributesForm(forms.ModelForm):
class Meta:
model = ProductAttributes
Write your views.py, urls.py and template accordingly
this method will give you a text box to enter products and drop-down for choosing color.
Hope it helped!

Categories

Resources