Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting getattr(): attribute name must be string error when running django test
I'm new to Django. I am building an app that requires a lot of control over user access to various use and features. For this I created a model called 'UserType' that has some user groups as objects i.e. scanner, overwatch, lancer and admin. Another model, AssignedType, assigns users to one or more UserType. It has two fields. 'user' which is related to User model and 'user_type' which is related to UserType model. A file 'rights.py' controls user access. Everything is working fine until I try to test it in tests.py Following is my code from tests.py from django.test import TestCase, Client from django.urls import reverse from DataMech.models import User, UserType, AssignedType class TestScanner(TestCase): def setUp(self): scanner1 = User.objects.create(username='scanner1', password='abc') scanner2 = User.objects.create(username='scanner2', password='abc') overwatch1 = User.objects.create(username='overwatch1', password='abc') overwatch2 = User.objects.create(username='overwatch2', password='abc') lancer1 = User.objects.create(username='lancer1', password='abc') lancer2 = User.objects.create(username='lancer2', password='abc') lancer3 = User.objects.create(username='lancer3', password='abc') lancer4 = User.objects.create(username='lancer4', password='abc') admin1 = User.objects.create(username='admin1', password='abc') scanner, created = UserType.objects.get_or_create(name='scanner') overwatch, created = UserType.objects.get_or_create(name='overwatch') lancer, created = UserType.objects.get_or_create(name='lancer') admin, created = UserType.objects.get_or_create(name='admin') AssignedType.objects.create(user=scanner1, user_type=scanner) AssignedType.objects.create(user=scanner2, user_type=scanner) AssignedType.objects.create(user=overwatch1, user_type=overwatch) AssignedType.objects.create(user=overwatch2, user_type=overwatch) AssignedType.objects.create(user=lancer1, user_type=lancer) AssignedType.objects.create(user=lancer2, user_type=lancer) AssignedType.objects.create(user=lancer3, user_type=lancer) AssignedType.objects.create(user=lancer4, user_type=lancer) AssignedType.objects.create(user=admin1, user_type=admin) AssignedType.objects.create(user=admin1, user_type=scanner) def test_allow_access_only_if_user_is_authorized_GET(self): c = Client() c.login(username='scanner1', password='abc') response = c.get(reverse('scanner')) self.assertEquals(response.status_code, 200) … -
How to get forloop.counter inside two forloops
I have a for loop inside another for loop and im trying to get the index (forloop.counter) from the inner loop. Django is for some reason giving me only the outer index. {% for category in categories %} {% for product in products %} {% if product.category.name == category.name %} <p>This is the amount of products inside this category: {{ forloop.counter }}<p> {% endif %} {% endfor %} {% endfor %} -
python sports.py api error unable to fetch cricket score
import sports matches = sports.get_sport(sports.CRICKET) for item in matches: print(item) Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\xml\etree\ElementTree.py", line 1700, in close self.parser.Parse("", 1) # end of data xml.parsers.expat.ExpatError: no element found: line 1, column 0 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\sports\scores.py", line 45, in _request_xml return _load_xml(r.content) File "C:\ProgramData\Anaconda3\lib\site-packages\sports\scores.py", line 59, in _load_xml return ET.fromstring(xml_data).find('channel').findall('item') File "C:\ProgramData\Anaconda3\lib\site-packages\defusedxml\common.py", line 132, in fromstring return parser.close() File "C:\ProgramData\Anaconda3\lib\xml\etree\ElementTree.py", line 1702, in close self._raiseerror(v) File "C:\ProgramData\Anaconda3\lib\xml\etree\ElementTree.py", line 1602, in _raiseerror raise err xml.etree.ElementTree.ParseError: no element found: line 1, column 0 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "F:\study\python\projects\friday\a.py", line 4, in matches = sports.get_sport(sports.CRICKET) File "C:\ProgramData\Anaconda3\lib\site-packages\sports\scores.py", line 106, in get_sport data = _request_xml(sport) File "C:\ProgramData\Anaconda3\lib\site-packages\sports\scores.py", line 47, in _request_xml raise errors.SportError(sport) sports.errors.SportError: Sport not found for cricket -
Form is not displaying
I have 2 views, DetailView is displaying the post data and CreateView is creating comment to this post. The problem is my template isnt rendering any comment form and theres no error in my console and I have no idea why this is not working. Am i doing something wrong? If yes, Can I implement this differently? If yes, what should I use? Thank you in advance :) views code: class PostDetailView(LoginRequiredMixin, DetailView): model = Post context_object_name = 'post' template_name = 'post/details.html' class CommentCreate(LoginRequiredMixin, CreateView): model = Comment form_class = CommentCreationForm context_object_name = 'forma' template_name = 'post/details.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) details.html template code: {% extends 'base.html' %} {% load static %} {% block content %} <h1>POST</h1> {{ post.content }} <hr> <form action="" method="post"> {% csrf_token %} {{ form }} <button class="btn btn-default" type="submit">Comment</button> </form> {% endblock content %} comment form: class CommentCreationForm(forms.ModelForm): class Meta: model = Comment fields = ('text', ) comment model: class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) text = models.TextField() date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) -
Get Image from my Django application in flutter
I'm trying to display images in my flutter application from my Django website.djangoApi but the problem in my flutter i can't see my pictures. (i don't know if the problem in my Django or flutter app) Flutter app: import 'dart:async'; import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; Future<List<Photo>> fetchPhotos(http.Client client) async { final response = await client.get('https://pure-eyrie-09235.herokuapp.com/photoAPI'); // Use the compute function to run parsePhotos in a separate isolate. return compute(parsePhotos, response.body); } // A function that converts a response body into a List<Photo>. List<Photo> parsePhotos(String responseBody) { final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>(); return parsed.map<Photo>((json) => Photo.fromJson(json)).toList(); } class Photo { final int id; final String title; final String url; final String descr; Photo({this.id, this.title, this.url, this.desc}); factory Photo.fromJson(Map<String, dynamic> json) { return Photo( // albumId: json['albumId'] as int, id: json['id'] as int, title: json['title'] as String, url: json['url'] as String, desc: json['desc'] as String, ); } } void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final appTitle = 'My Photo Sharing!'; return MaterialApp( title: appTitle, home: MyHomePage(title: appTitle), ); } } class MyHomePage extends StatelessWidget { final String title; MyHomePage({Key key, this.title}) : super(key: key); @override Widget build(BuildContext context) { … -
What would be the best architectural pattern to store user files in Django?
I am looking to make a Django-Rest web application that allows users to store files and folders, which they can view afterwards in my frontend (think: Dropbox, Google Drive, etc). I understand that Django has a built-in storage api, but it seems to me that I cannot use it because it only deals with file uploads (I am also looking to upload directories and subdirectories). This means that I would need to create a custom method to accomplish what I want. I am having trouble understanding how to deal with the folder structure that I should follow for this. I was thinking of creating individual folders for each user once they register to the platform. These folders would be named after the users uuid. For example: user: peter123 registers a uuid of uc3f-g239-h423-tx3y is assigned a folder named uc3f-g239-h423-tx3y is created in a common directory all files and folders that peter123 uploads are then stored in folder: uc3f-g239-h423-tx3y The same goes for all subsequent users, having their individual folder names represented by their uuid's. Structure would be something like this: common | |_____uc3f-g239-h423-tx3y | |____peter123.txt | |____peter123-subfolder | |_____peter123-subfile.csv | |_____du3y-dgp7-g9rq-23qp | |____bob123.txt | |____bob123.mp4 | |____bob123-subfolder | |_____bob123-subfile.mkv | … -
Adding a widget collapses form
I have a script like this: #User model about_text = models.TextField(max_length=1000, null=True, blank=True, validators=(MaxLengthValidator(1000),)) #forms.py class SettingsUpdateForm(forms.ModelForm): class Meta: model = User fields = ('about_text') labels = { 'about_text': '', } This works and gives a nice big field to write a text. Problem: If I add widgets = { 'about_text': forms.TextInput(attrs={'placeholder': 'Describe yourself!💯'}), } the field collapses to a singleline field. How do I keep the field big and have a placeholder? -
_generate_etree_functions() missing 1 required positional argument: '_iterparse'
I am using an old version of Django "1.9" and I have updated the file ElementsTree.py the last version was also not working, but now I am getting this error when I try to access the admin panel of Django Following is my file code File link Error Screenshort -
Initializing drf Serializer
I have two models: User and Employee. I want to return following json via drf: [ { 'admin': {}, 'employee': [{}, {}] }, { 'admin': {}, 'employee': [{}, {}] } ]. However, I don't understand how to initialize a TeamSerializer with data. What should I pass into TeamSerializer class Meta: model = User fields = [ "first_name", "last_name", "email", "hourly_rate", "role", ] class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = [ "first_name", "last_name", "email", "hourly_rate", "role", ] class TeamSerializer(serializers.Serializer): admin = AdminSerializer() employee = EmployeeSerializer() -
Get JSON as well as XML response using Django Restframework
I am working on creating an API, where I can return Json response as well as XML response based upon what format is needed. Settings.py file - INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'geoapp', 'rest_framework_xml', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] View.py file - from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET', 'POST', 'PUT']) def nominationurl(request): if request.method == 'GET': return Response("GET Remark") elif request.method == 'POST': dict1 = {} dict1['data'] = model.objects.values() dict1['format'] = request.data['format'] return Response(dict1) # {"format" : "json"} # {"format" : "xml"} Here I get normal Json response. But I want to decide type of response from POST request ie when {"format" : "json"} is posted I should get Json response and when {"format" : "xml"} is posted I should get XML response. I tried searching for the correct response but it is not working. Should I proceed? -
Why I cant use characters like () or [] in jinja sintax?
When I write something like these: {{ posts[0].title }} {% for post in posts[:2] %} I get an error! the error is like this. -
Error in Django: Using the URLconf defined in django_test.urls, Django-3 tried these URL patterns, in this order:
I've tried setting these URL's in this project, but I get a 404 when trying to access the registration.html file and the api-auth URL that is related to a REST API For reference: index = app django_test = site index/urls.py from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('', views.homepage, name="homepage"), path('/register', views.registration, name="registration"), path('api', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace="rest framework")), ] django_test/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('index.urls')), path('admin/', admin.site.urls) ] index/views.py from django.shortcuts import render def homepage(request): return render(request,"home/homepage.html") def registration(request): return render(request, 'home/registration.html') All of our HTML files are located in index/templates/home directory -
How to passing queryset inside static url in django template?
So, I have image in static folder, with the name of image same with username field that I have created. I want to show the photo for every posting based on the post that made by that user. I just thinking to pass the queryset inside static url like this: {% for post in data %} <img src="{% static 'project/image/{{ post.username }}.jpg' %}" alt="Profile" id="profile_image"> {% endfor %} But my image don't want to show up (error), and the terminal looks like this: [27/Feb/2021 15:43:14] "GET /static/project/image/%7B%7B%20post.username%20%7D%7D.jpg HTTP/1.1" 404 1758 Is there any way to do this? -
raise self.RelatedObjectDoesNotExist( Portal.models.logger.Student.RelatedObjectDoesNotExist: logger has no Student
I keep getting this error everytime I try to access the class assignment page. Below is the code of my project. Models.py class logger(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): username = models.OneToOneField(logger,on_delete=models.CASCADE,primary_key=True,related_name='Student') name=models.CharField(max_length=250) roll_no = models.CharField(max_length=50) email = models.EmailField(max_length=254) def __str__(self): return self.name class Meta: ordering = ['roll_no'] class Teacher(models.Model): username = models.OneToOneField(logger,on_delete=models.CASCADE,primary_key=True,related_name='Teacher') name = models.CharField(max_length=250) subject_name = models.CharField(max_length=250) email = models.EmailField(max_length=254) class_students = models.ManyToManyField(Student,through="StudentsInClass") def __str__(self): return self.name def get_absolute_url(self): return reverse('teacher_detail',kwargs={'pk':self.pk}) Views.py @login_required def class_assignment(request): student = request.user.Student assignment = SubmitAssignment.objects.filter(student=student) assignment_list = [x.submitted_assignment for x in assignment] return render(request,'class_assignment.html',{'student':student,'assignment_list':assignment_list}) class_assignment.html {% extends 'base.html' %} {% block content %} <div class="container"> <div class="jumbotron"> {% if student.student_assignment.count == 0 %} <h2>No assignments Yet</h2> {% else %} <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">Assignment Name</th> <th scope="col">Uploaded By</th> <th scope="col">Uploaded Date</th> <th scope="col">Download</th> <th scope="col">Status</th> </tr> </thead> <tbody> {% for assignment in student.student_assignment.all %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{ assignment.assignment_name }}</td> <td>{{ assignment.teacher }}</td> <td>{{ assignment.created_at }}</td> <td><a href="{{ assignment.assignment.url }}" class="btn btn-primary" target="_blank">Download</a></td> {% if assignment in assignment_list %} <td>Submitted</td> {% else %} <td><a href="{% url 'submit_assignment' id=assignment.id %}" class="btn btn-primary">Submit</a></td> {% endif %} </tr> {% endfor %} </tbody> </table> {% endif %} … -
Django test matching query does not exist
I'm new to Django. I am building an app that requires a lot of control over user access to various use and features. For this I created a model called 'UserType' that has some user groups as objects i.e. scanner, overwatch, lancer and admin. Another model, AssignedType, assigns users to one or more UserType. It has two fields. 'user' which is related to User model and 'user_type' which is related to UserType model. The file which controls access rights (rights.py) is as follows: from .models import User, UserType, AssignedType # Get all user types in the database as model objects scanner = UserType.objects.get(id=1) overwatch = UserType.objects.get(id=2) lancer = UserType.objects.get(id=3) admin = UserType.objects.get(id=4) # Rights of each type of user. Keys are the views and values are the user types allowed to access a particular view group_rights = { 'scanner':[scanner, admin], } # Function to determine whether the logged user may access a view. Returns True if allowed. False otherwise. def is_user_permitted(logged_user, view): # Get a list of users types assigned to the user assigned_types_objects = AssignedType.objects.all().filter(user=logged_user) assigned_types = [] for assigned_type in assigned_types_objects: assigned_types.append(assigned_type.user_type) # Get a list of users types permitted to access the view. view_rights = group_rights[view] # … -
Existing folder is not adding in GitHub
I am trying to Upload my Django project on GitHub and It is not uploading. Everything is working fine BUT error is showing at the End. The Error Total 318 (delta 73), reused 0 (delta 0), pack-reused 0 error: RPC failed; curl 56 OpenSSL SSL_read: Connection was reset, errno 10054 send-pack: unexpected disconnect while reading sideband packet fatal: the remote end hung up unexpectedly Done What i am trying I open git bash then type git init Then i type git add . then `git commit -m "first commit" , It all worked fine. and then git remote add origin <repository_url>, It also worked fine then i type git push origin master then it shows Total 318 (delta 73), reused 0 (delta 0), pack-reused 0 error: RPC failed; curl 56 OpenSSL SSL_read: Connection was reset, errno 10054 send-pack: unexpected disconnect while reading sideband packet fatal: the remote end hung up unexpectedly Done Then i checked into my repository and it is showing nothing. I dont' know what is the problem What have i tried I also tried git config --global http.postBuffer 524288000 in GitBash but nothing worked. I deleted my account too and created a new one BUT nothing worked. … -
Converting dataURI to file for upload via REST does not work but normal filefield upload works fine
I have implemented a solution that accepts a single file upload (image for profile) in a Django Rest Framework backend. This route api/people/id/upload_image. Only accepts a parameter with an image. and can be used via HTTP POST. When uploading via a fileinput field in eg. Postman, the default Django API or via browser fetch() in my Vue.js application is no problem. So it seems as long as it is a default form-upload field it is doing its job. But in my frond-end (vuejs 3) I am using an image-cropper. Users can upload an image and via the javascript cropper the image can be cropped. This is important for the UI because I need a square image. The cropper uses HTMLCanvasElement.toDataURL() as export format. And what seemed to be not that difficult gets me stuck for days now. I just can't find a way to convert and POST the cropped image in such a way that is accepted by the upload_image API backend. I am using Fetch() for sending this POST call. I am not a javascript expert so I get my knowledge via internet and I tried it in several ways; with first creating a BLOB from the dataURI, and … -
Django IntegrityError at /create_post/
When trying to create a create class-based view I get the IntegrityError listed above the full error is IntegrityError at /create_post/ null value in column "author_id" of relation "blog_post" violates not-null constraint DETAIL: Failing row contains (6, First, 2021-02-27 15:36:47.072327+00, Cosndfadfa, 2021-02-27 15:36:47.072447+00, null). I am not sure what I am doing wrong. Any help on this is greatly appreciated. Below are my views.py class CreateView(CreateView): model = Post template_name = "blog/post_form.html" fields = ["title", "content"] urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("about/", views.about, name="about"), path("blog/", views.BlogList.as_view(), name="blog-list"), path("create_post/", views.CreateView.as_view(), name="create"), ] my post model in models.py from django.db import models from django.conf import settings from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ["-created_on"] def __str__(self): return self.title and my post_form.py {%extends "blog/base.html"%} {% load crispy_forms_tags %} {%block content%} <div class="container"> <main class="form-signin"> <form method="POST"> {%csrf_token%} <h1 class="h3 mb-3 fw-normal">Create New Post </h1> {{form|crispy}} <button class="w-15 btn btn-lg btn-primary" type="submit">Create </button> </form> </main> </div> {%endblock content%} Any help on this is greatly appreciated. -
Get display value of CHOICES in python
Within django, I know that if you define a model with choices, you can print the value of the option to a template with the following Choices and field in models.py NAVBAR_COLOR = ( (0, "Dark"), (1, "Light"), ) navbarcolor = models.IntegerField(choices=NAVBAR_COLOR, default=1) template {{color.get_navbarcolor_display}} Is there a way to get the display value for the option within python for a given field? Thanks! -
Filter for > 10 entries in foreign key object
organizers = Organizer.objects.filter(events__isnull=False).distinct() for organizer in organizers: print("-----", organizer.name, "-----") events = organizer.events.all() for event in events: if not event.attendees.count() > 10: continue print(event.first()) You can see here I have three queries to return the first event that matches the criteria > 10 attendees. I wonder if there is a better way to combine this logic in one or two querysets instead. -
Django load text file into html file using jquery
I want to implement this example code from w3schools.com using Django. The code loads a text file into a html file using the jquery load() function. The code looks like this <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("#div1").load("demo_test.txt"); }); }); </script> </head> <body> <div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div> <button>Get External Content</button> </body> </html> My question is now, how do I store my text file such that the load function has access to it in my Django project? -
Django: get the id from on model to add it to another
I have 2 models I want to basicaly generate 2 database entries in 2 different models when only one is triggered. class Parent(models.Model): creation_date = models.DateTimeField(auto_now = True) entrya= models.CharField(max_length=50) rnum = models.CharField(max_length=50) entryb = models.CharField(max_length=50) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Child(models.Model): creationdate = models.DateTimeField(auto_now = True) rnum = models.ForeignKey(Parent, on_delete=models.CASCADE) amounta= models.DecimalField(max_digits=12, decimal_places=2) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Now when a form to make the parent is made, i automatically want a blank Child entry in the database Forms.py class RNumForm(forms.ModelForm): class Meta: model = Parent fields = ['entrya', 'rnum', 'entryb'] So next, here i want to make both database entries: Views.py @login_required def rnum(request): if request.user.is_authenticated: if request.method == "POST": addrnum = RNumForm(request.POST or None) if addrnum.is_valid(): addrnum.instance.user_id = request.user.id addrnum.save() rnum_new = addrnum.instance.rnum rnum_id_query = Parent.objects.filter(user=request.user, rnum = rnum_new).values("id") print(rnum_id_query) rnum_id = rnum_id_query.id print(rnum_id) Child.objects.create( amounta= "0", rnum = rnum_id, user_id = request.user.id, ) in my terminal i always get this printed out as an error <QuerySet [{'id': 1}]> {'id': 1} Cannot assign "{'id': 1}": "Child.rnum" must be a "Parent" instance. Does anybody have an idea or could anybody help please? Thanks a lot! -
Upload image in Django for specific user
I am trying to upload pic for specific user but nothing happened when i select image and upload it . it not store in db and not even in media folder setting.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' View.py def uploadPic(request): if request.method == 'POST' and 'SESSION_KEY' in request.session: form = Profile( user_id=request.session['SESSION_KEY'], profile_pic=ProfileForm(request.POST, request.FILES) ) form.save() return redirect('home') else: form = ProfileForm() return render(request, 'upload.html', { 'form': form }) Model.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) profile_pic = models.ImageField(null=True, blank=True, upload_to='image/') Form.py class ProfileForm(forms.ModelForm): class Meta: model = ProfileModel fields = ['profile_pic'] Template {% extends 'home.html'%} {% block content %} {%if user.is_authenticated%} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {% endif %} {% endblock %} -
Edit template Djangoms Blog post_list
please tell me how to redo the DjangoCMS blog template for the desired structure? I understand what needs to be edited post_list.html but there is no description of tags in the official documentation, what should I do? I need to output categories(Using input radio) and be able to choose to display articles of a certain category. Display the image (preview), title, and date. How do I do this? Unfortunately, there is very little about this in the documentation. Example of the desired structure blog -
Django how to identify not reister user by ID
Perhaps this is a stupid question, but I just can't figure it out. I have applications for voting for unauthorized users, now each user can vote one and the same pig an unlimited number of times, how to do this as a user ID in a numeric ID, which stores the user's answers to questions; one user can participate in any number of surveys getting the polls completed by the user with details on the answers (what is selected) by the unique user ID models.py class Poll(models.Model): question = models.TextField() option_one = models.CharField(max_length=50) option_two = models.CharField(max_length=50) option_three = models.CharField(max_length=50) option_one_count = models.IntegerField(default=0) option_two_count = models.IntegerField(default=0) option_three_count = models.IntegerField(default=0) active_from = models.DateTimeField(auto_now_add=True, null=True) active_for = models.IntegerField(default=0) def total(self): return self.option_one_count + self.option_two_count + self.option_three_count @property def is_active(self): return (timezone.now() - self.active_from).seconds*3600 < self.active_for views.py def vote(request, poll_id): poll = Poll.objects.get(pk=poll_id) if poll.is_active: print("poll active") else: print("not active") if request.method == 'POST': selected_option = request.POST['poll'] if selected_option == 'option1': poll.option_one_count += 1 elif selected_option == 'option2': poll.option_two_count += 1 elif selected_option == 'option3': poll.option_three_count += 1 else: return HttpResponse(400, 'Invalid form') poll.save() return redirect('results', poll.id) context = {'poll':poll} return render(request, 'poll/vote.html', context)