Answer the question
In order to leave comments, you need to log in
How to retrieve all data from database?
I'm doing a vote in Python Django, the main page should display the result of the votes of all users, but I only display the results of the current user. How to fix it?
views.py
def home(request):
value, create = Choose.objects.get_or_create(voter=request.user)
context = {
"value": value,
}
return render(request, 'registration/home.html', context)
def black(request):
if request.user.is_authenticated:
value, created = Choose.objects.get_or_create(voter=request.user)
if request.method == 'POST':
select_action = request.POST['choose']
if select_action == 'black':
value.count_black += 1
value.save()
else:
return render(request, 'registration/black.html', {"value": value})
return redirect("home")
class Choose(models.Model):
count_black = models.PositiveIntegerField(default=0, verbose_name="black")
count_white = models.PositiveIntegerField(default=0, verbose_name="white")
count_purple = models.PositiveIntegerField(default=0, verbose_name="purple")
voter = models.ForeignKey(User, null=True, blank=True, verbose_name='Пользователь',
on_delete=models.PROTECT)
<h1 style="color: white">{{ value.count_black }} </h1>
Answer the question
In order to leave comments, you need to log in
1. Did you read the docs (well, or at least articles) on ORM django?
2. Did you write the code yourself?
Something tells me that in both cases - no, because it is very easy not to understand how this method works, even having minimal knowledge on the topic (and even just knowing English and being friends with logic).
Choose.objects.get_or_create(voter=request.user)
It tries to find a suitable object, and if it doesn't exist, it creates it. That's all
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question