I'm using this model to allow user to subscribe or unsubscribe to a specific game. But now I'm unsure of how to count the number of users subscribed to a specific game.
class Subscription(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
game = models.ForeignKey(Game, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return str(self.id)
views.py:
class TitlePostListView(ListView):
model = Post
context_object_name = 'posts'
template_name = 'posts/game.html'
def get_queryset(self):
title = get_object_or_404(Game, slug=self.kwargs.get('slug'))
return Post.objects.filter(game=title).order_by('-date_published')
def get_context_data(self, **kwargs):
context = super(TitlePostListView, self).get_context_data(**kwargs)
context['game'] = get_object_or_404(Game, slug=self.kwargs.get('slug'))
context['subscription_status'] = subscription_status(self.request.user, context['game'])
return context
You would do something along the lines of this:
game = Game.objects.get(name="Some Game") # Gets the game obj (replace "name" with the identifier you use)
subscriptions = Subscription.objects.filter(game=game) # Filters all the subscriptions associated with the game obj above
sub_count = subscriptions.count() # Uses QuerySet method .count() to get amount of subscription instances, and avoids a potentially costly DB hit
EDIT
To get the query into your context when using ListView, you can do something like this:
class TitlePostListView(ListView):
model = Post
context_object_name = 'posts'
template_name = 'posts/game.html'
def get_queryset(self):
game = get_object_or_404(Game, slug=self.kwargs.get('slug'))
return Post.objects.filter(game=game).order_by('-date_published')
def get_context_data(self, **kwargs):
game = get_object_or_404(Game, slug=self.kwargs.get('slug'))
context = super(TitlePostListView, self).get_context_data(**kwargs)
context['game'] = game
context['subscription_status'] = subscription_status(self.request.user, context['game'])
context['sub_count'] = Subscription.objects.filter(game=game).count()
return context
And then in your template, you can use {{ sub_count }} to see the subscription count for that specified game.
Related
I am trying to save a form with the current logged in user's username, but the error "Cannot assign "'Neshno_Games2'": "League.host" must be a "Manager" instance." occurs
Views.py
class CreateLeaguesView(generic.CreateView):
model = League
template_name = "leagues/create-league.html"
form_class = LeaguesCreationForm
success_url = "/leagues/leagues"
def get_context_data(self, **kwargs):
context = super().get_context_data( **kwargs)
context['leagues'] = League.objects.all()
return context
def form_valid(self, form):
manager = self.request.user.username
League.objects.create(
host = manager,
)
return super(CreateLeaguesView, self).form_valid(form)
Model.py
class League(models.Model):
name = models.CharField(max_length=30)
no_players = models.IntegerField(default=20)
start_date = models.DateField(blank=False, null=False)
end_date = models.DateField(blank=False, null=False)
prize = models.CharField(max_length=300)
host = models.ForeignKey(Manager, on_delete=models.CASCADE)
def __str__(self):
return self.name
forms.py
class LeaguesCreationForm(forms.ModelForm):
class Meta:
model = League
fields = (
"name",
"no_players",
"start_date",
"end_date",
"prize",
)
You can try like this:
class CreateLeaguesView(generic.CreateView):
model = League
def form_valid(self, form):
form.instance.host= self.request.user.manager # accessing one to one data
return super().form_valid(form)
More information can be found here in this documentation: https://docs.djangoproject.com/en/4.0/topics/db/examples/one_to_one/
i have a model which has a foreign key relation with two oder models one of them is 'level'.
the view knows in which level you are based on a session variable,
and then filter the lessons
this is the lesson model:
class Lesson(models.Model):
level = models.ForeignKey(Level,on_delete=models.CASCADE)
subject = models.ForeignKey(Subject,on_delete=models.CASCADE)
chapiter = models.CharField(max_length=200)
lesson = models.CharField(max_length=200)
skill = models.CharField(max_length=200)
vacations = models.IntegerField()
link = models.URLField(max_length=700,null=True,blank=True)
remarques = models.TextField(null=True,blank=True)
order = models.IntegerField()
created = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now=True)
state = models.BooleanField(default=False)
now this is my cbv to create a new lesson:
class GlobalLessonView(CreateView):
model = Lesson
form_class = GlobalLessonForm
success_url = reverse_lazy('globalform')
and this is the form:
class GlobalLessonForm(forms.ModelForm):
class Meta:
model = Lesson
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['subject'].queryset = Subject.objects.none() #change to .all() to see list of all subjects
if 'level' in self.data:
try:
level_id = int(self.data.get('level'))
self.fields['subject'].queryset = Subject.objects.extra(where=[db_name+'.scolarité_subject.id in( select subject_id from '+db_name+'.scolarité_levelsubject where level_id='+level_id+')'])
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['subject'].queryset = self.instance.level.subject_set
one of the main conditions is to filter level by a session variable
but the form does not accept request.session
so is there any way to change the levels that shows up at the form from the class based view,or there any way to pass request.session to form.py
Add this to GlobalLessonView:
def get_form_kwargs(self):
"""Pass request to form."""
kwargs = super().get_form_kwargs()
kwargs.update(request=self.request)
return kwargs
Then change the constructor definition in GlobalLessonForm to:
def __init__(self, request, *args, **kwargs):
Then you will be able to reference request.session in GlobalLessonForm.
I have two models, Car and Booking. A Car is a ForeignKey field in Booking model. If Car is booked, it's removed from Car list.
After car is booked the code changes to is_available_car = false. And then car is not showing in Car listview. but the
Problem i am facing is:
After i removed booking from admin, the car is not showing in list view. if the car booking is closed i want to make is_available_car = True. I can't seem to change it from false to true.
I added a filter query to make is_available_car = True. Problem is after car is returned and booking time finished, I have to manually change the value of is_available_car = True every time.
Help me out please that if car booking is finished or i delete the booking .the car available value changes to true !!
These are my models and views:
Models
class Booking(models.Model):
booking_name = models.CharField(max_length=240, null=False)
customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='book_customers' )
book_car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name='book_car')
rental_price = models.IntegerField(blank=False, null=False)
times_pick = models.TimeField(blank=True)
is_approved = models.BooleanField(default=False)
def __str__(self):
return self.booking_name
def get_absolute_url(self):
return reverse("buggy_app:detail",kwargs={'pk':self.pk})
class Car(models.Model):
reg_no = models.CharField(max_length=16, unique=True)
model_year = models.DateField()
car_name =models.CharField(max_length=40)
car_image = models.ImageField(upload_to='cars', blank = True)
is_available_car = models.BooleanField(default = False)
def __str__(self):
return self.car_name
def get_absolute_url(self):
return reverse("buggy_app:details",kwargs={'pk':self.pk})
Views
class BookingView(FormView):
template_name = 'buggy_app/booking.html'
form_class = BookingForm
models = Booking
def form_valid(self, form):
car_id = self.request.GET.get('car', '')
car = Car.objects.get(id=car_id)
car.is_available_car = False
car.save()
form.save()
return super(BookingView, self).form_valid(form)
success_url = reverse_lazy('index')
def get_context_data(self, **kwargs):
# kwargs['car'] is the car booking now!
try:
kwargs['car'] = Car.objects.get(id=self.request.GET.get('car', ''))
except (Car.DoesNotExist, ValueError):
kwargs['car'] = None
return super(BookingView, self).get_context_data(**kwargs)
class CarListView(ListView):
context_object_name = 'cars'
model = models.Car
def get_queryset(self):
qs = super(CarListView, self).get_queryset()
qs = qs.filter(is_available_car=True)
return qs
You can create a signal handler that listens to the pre_delete signal for the Booking model: see the documentation. So everytime a booking is deleted, your signal handler will be called and you'll be able to update the corresponding car.
e.g.
#receiver(pre_delete, sender=Booking):
def update_car(sender, **kwargs):
car = sender.book_car
car.is_available = True
car.save()
Then make sure you register your handler as described in the Django docs above.
Now I don't know what you mean by "when a booking is finished", but that sounds just like a method on the Booking model itself:
def finish(self):
self.expired = True # You'd have to define what it means for a booking to be finished
car = self.book_car
car.is_available = True
car.save()
I'm having trouble incrementing the vote_score attribute of my model every time it is voted on. This is my model:
# idea model
class Idea(models.Model):
User = ('accounts.User')
creator = models.ForeignKey(User, related_name='ideas', on_delete=models.PROTECT)
title = models.CharField(max_length=100, null=True, blank=True)
vote_score = models.BigIntegerField(default=0, null=True, blank=True)
votes = VotableManager()
#vote model
class Vote(models.Model):
user = models.ForeignKey(AUTH_USER_MODEL)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
create_at = models.DateTimeField(auto_now_add=True)
vote = models.NullBooleanField()
objects = VoteManager()
class Meta:
unique_together = ('user', 'content_type', 'object_id')
#classmethod
def votes_for(cls, model, instance=None):
ct = ContentType.objects.get_for_model(model)
kwargs = {
"content_type": ct
}
if instance is not None:
kwargs["object_id"] = instance.pk
return cls.objects.filter(**kwargs)
#manager
_VotableManager(models.Manager):
def __init__(self, through, model, instance, field_name='votes', extra_field='vote_score'):
self.through = through
self.model = model
self.instance = instance
self.field_name = field_name
self.extra_field = extra_field
self.name = model.title
#instance_required
def up(self, user, vote):
with transaction.atomic():
if self.through.objects.filter(user=user, content_object=self.instance).exists():
c_type = ContentType.objects.get_for_model(self.instance)
vote_obj = self.through.objects.get(user=user, object_id=self.instance.id, content_type=c_type)
vote_obj.vote = vote
vote_obj.save()
self.instance.save()
else:
self.through(user=user, content_object=self.instance, vote=vote).save()
if self.extra_field:
setattr(self.instance, self.extra_field, F(self.extra_field)+1)
self.instance.save()
My goal is to have it so when the idea is created the creator automatically counts as 1 vote toward it so that falls under this view:
# idea create view
class IdeaCreateView(LoginRequiredMixin, CreateView):
model = Idea
form_class = IdeaCreateForm
template_name = 'idea_create.html'
success_url = 'success'
def dispatch(self, *args, **kwargs):
self.user = get_object_or_404(User, pk=kwargs['pk'])
return super(IdeaCreateView, self).dispatch(*args, **kwargs)
def form_valid(self, form):
idea = form.save(commit=False)
idea.creator = self.request.user
idea.save()
idea.votes.up(user=idea.creator, vote=True)
idea.vote_score += 1
return HttpResponseRedirect('success')
And then to allow other users to vote on it as well, which falls under this view:
#vote view
class IdeaVoteView(LoginRequiredMixin, CreateView):
form_class = VoteForm
required_fields = ('action',)
template_name = 'vote_confirm.html'
success_url = 'success'
def form_valid(self, form):
obj = Idea.objects.get(pk=self.kwargs['pk'])
user = self.request.user
user_id = self.request.user.pk
object_id = obj.pk
content_type_id = 10
form_class = VoteForm
self.vote = form.save(commit=False)
self.vote.user_id = user_id
self.vote.object_id = object_id
self.vote.content_type_id = content_type_id
if obj.votes.exists(user_id):
return HttpResponseRedirect('failure')
else:
self.vote.save()
obj.votes.up(user_id)
return HttpResponseRedirect('success')
def get_object(self, queryset=None):
obj = Idea.objects.get(pk=self.kwargs['pk'])
voters = obj.get_voters()
return voters
Why doesn't setting the extra_field attribute on the manager take care of this and what's going wrong in the views?
Wow, great news... After talking to myself for hours I figured it out. I created this model function:
def vote_up(self):
self.vote_score += 1
self.save()
The problem was I wasn't calling the save() method on this function so the increment wasn't getting saved! Really simple, but I glossed right over it. Anyway, maybe answering the question will help someone.
The Model flow Topic -> Section -> Article.
I am building an Update View for my FAQ project to update already created Articles. I want the Form to provide a selection of Sections based on the Topic the Article was created under. As I already have the Articles PK passed in through the URL I was hoping to use it to walk back up to the Topic when creating my filter. I am receiving an object has no attribute ‘section’ error when the template is attempting to render the form on line self.fields['section'].queryset = Section.objects.filter(topic_id=self.section.topic.id) in the UpdateAriticleForm. I need help to figure out my query filter.
The URL:
url(r'^ironfaq/article/update/(?P<pk>\d+)/$', ArticleUpdateView.as_view()),
The Form:
from django import forms
from .models import Topic, Section, Article
class CreateArticleForm(forms.ModelForm):
section = forms.ModelChoiceField(queryset=Section.objects.none())
def __init__(self, *args, **kwargs):
topic_pk = kwargs.pop('topic_pk')
super(CreateArticleForm, self).__init__(*args, **kwargs)
self.fields['section'].queryset = Section.objects.filter(topic_id=topic_pk)
class Meta:
model = Article
widgets = {
'answer': forms.Textarea(attrs={'data-provide': 'markdown', 'data-iconlibrary': 'fa'}),
}
fields = ('title','section','answer')
class UpdateArticleForm(forms.ModelForm):
section = forms.ModelChoiceField(queryset=Section.objects.none())
def __init__(self, *args, **kwargs):
super(UpdateArticleForm, self).__init__(*args, **kwargs)
self.fields['section'].queryset = Section.objects.filter(topic_id=self.section.topic.id)
class Meta:
model = Article
widgets = {
'answer': forms.Textarea(attrs={'data-provide': 'markdown', 'data-iconlibrary': 'fa'}),
}
fields = ('title','section','answer')
The View:
class ArticleUpdateView(UpdateView):
model = Article
form_class = UpdateArticleForm
template_name = "faq/form_create.html"
def form_valid(self, form):
article = form.save(commit=False)
article.activity_user = self.request.user.username
article.activity_date = datetime.datetime.now()
article.save()
self.success_url = "/ironfaq/%s/%s/%d" % (article.section.topic.slug,article.section.slug,article.id)
return super(ArticleUpdateView,self).form_valid(form)
The Models:
class Topic(Audit):
name = models.CharField(max_length=255)
icon = models.CharField(max_length=25,blank=True,null=True)
sort = models.SmallIntegerField()
slug = models.SlugField()
class Meta:
verbose_name_plural = "topics"
def __str__(self):
return self.name
class Section(Audit):
name = models.CharField(max_length=255)
sort = models.SmallIntegerField()
slug = models.SlugField()
topic = models.ForeignKey(Topic,on_delete=models.CASCADE)
class Meta:
verbose_name_plural = "sections"
def __str__(self):
return self.name
class Article(Audit):
title = models.CharField(max_length=255)
sort = models.SmallIntegerField()
slug = models.SlugField()
section = models.ForeignKey(Section,on_delete=models.CASCADE)
answer = models.TextField()
vote_up = models.IntegerField(default=0)
vote_down = models.IntegerField(default=0)
view_count = models.IntegerField(default=0)
class Meta:
verbose_name_plural = "articles"
def __str__(self):
return self.title
The answer to the this issue was not passing 'pk' as a argument to the form and to add get_form_kwargs to the view to enable the form to see the 'pk' passed in the URL.
Form:
class UpdateArticleForm(forms.ModelForm):
section = forms.ModelChoiceField(queryset=Article.objects.none())
def __init__(self, pk, *args, **kwargs):
super(UpdateArticleForm, self).__init__(*args, **kwargs)
self.fields['section'].queryset = Section.objects.filter(topic_id__exact=Article.objects.filter(id=pk).first().section.topic.id)
View:
class ArticleUpdateView(UpdateView):
model = Article
form_class = UpdateArticleForm
template_name = "faq/form_create.html"
def get_form_kwargs(self):
kwargs = super(ArticleUpdateView,self).get_form_kwargs()
kwargs.update(self.kwargs)
return kwargs
def form_valid(self, form):
article = form.save(commit=False)
article.activity_user = self.request.user.username
article.activity_date = datetime.datetime.now()
article.save()
self.success_url = "/ironfaq/%s/%s/%d" % (article.section.topic.slug,article.section.slug,article.id)
return super(ArticleUpdateView,self).form_valid(form)