Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
what is the use of this package 'django-tenant-users'?
I want to know how to access a Django multitenant user in a single login(my-domain.com/login). After logging in it should be redirected to a specific tenant subdomain(tenant1.my-domain.com). 'django-tenant-users' this package is helpful or not for multiple tenants in single login. https://github.com/Corvia/django-tenant-users Please give me a solution to that. -
AssertionError: First parameter to ForeignKey must be either a model, a model name, or the string 'self'
I just created a model like this : from django.db import models # Create your models here. class Category: title = models.CharField(max_length=50) slug = models.CharField(max_length=200) cat_image = models.ImageField(upload_to='images/') def __str__(self): return self.title class Brand: title = models.CharField(max_length=50) slug = models.CharField(max_length=200) brand_image = models.ImageField(upload_to='images/') def __str__(self): return self.title class UOM: title = models.CharField(max_length=100) def __str__(self): return self.title class Product_Images: multi_images = models.ImageField(upload_to='images/') class Product: name = models.CharField(max_length=100) slug = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) price = models.IntegerField(null=True, blank=True) height = models.IntegerField(null=True, blank=True) weight = models.IntegerField(null=True, blank=True) length = models.IntegerField(null=True, blank=True) color = models.IntegerField(null=True, blank=True) stock = models.BooleanField() SKU = models.CharField(max_length=150) def __str__(self): return self.name class Customer: phone_number = models.CharField(max_length=11) first_name = models.CharField(max_length=10) last_name = models.CharField(max_length=10) email = models.CharField(max_length=20) password = models.CharField(max_length=10) def __str__(self): return self.first_name class Order: customer = models.ForeignKey(Customer, on_delete=models.CASCADE) invoice = models.CharField(max_length=16, null=True, blank=True) phone = models.CharField(max_length=12) address = models.CharField(max_length=150) But facing this error dont have any idea why i am getting this kind of error. I cant even makemigrations if i delete some fields. It says no change detected but i changed some fields still getting this kind of error can some one solve this issue for me. and please explain why ia magetting … -
Django User Model AttributeError: 'str' object has no attribute 'objects'
I am using django as my backend for a project but anytime i perform queries on my User model, i get the error AttributeError: 'str' object has no attribute 'objects' But this error only occurs when i import the user model from settings from django.conf import settings User = settings.AUTH_USER_MODEL but not from from django.contrib.auth.models import User Settings.py AUTH_USER_MODEL = 'users.User' User's Models.py from django.db import models from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from rest_framework.authtoken.models import Token class UserManager(BaseUserManager): def create_user(self, email,username, password, phone, **extra_fields): if not email: raise ValueError("Email Address Is Needed") if not username: raise ValueError("Username Must Be Provided") email = self.normalize_email(email) user = self.model( email=email, username=username, phone=phone ) user.set_password(password) user.is_active = False user.save() def create_superuser(self, email,username, password,phone): email = self.normalize_email(email) user = self.model( email=email, username=username, phone=phone ) user.set_password(password) user.is_active = True user.is_admin = True user.save() class User (AbstractBaseUser): username = models.CharField(max_length=254,blank=False,null=False,unique=True) email = models.EmailField( unique=True, max_length=254, blank=False, null=False) phone = models.CharField(max_length=250,blank=False,null=False,unique=True) is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email','phone'] def get_full_name(self): return f"{self.first_name} {self.last_name}" def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" … -
Can't retrieve value from Django Template (.html) to my views
I'm new to Django and I'm trying to develop an apllication that deals with learning objects metadata. One of the functions of the system is to view the L.O. metadata in browser. I have an HTML template that lists the result of the query from the database. Each result come along with a "Visualize Metadata" button, that when clicked, should display the metadata of that object in browser. So I want my button to pass the object ID back to my view, so i can make another query by the specific ID and print the results on the screen. This is my template .html {% if objects %} <ul> {% for object in objects %} <li> {{ object.General.title }} <form action='visualize' method='POST' name='id' value="{{object.General.id}}"> {% csrf_token %} <button type="submit" >Visualize Metadata </button> </form> </li> {% endfor %} </ul> {% else %} <p>No results found.</p> {% endif %} And this is my views.py function def visualize_lom_metadata(request): if request.method == 'POST': objID = request.POST.get('id') return HttpResponse(objID) For now i just want to see if that's possible by printing the objID in the screen. But when I try to do that,it just returns "None". Anyone knows how to retrieve data from template.html to … -
Django ModeForm display model field of foreign key instead object id
I am trying to show a model field in a select field in my template. I am using a foreign key which is selected in the select field. The problem is that only the object id is shown. How can I make it show a model field of my foreign key ('crt_id' from Certificate model for example) and not an object and the id? (see picture) Thank you in advance my code: Certificate model class Certificate(models.Model): crt_id = models.CharField(max_length=60) crt_expire = models.DateTimeField() crt_active = models.BooleanField(default=False) Device model class Device(models.Model): device_name = models.CharField(max_length=64) device_group = models.CharField(max_length=64) device_certificate = models.ForeignKey(Certificate, models.SET_NULL, blank=True, null=True) forms.py class DeviceForm(forms.ModelForm): device_group = forms.CharField(required=False) device_name = forms.CharField(required=True) class Meta: model = Device fields = [ 'device_name', 'device_group', 'device_certificate' ] -
How to implement orm left join
I have to following models: class A(models.Model): id = models.IntegerField(max_length=20, primary_key=True) appid = models.IntegerField(max_length=20,default=0) status = models.IntegerField(max_length=20) class B(models.Model): id = models.IntegerField(max_length=20, primary_key=True) appid = models.IntegerField(max_length=10,null=False,default='0') c = models.ForeignKey(C) a = models.ForeignKey(A) class C(models.Model): appid = models.IntegerField(default=0) ip = models.CharField(max_length=50, null=True, blank=True) Now I want a Django query: select C.ip,status from A left join C on A.appid = C.appid where appid = B.appid; Please kind people help me how to use orm to achieve -
How to pass a variable from a Django view to forms.py, to assist in overriding a query for a field?
I'm trying to pass a variable to a Django form to use as the criteria to filter my queryset by. The setup is that there are 'contestants', 'entries' and 'teams', and for a form on a page to view entries, I want to show only contestants on the same team as the logged in user. My attempt currently is with my view: def viewentry(request, urlid): entry = Entry.objects.get(id=urlid) team_id = entry.assigned_contestant.assigned_team.id form = AssignTeamContestantForm() if request.method == 'POST': form = AssignTeamForm(request.POST, instance=entry, team_id=team_id) if form.is_valid(): form.save() context = { 'entry': entry, 'urlid': urlid, 'form': form, } return render(request, 'entries/entry.html', context) and in my form: class AssignTeamContestantForm(forms.ModelForm): def __init__(self, team_id, *args, **kwargs): super(AssignTeamContestantForm, self).__init__(*args, **kwargs) self.fields['assigned_contestant'].queryset = Contestant.objects.filter(assigned_team__id=team_id) class Meta: model = Entry fields = ['assigned_contestant'] labels = {'assigned_contestant': ''} This is my latest attempt, I've been trying a lot of different things based on other answers I've found but can't seem to get anything to stick. What is the best approach for this problem with Django 3? -
What does max_retries and retry_backoff_max mean if retry_backoff is set to True in Celery?
The celery documentation gives the following example for automatically retrying a task: class BaseTaskWithRetry(Task): autoretry_for = (TypeError,) retry_kwargs = {'max_retries': 5} retry_backoff = True retry_backoff_max = 700 retry_jitter = False retry_backoff means that Celery will use exponential backoff - so in this case (according to the docs): The first retry will have a delay of 1 second, the second retry will have a delay of 2 seconds, the third will delay 4 seconds, the fourth will delay 8 seconds, and so on. However, in the example max_retries is five, and yet retry_backoff_max is 700. I would think that if max_retries is set to five, then the retries would happen at one second, two seconds, four seconds, eight seconds, and sixteen seconds. That is all, because that's five retries. The backoff never gets anywhere close to 700 seconds. Is retry_backoff_max in the given example pointless? What does max_retries of five actually mean in this example? -
Streaming zip in Django for large non-local files possible?
I've got a proxy written in Django which receives requests for certain files. After deciding whether the user is allowed to see the file the proxy gets the file from a remote service and serves it to the user. There's a bit more to it but this is the gist. This setup works great for single files, but there is a new requirement that the users want to download multiple files together as a zip. The files are sometimes small, but can also become really large (100MB plus) and it can be anywhere from 2 up to 1000 files simultaneously. This can become really large, and a burden to first get all those files, zip them and then serve them in the same request. I read about the possibility to create "streaming zips"; a way to open a zip and then start sending the files in that zip until you close it. I found a couple php examples and in Python the django-zip-stream extension. They all assume locally stored files and the django extension also assumes the usages of nginx. There are a couple things I wonder about in my situation: I don't have the files locally stored. I can … -
How to find the highest value of a ForeignKey field for a specific user in Django
I am building an app that allows users to record their workouts. First they will create an exercise, (e.g Bench Press), and then they will complete a form to show how much weight they were able to lift for that specific exercise. Their results will display below the form. There will be many workout forms, relating to many different workouts. The workouts and exercises will also be specific to each user. Here is my models.py: from django.contrib.auth.models import User class Exercise(models.Model): name = models.CharField(max_length=100) class Workout(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) weight = models.DecimalField(default=0.0, max_digits=5, decimal_places=1) exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, default=None) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) What I now want to do is be able to show the user what their max lift was for each different workout, but can't figure out how to retrieve this information. I have searched for the answer online and it seems that using aggregate or annotate might be the way to go, but I have tried a bunch of different queries and can't get it to show what I need. Hope somebody can help. -
Static files not loaded into templates
I am new to Django and so far all I know about static files is that they are CSS, JS, and images and they should be in a directory called static within the app directory but when I use one of these files in my template like that: first I load the static files {% load static %} <!-- in the 1st line of the template --> then I link the CSS file like that <link href="{% static 'auctions/styles.css' %}" rel="stylesheet"> They don't load and the styles don't seem to appear so I just want to know what I am missing here -
Django container fails to connect MySQL container with error "Can't connect to MySQL server on 'db' (115)" in the first migration
I am trying set up a Django development environment using Docker. But, the Django container fails to connect to MySQL container with following error: django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)") Please give me some advises to solve this problem. Below is the structure of the directory: . ├── python │ ├── Dockerfile │ └── requirements.txt ├── docker-compose.dev.yml ├── mysql │ ├── conf.d │ │ └── default_authentication.cnf │ ├── Dockerfile │ └── init.d │ └── init.sql ├── nginx Below is the Docker configuration: ("octave" is the name of the web application). version: '3.7' services: python: build: context: ./python dockerfile: Dockerfile command: uwsgi --socket :8001 --module octave.wsgi --py-autoreload 1 --logto /tmp/uwsgi.log restart: unless-stopped container_name: Django networks: - django_net volumes: - ./src:/code - ./static:/static expose: - "8001" depends_on: - db db: image: mysql:latest restart: unless-stopped container_name: MySQL networks: - django_net ports: - "3306:3306" environment: MYSQL_ROOT_PASSWORD: ${OCTAVE_DB_PASSWORD:-default} TZ: "Asia/Tokyo" volumes: - octave.db.volume:/var/lib/mysql - ./mysql/init.d:/docker-entrypont-initdb.d - ./mysql/conf.d:/etc/mysql/conf.d (... the configuration of nginx is omitted.) networks: django_net: driver: bridge volumes: octave.db.volume: name: octave.db.volume Below is requirements.txt: Django==3.1.4 uwsgi==2.0.18 mysqlclient==2.0.1 Below is mysql/init.d/init.sql: CREATE DATABASE IF NOT EXISTS octave_db CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; CREATE USER IF NOT EXISTS 'octave_user'@'%' IDENTIFIED BY ${OCTAVE_DB_PASSWORD} … -
OperationalError at /admin in Django
I am following this article from simpleisbetterthancomplex to build a multiple usertype in django. but when i visit the admin page this is the error i get. "no such column: catalog_merchant.user_id" models.py class User(AbstractUser): is_customer=models.BooleanField(default=False) is_merchant=models.BooleanField(default=False) class Customer(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) class Merchant(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) shop_name=models.CharField(max_length=100) shop_address=models.CharField(max_length=100) phone_number=models.IntegerField() email_address=models.EmailField() country=models.CharField(max_length=100) city=models.CharField(max_length=100) state=models.CharField(max_length=100) zip_code=models.IntegerField() thanks beforehand. -
Customize the JSON output in django-rest api
I'm working on the creation of a django REST api where I can visualize some numerical data of different variables. This values are allocated on a database (using sqlite) each one as a column of the same table. The problem is that the results appear as an array of objects like this: (each object is a row in the table) But I would like to have it in the form of a object of arrays: "results": { "dir_racha": [125.0,137.0,131.0], "hum_rel": [87.0,87.0,86.0], // } I found out that I can use posgres' models.ArrayField object, but I don't want to change my database engine. Also, I think I can get what I want by using JsonResponse and doing it by hand, but I want to use django REST framework if possible. This is the model I use: class Data(models.Model): dir_racha = models.FloatField() hum_rel = models.FloatField() presion = models.FloatField() racha = models.FloatField() tem = models.FloatField() v_vent = models.FloatField() datetime = models.CharField(max_length=20, primary_key=True) def __str__(self): return 'Data.' The serializer class: class DataSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Data fields = ('dir_racha', 'hum_rel',\ 'presion', 'racha', 'tem', 'v_vent', 'datetime') And finally the viewset: class DataViewSet(viewsets.ModelViewSet): queryset = Data.objects.all().order_by('datetime') serializer_class = DataSerializer -
Many кусщкві in the foreign key field (ModelForm Django)
I have tables: # model.py class ctNovaPoshta(models.Model): SiteKey = models.CharField(max_length=50, verbose_name="Код відділення", primary_key=True) ShortAddress = models.CharField(max_length=200, verbose_name="Адреса відділення") Number = models.CharField(max_length=50, verbose_name="Номер відділення") def __str__(self): return f'{self.ShortAddress} [{self.Number}]' class docOrder(models.Model): ... nova_poshta = models.ForeignKey(ctNovaPoshta, null=True, blank = True, on_delete = models.DO_NOTHING, verbose_name="Нова пошта") # form.py OrderFormSet = inlineformset_factory(docOrder, docOrderProduct, form=OrderProductForm, extra=1, ) # view.py class OrderProductCreate(CreateView): template_name = 'order/order_create.html' model = docOrder fields = ['description', 'client', 'type_price', 'status', 'date_ship', 'nova_poshta'] success_url = reverse_lazy('order-list') def get_context_data(self, **kwargs): data = super(OrderProductCreate, self).get_context_data(**kwargs) if self.request.POST: data['product'] = OrderFormSet(self.request.POST) else: data['product'] = OrderFormSet() return data def form_valid(self, form): ... In the table ctNovaPoshta I have 10,000 records. So when I generate an html page: ... <div class="tab-pane fade" id="nav-contact" role="tabpanel" aria-labelledby="nav-contact-tab"> {{ form.nova_poshta|as_crispy_field }} </div> ... I have a very buggy browser. How to properly generate an html page in such crap? What are the approaches to solving this problem? is it possible to completely change the display logic? -
How to edit data from database in Django?
I'm a beginner in Django . I got all data associated with User and displayed it in a table. And one field in the table is a dropdown which can be used to change the value in each row and there is an update button at the end to update changes(if any) in the dropdown.How can i do the updation ? I know it is simple. What should i do ? Just guide me .ThankYou //views.py @method_decorator(login_required, name='dispatch') class AllUsersView(TemplateView): template_name = 'users/all_users.html' def get_context_data(self, **kwargs): context = super(AllUsersView, self).get_context_data(**kwargs) context['users'] = User.objects.all() return context // all-users.html <table class="addrss-list"> <tr> <th>Name</th> <th>Email</th> <th>Country</th> <th>Plan</th> <th>Role</th> <th>Action</th> </tr> {% for user in users %} <tr> <td>{{user.username}}</td> <td>{{user.email}}</td> <td>{{user.country}}</td> <td>{{user.subscription.active_plan.title}}</td> <td> {% if user.role == "student" %} <select> <option selected>Student</option> <option>Tutor</option> </select> {% elif user.role == "tutor" %} <select> <option selected>Tutor</option> <option>Student</option> </select> {% endif %} </td> <td><a href="/update-user/{{user.id}}" class = "text-decoration-none">Update</a></td> </tr> {% endfor %} </table> -
Work with templates as frontend developer
I have accepted a job, in which I have to work on some html and css in frontend. However, the files I was given to work with seem to be interpreted by some kind of interpreter (I think Django or Jinja2). All I have however are frontend files and I cannot figure out, how to debug my code without any interpreter. F:. ├───static │ ├───css │ └───images │ └───navigation └───templates ├───admin ├───cart ├───home ├───order ├───partials ├───payment ├───product ├───ticket └───user above I have listed the folders I have to work with. Each folder only contains html files, that look like this for example: <input id="navi-open" type="checkbox" name="" class="ct" /> <div id="navigation" class="column"> <label for="navi-open" class="navi-button"> <img src="{{ url_for('static', filename='images/cancel.png') }}" alt="" /> </label> <div id="navigation-items" class="column h-sb"> <div class="category"> <a href="{{ url_for('home.home') }}" style="opacity:1" class="navigation-item light {{ 'active' if current_page == 'homepage' else '' }}"> <div style="opacity:1" class="icon"> <img src="{{ url_for('static', filename='images/karma_blackwhite.png') }}" alt="" style="filter: invert(0);" /> </div> <div class="label">Homepage</div> <div class="tooltip">Homepage</div> <div class="indicator"></div> </a> <a href="{{ url_for('home.news') }}" class="navigation-item {{ 'active' if current_page == 'news' else '' }}"> <div class="icon"> <img src="{{ url_for('static', filename='images/navigation/newspaper.png') }}" alt="" /> </div> <div class="label">News</div> <div class="tooltip">News</div> <div class="indicator"></div> </a> <a href="{{ url_for('home.about') }}" class="navigation-item … -
How to avoid typing "python" at the begining of new command [closed]
I have two notebooks Windows 10. Both with same installed PyCharm version. If I want to perform a command: At the first one I should type: manage.py runserver At another one I must type: python manage.py runserver (without word "python" the command would not perform). How to fix at the 2nd notebook to avoid typing "python" every time ? P.S. I added all routes to python39.exe to the PATH - no result. -
module has no Attribute in Django
i check everything but i still can't figure out the problem. this is the error that i get "AttributeError: module 'users.views' has no attribute 'CustomerSignUp' " urls.py path('customer/register/', views.CustomerSignUp.as_view(), name='customer_homepage'), path('merchant/signup/',views.MerchantSignUpView.as_view(), name='merchant_signup'), views.py class CustomerSignUpView(CreateView): model = User form_class = CustomerSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'customer' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('catalog:index') thanks beforehand. -
Using Proxy as Static IP [PythonAnywhere] [closed]
recently I deployed a python web on Pythonanywhere and I also integrate some third-parties in it, then turned out I need a Static IP for third-parties to add to whitelist. Unlucky for me, PythonAnyWhere doesn't support it. As I intend to use a Proxy server for this purpose, will it work or do you have any advices for it. Many thanks in advance, -
Which Language or Framework Should I Use to Create an ETL
I am trying to build an ETL app which can schedule automated ingestion of weather and agriculture data from websites like agromonitoring.com and openweathermap.org. The app should, on schedule, pull data from an API, split the contents of the JSON response into individual JSON files and save it in AWS S3. The same app should also POST this same JSON to another API endpoint. I am unsure which language/framework or technology to study and use for this project. I tried with Apache Nifi but I am unable to figure out how to dynamically change the date parameter on the API's URL. What is the easiest and fastest way to do this? Thank you in advance for the assistance! -
Multiple forms in django template always submitting same form
I have a template with 3 forms, and submitting any of the last 2 always only results in the first form being submitted. I've searched on this issue, and tried adding prefixes and conditional logic like is suggested in answers to this question, but neither solution is working for me. A single form works absolutely fine, it is just attempting to get 3 working, or even 2, where I am running into issues. Is there another solution other than using conditional logic and prefixes? My current attempt is: if request.method == "POST": approveform = ApproveOrDenyForm(request.POST, instance=contestant, prefix='approved') if approveform.is_valid(): contestant = approveform.save() else: approveform = ApproveOrDenyForm(instance=contestant, prefix='approved') if request.method == "POST" and not approveform.is_valid(): statusform = ChangeStatusForm(request.POST, instance=contestant, prefix='status') if statusform.is_valid(): contestant = statusform.save() else: statusform = ChangeStatusForm(instance=contestant, prefix='status') if request.method == "POST" and not approveform.is_valid() and not statusform.is_valid(): assignteamform = AssignTeamForm(request.POST, instance=contestant, prefix='assignteam') if assignteamform.is_valid(): contestant = assignteamform.save() else: assignteamform = AssignTeamForm(instance=contestant, prefix='assignteam') I tried adding conditional logic to every form also, e.g. making sure approveform was not statusform or assignteamform, but it made no difference. What is the correct approach here? -
Django heroku : Unable to deploy application (ModuleNotFoundError)
When I am deploying my Django application on Heroku, the application crash and Heroku's logs notify me about this error : 2020-12-07T12:55:55.982458+00:00 app[web.1]: ModuleNotFoundError: No module named 'WebSite' The thing is, WebSite is not a python module, but a folder in my Django application (Achievement Comparer behing my main application name). Repository picture Of course, if I start my application locally, everything works just fine. -
Loading "/Media/" files with Django Webpack Loader
After I setup a frontend with a django webpack loader, the media files are not rendering. settings.py STATIC_URL = '/static/' MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) WEBPACK_LOADER = { "DEFAULT": { "BUNDLE_DIR_NAME": "dist/", "STATS_FILE": os.path.join(BASE_DIR, "frontend", "webpack-stats.json"), } } And urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include("companies.routes.urls")), path('api/v2/', include("projects.routes.urls")), path('accounts/register/', RegistrationView.as_view( form_class=CompanyUserForm, success_url="/", ), name="django_registration_register"), path('accounts/', include("django_registration.backends.one_step.urls")), path('accounts/', include("django.contrib.auth.urls")), path('api-auth/', include("rest_framework.urls")), path('api/rest_auth/', include("rest_auth.urls")), path('api/rest_auth/django_registration/', include("rest_auth.registration.urls")), re_path(r'^.*$', IndexTemplateView.as_view(), name="entry-point") ] # adding the media root path. urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But when I browse the media file url, image isn't rendering. I think the problem lies in the webpack loader, but I am not sure how to fix the issue here. -
How to restrict anonymous users to vote only once in django poll app?
I want to limit that each user can only vote once for a question in my poll application. In case of authenticated users my code works very well, however when an anonymous user (not registered) try to vote I got the next error: TypeError: 'AnonymousUser' object is not iterable How can I restrict that anonymous users could vote only once? You can see my related code here: models.py: class Question(models.Model): question_text = models.TextField("Question", max_length=300) category = models.CharField(max_length=100) pupblish_date = models.DateTimeField(default=now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField("Choice",max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class Vote(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) voter = models.ForeignKey(User, on_delete=models.CASCADE) views.py: def vote_view(request, poll_id): poll = get_object_or_404(Question, pk=poll_id) if Vote.objects.filter(question=poll, voter=request.user).exists(): messages.error(request,"Already Voted on this choice") return redirect("poll_app:home") else: if request.method == "POST": try: selected_choice = poll.choice_set.get(pk=request.POST["clap"]) except(KeyError): return render(request, "poll_app/vote.html", { "poll": poll, "error_message": "You haven't voted yet!" }) else: selected_choice.votes += 1 selected_choice.save() Vote.objects.create(voter = request.user, question=poll) return redirect(reverse("poll_app:result", args=(poll.id,))) else: context = {"poll": poll} return render(request, "poll_app/vote.html", context) Thanks!