Taggit gets wrong tags - django-taggit

I have a Work model with Category Foreign Key. I am doing -->
drawingTags = Tag.objects.filter(Q(work__category__slug_en = 'drawing') |
Q(work__category__slug_en = 'illustration') |
Q(work__category__slug_en = 'sketch') |
Q(work__category__slug_en = 'storyboard'))
I get also the tags that do not belong to drawings ? Am i doing smt wrong ?
-- EDIT --
I did a little test. I have two applications named blog and web.
In blog i have 'entry' model and in web i have 'work' model. Both of those models have TaggableManager fields named tags...
When i want to take the tags of works categorized under drawing and do -->
drawingTags = Tag.objects.filter( work__in = drawings ).distinct()
If there is a drawing with id 1 and if entry model has an entry with id 1. Than i get both item's tags. I think there is a problem here but i do not know how to solve the puzzle?

Solution :
from django.contrib.contenttypes.models import ContentType
contentType = ContentType.objects.get_for_model(Work)
drawingTags =Tag.objects.filter(taggit_taggeditem_items__content_type=contentType,
work__in = drawings ).distinct()

Related

How to prevent duplicates when using ModelChoiceFilter in Django Filter and Wagtail

I am trying to use filters with a Wagtail Page model and a Orderable model. But I get duplicates in my filter now. How can I solve something like this?
My code:
class FieldPosition(Orderable):
page = ParentalKey('PlayerDetailPage', on_delete=models.CASCADE, related_name='field_position_relationship')
field_position = models.CharField(max_length=3, choices=FIELD_POSITION_CHOICES, null=True)
panels = [
FieldPanel('field_position')
]
def __str__(self):
return self.get_field_position_display()
class PlayerDetailPage(Page):
content_panels = Page.content_panels + [
InlinePanel('field_position_relationship', label="Field position", max_num=3),
]
class PlayerDetailPageFilter(FilterSet):
field_position_relationship = filters.ModelChoiceFilter(queryset=FieldPosition.objects.all())
class Meta:
model = PlayerDetailPage
fields = []
So what I am trying to do is create a filter which uses the entries from FIELD_POSITION_CHOICES to filter out any page that has this position declared in the inline panel in Wagtail.
As you can see in the picture down below, the filters are coming through and the page is being rendered. (These are 2 pages with a list of 3 field positions).
So Page 1 and Page 2 both have a "Left Winger" entry, so this is double in the dropdown. The filtering works perfectly fine.
What can I do to prevent this?
The solution should be something like this (Credits to Harris for this):
I basically have one FieldPosition object per page-field position, so it's listing all of the objects correctly. I suspect I should not use the model chooser there, but a list of the hard coded values in FIELD_POSITION_CHOICES and then a filter to execute a query that looks something like PlayerDetailPage.objects.filter(field_position_relationship__field_position=str_field_position_choice). But what is the Django Filter way of doing this?
Raf
In my limited simplistic view it looks like
class PlayerDetailPageFilter(FilterSet):
field_position_relationship = filters.ModelChoiceFilter(queryset=FieldPosition.objects.all())
is going to return all the objects from FieldPosition and if you have 2 entries for 'left wing' in here (one for page 1 and one for page 2) then it would make sense that this is duplicating in your list. So have you tried to filter this list queryset with a .distinct? Perhaps something like
class PlayerDetailPageFilter(FilterSet):
field_position_relationship = filters.ModelChoiceFilter(queryset=FieldPosition.objects.values('field_position').distinct())
I found the solution after some trial and error:
The filter:
class PlayerDetailPageFilter(FilterSet):
field_position_relationship__field_position = filters.ChoiceFilter(choices=FIELD_POSITION_CHOICES)
class Meta:
model = PlayerDetailPage
fields = []
And then the view just like this:
context['filter_page'] = PlayerDetailPageFilter(request.GET, queryset=PlayerDetailPage.objects.all()
By accessing the field_position through the related name of the ParentalKey field_position_relationship with __.
Then using the Django Filter ChoiceFilter I get all the hard-coded entries now from the choice list and compare them against the entries inside the PlayerDetailPage query set.
In the template I can get the list using the Django Filter method and then just looping through the query set:
<form action="" method="get">
{{ filter_page.form.as_p }}
<input type="submit" />
</form>
{% for obj in filter_page.qs %}
{{ obj }} >
{% endfor %}

Django - Setting a value of Model inside template page

I have a simple Django App having database interactions. I need to make the functionality of Video Visiting counter. So that I need to update- increment the counter each time when user visit the video.
I have a video object on template page(video-details.html).
This is how I access the video_file_name.
<h1 id="video1">{{video_obj.video_file_name}}</h1>
I have video model as:
class Video_Mapping(models.Model):
video_file_name = models.CharField(max_length=100)
video_description = models.CharField(max_length=2000, default='Video Description')
created_at = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
video_category_id = models.IntegerField(default=1)
video_seen_count = models.IntegerField(default=0)
I want to update the video_seen_count model value on template page.
More info: As I can do similar thing in View like following.
video = Video_Mapping.objects.get(pk=video_id);
video.video_description = description; video.save();
Please suggest me the best way to do it in the video-detail.html template page.
The simplest thing which I have done here is as per #birophilo'suggestion.
I was actually finding the way to increment the video_seen_count value from template(html page).
But after doing more research and try as suggested in comment, I decided to make this increment operation before the template renders(So in the view).
So it worked like:
video.video_screen_count += 1
video.save();
Thanks.

Allowing a user to schedule an event and have it linked to their account information for use in a django template

I've looked into the answers posted to similar questions but I couldn't get anything to work for my situation, so I will post my question. The way I have it, I always get the result "None" when I try to get the first name of the user who created an event... So I have multiple classes of users and I want to allow one type of user to be able to schedule events, with the template showing the user who created the event along with the various other fields that are in the class relating to the event. So for example:
#models.py
class BaseProfile(models.Model):
user = models.ForeignKey(User, unique=True)
first_name = models.CharField(max_length=20, verbose_name=_('First Name'))
last_name = models.CharField(max_length=20, verbose_name=_('Last Name'))
...
#More common fields
#Used for when a new broadcaster registers; fields specific to broadcasters
classBroadcasterProfile(models.Model):
user_type = models.CharField(max_length=20, default="broadcaster")
...
#Other fields specific to broadcasters
#Used when a broadcaster creates a profile for themselves after they have registered
class BroadcasterAccountProfile(BroadcasterProfile):
...
#A broadcaster wants to schedule an event
class UpcomingEvents(models.Model):
title = models.CharField(max_length=50, verbose_name=_('Title'))
description = models.TextField(max_length=100, verbose_name=_('Event Description'))
instructor = models.ForeignKey(BroadcasterAccountProfile, null=True, blank=True, related_name='instructor')
event_date = models.DateField(auto_now=False, auto_now_add=False, verbose_name=_('Date of Event'))
...
#Additional info to be included with the scheduling of event
So after a broadcaster has registered, created a profile, and scheduled an event (which all works successfully), the view I am trying to use for displaying the upcoming scheduled events is as follows:
#views.py
def upcoming_event_list(request):
today = datetime.date.today()
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
todays_events = UpcomingEvents.objects.filter(event_date=today)
tomorrows_events = UpcomingEvents.objects.filter(event_date=tomorrow)
return render_to_response('events/preview.html', {'today': today, 'tomorrow': tomorrow,
...
I can have my template display anything related to the upcoming events except for anything related to the broadcaster who created the event. I have tried adding values to my views:
def upcoming_event_list(request):
...
values = UpcomingEvents.objects.values('instructor__first_name', 'instructor__last_name', 'instructor__avatar')
#template.html
{% for v in values %}
Broadcaster Name:{{ v.instructor__first_name }}
{% endfor %}
This would show "Broadcaster Name: None". Am I completely heading in the wrong direction, or what can I do to try to make this work? Sorry if this was confusing. I tried to make it as clear as possible, but seeing as how I am confused myself, I don't know how successful I was in trying to describe my problem. Thanks for any help. Please let me know if I need to clarify anything.
Have you tried {{ v.instructor.first_name }} in your template?
Note the .(full-stop/dot/period/whatever-you-call-it) instead of a __(double underscore).

AppEngine Datastore get entities that have ALL items in list property

I want to implement some kind of tagging functionality to my app. I want to do something like...
class Item(db.Model):
name = db.StringProperty()
tags = db.ListProperty(str)
Suppose I get a search that have 2 or more tags. Eg. "restaurant" and "mexican".
Now, I want to get Items that have ALL, in this case 2, given tags.
How do I do that? Or is there a better way to implement what I want?
I believe you want tags to be stored as 'db.ListProperty(db.Category)' and then query them with something like:
return db.Query(Item)\
.filter('tags = ', expected_tag1)\
.filter('tags = ', expected_tag2)\
.order('name')\
.fetch(256)
(Unfortunately I can't find any good documentation for the db.Category type. So I cannot definitively say this is the right way to go.) Also note, that in order to create a db.Category you need to use:
new_item.tags.append(db.Category(unicode(new_tag_text)))
use db.ListProperty(db.Key) instead,which stores a list of entity's keys.
models:
class Profile(db.Model):
data_list=db.ListProperty(db.Key)
class Data(db.Model):
name=db.StringProperty()
views:
prof=Profile()
data=Data.gql("")#The Data entities you want to fetch
for data in data:
prof.data_list.append(data)
/// Here data_list stores the keys of Data entity
Data.get(prof.data_list) will get all the Data entities whose key are in the data_list attribute

How to modify attributes of forms generated by webapp (Google App Engine)?

Here are model and form classes from example:
http://code.google.com/appengine/articles/djangoforms.html
class Item(db.Model):
name = db.StringProperty()
quantity = db.IntegerProperty(default=1)
target_price = db.FloatProperty()
priority = db.StringProperty(default='Medium',choices=[
'High', 'Medium', 'Low'])
entry_time = db.DateTimeProperty(auto_now_add=True)
added_by = db.UserProperty()
class ItemForm(djangoforms.ModelForm):
class Meta:
model = Item
exclude = ['added_by']
It will be rendered as table rows.
Can I change how they will be rendered (change width or make it to be list instead of table row or anything…)?
Take a look at the Django forms docs, here. The docs are for 1.0, but most of it applies to the 0.91 version bundled with App Engine, too.
The short answer to your question: form.as_p will generate an HTML representation of the form as a series of <p> tags, while form.as_ul will generate a series of <ul> tags and form.as_table will generate a table.

Resources