I have this Page model:
class BlogPostPage(Page):
date_published= models.DateField('Published date', blank=True, null=True)
intro= models.CharField(max_length=250)
body = RichTextField(blank=True)
header_image = models.ForeignKey('wagtailimages.Image', blank=True, null=True,
on_delete=models.SET_NULL, related_name='+')
tags = ClusterTaggableManager(through='blog.BlogPageTag', blank=True)
categories = ParentalManyToManyField('blog.BlogCategory', blank=True)
def get_context(self, request):
context = super().get_context(request)
all_categories = []
for post in self.get_siblings(inclusive=True):
all_categories +=post.specific.categories.all()
all_categories = sorted(set(all_categories))
context['all_categories']= all_categories
return context
When the page is access I get a TypeError:
TypeError at /blog/xxx/
'<' not supported between instances of 'BlogCategory' and 'BlogCategory'
Inputs on why this is happening and how it can be avoided are requested.
You can define the key parameter for sorted, according to key functions.
But I am not sure, is + allowed in: all_categories +=post.specific.categories.all()?
Related
Please I'm trying to implement a SIMPLE messaging function (NOT A REAL TIME CHAT)
But I keep getting this error message I understand what it says or mean but I'm not sure why I am unable to establish this relationship
Please I need help to alternative if I can't do things this way
This is my profile(Engineer) models
class Engineer(AbstractUser):
username = models.CharField(max_length=200, null=True)
email = models.EmailField(unique=True, null=True)
bio = models.TextField()
avatar = models.ImageField(default="profile.png")
country = models.CharField(max_length=200)
years_of_experience = models.PositiveIntegerField(null=True, blank=True)
tech_stack = models.CharField(null=True, blank=True, max_length=300)
inbox = models.ForeignKey(Inbox, null=True, on_delete=models.CASCADE)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["username"]
def __str__(self):
return self.username
and this is my Inbox models
class Inbox(models.Model):
sender = models.ForeignKey(Engineer, null=True, on_delete=models.CASCADE, related_name='mail_sender')
receiver = models.ForeignKey(Engineer, null=True, on_delete=models.CASCADE, related_name="mail_receiver")
message = models.CharField(max_length=500)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["-created"]
def __str__(self):
return self.sender.username
Just make the Engineer import as follows
sender = models.ForeignKey('Engineer', null=True, on_delete=models.CASCADE, related_name='mail_sender')
receiver = models.ForeignKey('Engineer', null=True, on_delete=models.CASCADE, related_name="mail_receiver")
I have this models and the view for user profile.
class Room(models.Model):
admin = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True)
group_photo = models.ImageField(null=True, upload_to = 'images/', default='avatar.svg')
name = models.CharField(unique=True, max_length=100)
description = models.TextField(null=True, blank=True)
members = models.ManyToManyField(User, related_name='members', blank=True)
created = models.DateTimeField(auto_now_add=True)
views.py
#login_required(login_url= 'login')
def userprofile(request, pk):
user = User.objects.get(username=pk)
#groups = user.room_set.all()
groups = Room.objects.filter(admin=user)
all_groups = Room.objects.filter(members=user)
return render(request, 'base/profile.html', {'user':user, 'groups':groups, 'all_groups':all_groups})
Please explain how _set.all method filter method are doing the same job.
I don't understand where the room is coming from (there is only (Room) model.
explain the mechanism of user.room_set.all line respect to filter;
I am working on a post request in which the user chooses from a list of tags and makes combinations of tags. The combination of tags should then be posted. Nothing should get changed in the Tag table.
These are the models:
models.py
class Tag(models.Model):
name = models.CharField(max_length=256)
language = models.CharField(max_length=256)
objects = models.Manager()
def __str__(self):
"""Return a human readable representation of the model instance."""
return self.name or ''
#property
def tags(self):
tags = self.tagging.values('tag')
return tags.values('tag_id', 'tag__name', 'tag__language')
class Combination(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, null=True)
resource = models.ForeignKey(Resource, on_delete=models.CASCADE, null=True)
tag_id = models.ManyToManyField(Tag, null=True)
created = models.DateTimeField(editable=False)
score = models.PositiveIntegerField(default=0)
objects = models.Manager()
def __str__(self):
return str(self.tag_id) or ''
This is the serializer for Combination.
serializers.py
class CombinationSerializer(serializers.ModelSerializer):
tag_id = TagWithIdSerializer(many=True, required=False, write_only=False)
resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(),
required=True,
source='resource',
write_only=False)
gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(),
required=False,
source='gameround',
write_only=False)
user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(),
required=False,
source='user',
write_only=False)
class Meta:
model = Combination
depth = 1
fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag_id', 'created', 'score')
def create(self, validated_data):
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
score = 0
tag_data = validated_data.pop('tag_id', None)
combination = Combination(
user=user,
gameround=validated_data.get("gameround"),
resource=validated_data.get("resource"),
created=datetime.now(),
score=score
)
combination.save()
for tag_object in tag_data[0]:
combination.tag_id.add(tag_object)
return combination
def to_representation(self, instance):
rep = super().to_representation(instance)
rep['tag_id'] = TagWithIdSerializer(instance.tag_id.all(), many=True).data
return rep
I have tried posting the following JSON object to the database:
{
"gameround_id": 2015685170,
"resource_id": 327888,
"tag_id": [{"id": 2014077506, "name": "corwn","language": "en"}]
}
I am getting a ValueError: Field 'id' expected a number but got 'name'.
How can I fix this issue?
you need to provide tag id for each tag not all tag data,
Try like this
{
"gameround_id": 2015685170,
"resource_id": 327888,
"tag_id": [2014077506,2014077507]
}
Im Try to Catch any data from database with table name is 'UserUsulan'.
I have two field, 'Ketua' and 'Anggota'.
In Ketua Field is ForeignKey from User, and Anggota is ManyToMany Field with relationship from User.
I want to render the data.
if in Ketua Field equal current.user render the data.
and also if current.user in Anggota field i want it render too.
So,
If the current.user is not able in Ketua Field, but able in Anggota Field. Render the Data
If the current.user is not able in Anggota Field, buat able in Ketua Field. Render the Data Too.
How To Solve this problem.
Im read with this documentation Spanning multi-valued relationships . But the Queryset is empty[].
models.py
tahun = models.IntegerField(_('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)
judul_penelitian = models.TextField(blank=True)
jenis_penelitian = models.CharField(max_length=16, blank=True, default="", choices=JENIS_PENELITIAN_CHOICE)
tmt_awal = models.DateField(null=True, blank=True)
tmt_akhir = models.DateField(null=True, blank=True)
bidang_penelitian = models.CharField(max_length=10, blank=True, default="", choices=BIDANG_PENELITIAN_CHOICE)
tujuan_sosial_ekonomi = models.TextField(blank=True)
sumber_dana = models.CharField(max_length=30, blank=True, default="", choices=SUMBER_DANA_CHOICE)
skema_penelitian = models.CharField(max_length=15, blank=True, default="", choices=SKEMA_PENELITIAN_CHOICE)
jumlah_dana_usulan = MoneyField(max_digits=14, decimal_places=2, default_currency='IDR')
target_luaran = models.CharField(max_length=23, blank=True, default="", choices=TARGET_LUARAN_CHOICE)
ketua = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='ketua_penelitian', on_delete=models.CASCADE, null=True, blank=True)
anggota = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='anggota_penelitian')
upload_file = models.FileField(upload_to='Penelitian/', null=True, blank=True)
status_usulan = models.CharField(max_length=8, blank=True, choices=STATUS_USULAN_CHOICE, default='MENUNGGU')
jumlah_dana_disetujui = MoneyField(max_digits=14, decimal_places=2, default_currency='IDR', null=True, blank=True)
keterangan_operator = models.TextField(null=True, blank=True)
com_reviewer_1 = models.TextField(null=True, blank=True)
com_reviewer_2 = models.TextField(null=True, blank=True)
views.py
def get_queryset(self):
queryset = super(UserUsulanPenelitianCreateAndListView, self).get_queryset()
queryset = queryset.filter(ketua=self.request.user,).filter(anggota=self.request.user,)
print(queryset)
return queryset
I Found The Answer, Using Q for the queryset
Import Q
from django.db.models import Q
Using Q in Queryset
def get_queryset(self):
queryset = super(UserUsulanPenelitianCreateAndListView, self).get_queryset()
queryset = queryset.filter(Q(ketua=self.request.user)|Q(anggota=self.request.user)).distinct()
print(queryset)
return queryset
I would like to make a Ingredientslist for recipies(model named articles) and therefore need to assign unique values to Ingredients out of a Many to Many Infredient list.
I know that there is no straight forward way to implement a two dimensional array in django but I hope someone here has had this issue and knows a workaround.
Here I have my models being part of this issue:
class Ingredient(models.Model):
name = models.CharField(max_length=200, null=False)
kcal = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(800)], blank=True, default=0)
carbs = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)], blank=True, default=0)
protein = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)], blank=True, default=0)
fat = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)], blank=True, default=0)
class Article(models.Model):
banner = models.ImageField(null=True, default='dashboard-BG.jpg')
headline = models.CharField(max_length=200, null=False, default='Unnamed')
subtitle = models.CharField(max_length=300, null=False, default='Unnamed')
article_body = models.CharField(max_length=4000, null=False, default='Lorem Ipsum')
date_created = models.DateTimeField(auto_now_add=True)
ingredientList = models.BooleanField(null=True, default=False)
ingredients = models.ManyToManyField(Ingredient, blank=True)
kcal = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(3000)], null=True, blank=True)
carbs = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(3000)], null=True, blank=True)
protein = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(3000)], null=True, blank=True)
fat = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(3000)], null=True, blank=True)
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
ingredients = self.ingredients
totalCalories = 0
totalCarbs = 0
totalProtein = 0
totalFat = 0
for i in ingredients:
totalCalories += i.kcal
totalCarbs += i.carbs
totalProtein += i.protein
totalFat += i.fat
if i == 0:
return
self.kcal = totalCalories
self.carbs = totalCarbs
self.protein = totalProtein
self.fat = totalFat
self.save()
def __str__(self):
return self.headline
The 'two dimensional array should be the ingredients model field. Many ingredients having a specific unique amount for this recipe.
Thx for all the answers in advance ;)
In Django, models are representations of fields in SQL datatables. You could look into the JSONField type. This Field will hold any form of JSON data, basically a python dictionary. You could have one key for the ingredient and one key for the amount. Hope this helps!