Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
upload image from react to django api
i'm using "react-images-upload" to upload images from react to django api but every time i choose an image i get a re-render to a blank screen export default class CreatePost extends Component { constructor(props) { super(props); this.state = { title: this.props.title, main_post: this.props.main_post, thumbnail: this.props.thumbnail, pictures: [] }; this.handlethumbnail = this.handlethumbnail.bind(this); handlethumbnail(e) { this.setState({ pictures: this.state.pictures.concat(picture), thumbnail: e.target.pictures[0], }); render() { return ( <> <ImageUploader singleImage={true} buttonText='Choose images' onChange={this.handlethumbnail} imgExtension={['.jpg', '.gif', '.png', '.gif']} maxFileSize={5242880} /> } </> i also configured the media folder in setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and in urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
adding a one-to-many django model as a foreign key to another django model
I currently have three models: Member, Driver, and Order, where Member and Driver are one to many models (one member can have multiple taxi orders) and order holds the foreign keys to the Member and Driver models. I've written a script that passes the contents of the input file into my Django models. I've been able to load data into my Member and Driver models; however, I keep getting errors when loading data into my order models, and I suspect its because I used the get_or_create function inside a loop (and is not globally accessible). Is this the case? I thought models would be accessible globally seeing as I'd imported it into the script. Here's my code for reference (also, I'm using Python 2.7 and Django 1.6.11): models.py from django.db import models from django.conf import settings # from datetime import datetime from decimal import Decimal import pymysql # apparently this isn't officially supported by django LOL o well pymysql.install_as_MySQLdb() # Create your models here. ORDER_STATUS = ( ('No Car', 'NC'), ('User Cancelled', 'UC'), ('Completed', 'CC'), ('Driver Cancelled', 'DC'), ) PAYMENT_METHOD = ( ('CA', 'cash'), ('CC', 'creditCard'), ) class Member(models.Model): member_hash = models.CharField(max_length=32) member_loc_lat = models.DecimalField(max_length=20, max_digits = 25, decimal_places = … -
Compare against null value in Django Filefield
In my 'FileField` in models I have the following: document = models.FileField(upload_to='delivered/', null=True, blank=True) I tried to compare against this file field using None but it doesn't work What I tried: d_url = Delivered.objects.filter(allotment_id =a_id).first().document print("d url", d_url) print("d url", type(d_url)) if d_url is None: print("none") There are a few entries where I haven't uploaded the files and in those cases I want to do something but the if statement is never accessed, how do I do it ? -
i'm trying to create a product and save to database but isn't working
I'm trying to create a product and save it. The page redirects where it's supposed to but doesn't save the date. recently I had some problem registering a user and when I fixed it now this problem occurred. views.py from django.shortcuts import render from django.contrib.auth import authenticate,login,logout from .models import myUser,Listings,Bid from django.http import HttpResponseRedirect from django.urls import reverse from .form import registerForm,loginForm,createListingForm from django.db import IntegrityError from django.contrib.auth.decorators import login_required from django.contrib import messages # Create your views here. def index(request): if not request.user.is_authenticated: message = f"please sign in" else : message = f"signed in as {request.user}" return render(request, "auctions/index.html",{ "listings": Listings.objects.all(), "message": message }) def login_view(request): if request.method == "POST": form = loginForm() email = request.POST["email"] password = request.POST["password"] user = authenticate(request,username=email,password=password) if user is not None: login(request,user) return HttpResponseRedirect(reverse('index')) else: return render(request, "auctions/login.html",{ "form": form , "message": "username/password not valid" }) return render(request, "auctions/login.html",{ "form": loginForm() }) def logout_view(request): logout(request) return HttpResponseRedirect(reverse('index')) def register(request): if request.method == "POST": form = registerForm() email = request.POST["email"] # check passwords are same password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render (request, "auctions/register.html",{ "form": form, "message": "Passwords does not match" }) # Attempt to create new user … -
Enforce Django Admin to correctly call .update() instead of .save() to avoid triggering checks meant for object creation
How do we enforce Django Admin to correctly call .update() instead of .save() to avoid triggering checks meant for object creation? This is the models.py: class BinaryChoice(): # field definitions ... def save(self, *args, **kwargs): # check if binary if self.question.qtype == 2: if self.question.choices.count() < 2: super(BinaryChoice, self).save(*args, **kwargs) else: raise Exception("Binary question type can contain at most two choices.") else: super(BinaryChoice, self).save(*args, **kwargs) This passes the test, no surprises: class SurveyTest(TestCase): def test_binary_choice_create(self): q1 = Question.objects.create(survey=survey, title='Have you got any internship experience?', qtype=Question.BINARY) BinaryChoice.objects.create(question=q1, choice="Yes") BinaryChoice.objects.create(question=q1, choice="No") with self.assertRaises(Exception): BinaryChoice.objects.create(question=q1, choice="Unsure / Rather not say") The .save() correctly checks that there isn't already 2 binary choices related to the same Question. However, in Django Admin, when using the interface to update the value (anything arbitrary, for example changing the value from "Yes" to "Sure") and saving it, one would expect the .update() method to be called. It turns out, according to Django docs and also a relevant thread here, the .save() method is called instead. So now our update operation would fail when there's already 2 BinaryChoice, even if you intend to update a value in-place using the Django Admin's default interface. For completeness sake, this is admin.py: … -
How to turn off or terminate my Django app when I click the button on browser
I'm new to python and Django, now I want to ask about how to turn off or terminating my Django app when I click button on my browser. On the browser, I click the button and then sending post request to the server using javascript fetch api. On the server when I sending the POST request, i'm executing exit() command, but it doesn't kill my Django app. Is there a way to kill my Django app? -
Error installing django-vimeo: Failed building wheel for xxhash
I have created a new virtual environment installed Django, I'm using Python3. When I try to run pip3 install django-vimeo it throws me this error. ERROR: Command errored out with exit status 1: command: 'C:\Users\...\env\Scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users...AppData\\Local\\Temp\\pip-install-ntq_y7sl\\xxhash_5774b3470aaf44ff8894164020121d78\\setup.py'"'"'; __file__='"'"'C:\\Users...AppData\\Local\\Temp\\pip-install-ntq_y7sl\\xxhash_5774b3470aaf44ff8894164020121d78\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\apoor\AppData\Local\Temp\pip-wheel-2a0xk73p' cwd: C:\Users\...AppData\Local\Temp\pip-install-ntq_y7sl\xxhash_5774b3470aaf44ff8894164020121d78\ Complete output (5 lines): running bdist_wheel running build running build_ext building 'xxhash' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ ---------------------------------------- ERROR: Failed building wheel for xxhash The error says to install Microsoft Visual C++ 14 or greate in order to fix this but I dont see such a dependency listed in the installation instructions of the package. Did I miss something here? -
Django - Field name is changing to the variable data instead of being filled with the variable data
In the below code, when I call the area variable in the location model field, the name of the model field gets changed to the value of the area variable instead of the field being filled with the area value. What's causing this? class Profile(models.Model): loc = get('http://ipapi.co/json/?key=left_blank_for_reasons') address = loc.json() city = address['city'] region = address['region'] area = city + ", " + region user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') location = models.CharField(area, max_length=100, blank=True) -
multipart upload to S3 with Django-storages
I'm using django-storages to upload large files into s3. Currently testing with files that are 1GB in size and would like to split it into multi part for quicker uploads. I have tried setting AWS_S3_MAX_MEMORY_SIZE to 5mb to see if that would help, but no luck. I could not find any other settings for multipart uploads in the django-storage docs https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html. -
is it safe to only use Paypal client side Integration?
i'm programming a ecommerce website using django and paypal smart Payment Buttons Integration and i want to know if it's safe to only use the client side integration or do i need a server side integration. <script src="https://www.paypal.com/sdk/js?client-id={{ client_id }}&currency=USD"></script> <script> // Render the PayPal button into #paypal-button-container let total = '{{ product.price }}'; paypal.Buttons({ // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: total } }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(details) { // Show a success message to the buyer alert('Transaction completed by ' + details.payer.name.given_name + '!'); }); } }).render('#paypal-button-container'); </script> Thank you in advanced. -
How to create a "not equal" and "not in" filter in django with graphene-django and django-filters
I tried to find solutions on how to carry out not equal and not in filtering, but due to my inexperience I was unable to identify a solution. this is a fragment of my current structure. # result/models.py class Result(models.Model): ... object = models.ForeignKey(Object, on_delete=models.PROTECT) ... # result/types.py class ResultType(DjangoObjectType): class Meta: model = Result filter_fields = { ... 'object__object_name': ['exact', 'icontains'], ... } convert_choices_to_enum = False interfaces = (graphene.relay.Node,) object = DjangoFilterConnectionField(ObjectType) # result/queries.py class Query(object): results = DjangoFilterConnectionField(ResultType) I wanted to be able to perform searches similar to: # result/types.py class ResultType(DjangoObjectType): class Meta: model = Result filter_fields = { ... 'object__object_name': ['exact', 'icontains', 'notequal', 'notin'], ... } convert_choices_to_enum = False interfaces = (graphene.relay.Node,) object = DjangoFilterConnectionField(ObjectType) query { results ( object_ObjectName__Notequal: "Pluto"){ edges { node { object { objectName } } } } } -
Django filter exact value in list
Good day again SO. I was hoping you can help me with some of the logic. Based on this SO Answer, I can filter the search with a list which works perfectly. However, I wish to get an EXACT id instead of at least one matches. models: class Condition: condition_name = models.CharField(....) class Jobs: jobs = models.CharField(...) class JobsConditions: account = models.ForeignKey(Account...) job_item = models.ForeignKey(Jobs...) condition = models.ForeignKey(Condition...) So if I try to search for Jobs with Conditions, I do the following: cond_array = [1,2,4,5] # Append to array based on request. condition_obj = Condition.objects.filter(id__in=cond_array) Then compare condition_obj to JobsConditions model. How to use this so that I will only get only the jobs with exact condition? No more no less. -
Django: UnboundLocalError at /all_hours_report local variable 'HttpResponse' referenced before assignment
I'm stumped. I have a django project and keep getting this error when trying to call HttpResponse. I've ran into this with HttpResponse at random times, but it works in dozens of other places in my project. I've tried many things and am still getting the error. Here is the code snippet throwing the error: from django.template import loader from django.http import HttpResponse from django import template def all_hours_report(request): context={ 'msg' : "You are not authorized" } template = loader.get_template('unauthorized.html') return HttpResponse(template.render(context, request)) Django==2.1.15 Python==3.8 -
Does Django use one thread to process several requests in WSGI or Gunicorn?
As per the title, I am wondering if Django, when run via WSGI or Gunicorn, uses one thread to process several requests? I know it is a bad practice to access the request from places not meant to be accessed from, but I still want to do it. (for good reasons in my opinion, such as accessing the current user and site in my custom template loader. Django template loader doesn't offer these two entities.) Now I managed to get access to the user, etc. from everywhere using the following bit of code: import threading _thread_locals = threading.local() def get_current_user(): request = get_current_request() if request: return getattr(request, "user", None) class RequestThreadMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): _thread_locals.request = request response = self.get_response(request) return response My question/concern is: is it guaranteed that requests/users don't get mixed up in production? I am concerned the second user, for instance, gets identified as the first user because the thread is being used for my than one request. Is that possible, or every request has its own local thread in WSGI and Gunicorn? -
How to create a login in drf
I am making an application in drf that is doing a login validation through the tokens, but I ran into a problem and it is that I have not been able to generate a login because although I create the user and assign a token, it does not I have it been able to perform the login validation: This is my model: from django.db import models from django.conf import settings from django.dispatch import receiver from django.db.models.signals import post_save from django.contrib.auth.models import AbstractUser from rest_framework.authtoken.models import Token class User(AbstractUser): def get_full_name(self): return f'{self.first_name} {self.last_name}' @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_token_user(sender, instance, **kwargs): if kwargs.get('created', False): Token.objects.create(user=instance) This is my serializer: from django.contrib.auth.hashers import make_password from rest_framework import serializers from .models import User class UserSerializer(serializers.ModelSerializer): password2 = serializers.CharField(write_only=True) class Meta: model = User fields = ( 'first_name', 'last_name', 'username', 'email', 'password', 'password2' ) def validate(self, data): if data.get('password') != data.get('password2'): raise serializers.ValidationError('Las contraseñas no son iguales') return data def create(self, validated_data): return User.objects.create( first_name=validated_data.get('first_name'), last_name=validated_data.get('last_name'), username=validated_data.get('username'), email=validated_data.get('email'), password=make_password(validated_data.get('password')) ) This is my view: class CreateUser(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def post(self, request, format=None): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status.HTTP_200_OK) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST) I know drf provides a login: … -
Django - how to render template after AJAX POST request from view function using the context variables pulled from the database
Simple question but can't find the answer. I submit an AJAX post request from my template template1.html, my view function uses the AJAX POST data to lookup objects/context variables from the database. Then I simply want to load a different template template2.html from this view function using those context variables as template tags in this new template (template2.html). I do NOT want to use the AJAX success call-back function to load the next template (because I don't want the context variables displayed in the URL in the GET request). Doing simply render(request, "template2.html", context=context) from within the view does not work. Please help. (To Stackoverflow moderators - there is no reason to close this question. It's sufficiently clear and detailed) -
How to add information to a field from a function created in a view?
How would I take a value from a view function and put it in a model field? For example, let’s say I did a view that adds two numbers together. How would take that value and add it to the field of a model every time an instance of that model is created? Or is there another way of doing this that I’m not seeing. I have a function that takes the user's IP and displays the city and region they are in. I was wondering how I could put that information in a model field every time an instance of that model is created. -
Issue with Model form
forms.py from django import forms from .models import Topic class TopicForm(forms.Form): class Meta: model = Topic fields = ['text'] labels = {'text':''} I receive a runtime error when I run this this code. The error is 'TopicForm has no attribute 'save'. i am using a model form. views.py def new_topic(request): """Add a new topic.""" if request.method != 'POST': # No data submitted; create a blank form. form = TopicForm() else: # POST data submitted; process data. form = TopicForm(data=request.POST) if form.is_valid(): form.save() return redirect('learning_logs:topics') # Display a blank or invalid form. context = {'form': form} return render(request, 'learning_logs/new_topic.html', context) -
How to inject data in a template out of context in html django? form python
forms are passed to the template, which are loaded dynamically depending on the record in the database. that is, in a loop I add shape objects with a key in the form of a number you need to display all forms in a loop in html views class OrderAddView(TemplateView): template_name = 'orders/order_add.html' def get(self, request, *args, **kwargs): context = super().get_context_data(**kwargs) related = self.checkRelated() if related: tag = 0 for x in related: tag += 1 formPath = x.module_name + '.forms' app_form = importlib.import_module(formPath) context[tag] = app_form.RelatedAddForm context['count_form'] = range(1, tag+1) formOne = SimpleOrderAddForm() formOne.prefix = 'one_form' context.update({'formOne': formOne}) return self.render_to_response(context) html <form action="{% url 'order_add' tag %}" method="post"> {% csrf_token %} {% for x in count_form %} {{ context[x].as_p }} {{ x.as_p }} {% endfor %} {{ formOne.non_field_errors }} {{ formOne.as_p }} <button type="submit" class="btn btn-primary btn-block">Add order</button> </form> forms do not appear! how to specify a reference to an object by this key in a loop? if I output directly, for example {{1.as_p}}, it outputs the form, but if {{x.as_p}} is in a loop, where x = 1, it doesn't. how to be print context form {'tag': 'fast', 'view': <orders.views.OrderAddView object at 0x0000000007422DF0>, 1: <class 'clients.forms.RelatedAddForm'>, 'count_form': range(1, 2)} -
Error when running django-admin in command line "ModuleNotFoundError: No module named 'asyncio.base_events'"
Created the virtual env with pyenv pyenv init pyenv shell 3.9.0 python -m venv name_of_venv Installed Django through pip in a virtual env: pip install Django==3.1.7 Then when I run django-admin in cmd line I get the following error: File "/Users/sushensatturu/envs/excel/bin/django-admin", line 5, in <module> from django.core.management import execute_from_command_line File "/Users/sushensatturu/envs/excel/lib/python3.9/site-packages/django/core/management/__init__.py", line 12, in <module> from django.conf import settings File "/Users/sushensatturu/envs/excel/lib/python3.9/site-packages/django/conf/__init__.py", line 19, in <module> from django.utils.deprecation import RemovedInDjango40Warning File "/Users/sushensatturu/envs/excel/lib/python3.9/site-packages/django/utils/deprecation.py", line 1, in <module> import asyncio File "/Users/sushensatturu/.pyenv/versions/3.9.0/lib/python3.9/asyncio/__init__.py", line 8, in <module> from .base_events import * -
Django: Page not found , Raised by:django.views.static.serve
I am trying to display a static image in django. When I select image using django admin portal then it's works fine. it is displaying image. But when I select image from my front-end page, I get: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/media/destination-2.jpg Raised by: django.views.static.server Here are my codes: urls.py from django.urls import path,include from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from mainapp import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('mainapp.urls')), ] admin.site.site_header = "Login to our web Portal" admin.site.site_title = "This is Admin Portal" admin.site.index_title = "Welcome to Amnet" #urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py STATICFILES_DIRS=[os.path.join(BASE_DIR,'static') ] MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(BASE_DIR,'media') models.py from django.db import models # Create your models here. class Amnet(models.Model): imagee = models.FileField(default='bg_2.jpg') views.py from django.shortcuts import render from mainapp.models import Amnet # Create your views here. def index(request): if(request.method == "POST"): imagee= request.POST.get('imagee') am = Amnet(imagee=imagee) am.save() return render(request,'image-main.html') else: return render(request,'image-main.html') html page <form action="" method="POST"> {% csrf_token %} <td><input type="file" name="imagee" id="file"></td> <td><img src="" id="profile-img-tag" width="200px" /></td> </tr> </table> <input type="Submit" value="Submit" id="btn"><br> </form> -
meaning of django migrate ModuleNotFoundError
https://tryhackme.com/room/django I am trying to follow the above django tutorial. django-admin startproject mysite cd mysite python3 manage.py migrate python3 manage.py startapp Articles In mysite/settings.py, I modified the following line. INSTALLED_APPS = [ 'Articles', # add 'django.contrib.admin', ... In mysite/urls.py, I changed the following lines. from django.urls import path, include # modified urlpatterns = [ path('Articles/', include('Articles.urls')), # added But when I run the following command, it fails. Does anybody know what is wrong? Thanks. $ python3 manage.py migrate Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 65, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/urls/resolvers.py", line 584, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File … -
Cual es la forma correcta de importar una app en INSTALLED_APPS cuando las app esta en una carpeta?
Estoy trabajando en un pequeño proyecto y tiene la siguiente estructura de directorios: Web/ apps/ crud login perfil necesito poner la configuraciones de mi app en INSTALLED_APPS pero no se de que forma ya que lo normal seria : perfil.apps.PerfilConfig lo hago de esta manera : apps.perfil.apps.PerfilConfig y me sale el siguiente error """ django.core.exceptions.ImproperlyConfigured: Cannot import 'perfil'. Checkthat'apps.perfil.apps.PerfilConfig.name' is correct """ mi pregunta es, cual es la manera de hacerlo cuando las app estan en otra carpeta, gracias -
{{ form.object }} in Django UpdateView
According to the docs self.object exists for UpdateView Template: {% block content %} <p> {{ form.object.some_foreign_key }} </p> <form method="post"> {{ form.as_p }} <input type="submit" value="Update"> </form> {% endblock %} But form.object does not exist: Failed: Undefined template variable 'form.object' in '/foo/bar_form.html' Why does form.object not exist in the template? -
How can I filter the results of a view with multiple contexts in Django?
I want to make a view that details the poll result listing the alternatives and the total votes for each alternative, but I can't filter the votes since a list of alternatives is returned when I take the poll's pk. So I can't filter the votes by the alternative pk. class Poll(models.Model): text = models.TextField(max_length=500, verbose_name="Poll") class Alternative(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE) alternative_text = models.CharField(max_length=50, verbose_name="Alternative") class Vote(models.Model): alternative = models.ForeignKey(Alternative, on_delete=models.CASCADE) quantity_votes = models.IntegerField(default=0, null=True, blank=True) vote_date = models.DateField(auto_now=True) # My view def result_poll(request, pk): poll = Poll.objects.get(pk=pk) alternatives = Alternative.objects.filter(poll_id=poll.id) votes = Vote.objects.filter(alternatives) #just to exemplify context = { 'poll': poll, 'alternatives': alternatives, 'votes': votes, } return render(request, 'result.html', context)