Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to include telugu language in django forms
Model: class Application(models.Model): full_name = models.CharField(max_length=40) father_or_husband_name = models.CharField(max_length=20) nominee_name = models.CharField(max_length=20) date_of_birth = models.DateField() job = models.CharField(max_length=20) address = models.CharField(max_length=20) mobile_no = models.CharField(max_length=10) Forms: class ApplicationForm(forms.ModelForm): class Meta: model = Application fields = ('full_name', 'father_or_husband_name', 'nominee_name', 'date_of_birth', 'job', 'address', 'mobile_no') In my template the fields display as: Full Name: Father Or Husband Name: Nominee Name: Date Of Birth: Job: Address: Mobile No: I want these fields in my native language Telugu. -
Connecting to Heroku Postgres with Django
I am trying to migrate my Postgres database that I created via Heroku, so that I can a superuser for my Django project. Using heroku run python manage.py migrate Produces the following error in my heroku logs django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? I believe this is because the project cannot connect to the server, but I am not sure why. In my production settings.py, I have the following: from .base import * import dj_database_url ALLOWED_HOSTS = ['herokuappurl.herokuapp.com'] DATABASES = { 'default': { } } db_from_env = dj_database_url.config() print(db_from_env) DATABASES['default'].update(db_from_env) I printed the contents of db_from_env just to make sure that the credentials listed in the dictionary match what is in my heroku config. Can anyone point me in the right direction? Thank you. -
django aws s3 image resize on upload and access to various resized image
I would like to be able resize my uploaded image to various size categories: original medium (500kb) small (200kb) And save it to AWS S3. And later be able to access it. One strategy is to save it in filename_small.jpg, filename_medium.jpg, have a helper function to be able to append the _small, _medium to access those files. Im not sure how to save all the different files (resized) and then access it with the helper. https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/storage_backends.py class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = False https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py class Employee(models.Model): ... face_image = models.FileField(upload_to=upload_to('employee/face_image/'), blank=True, storage=MediaStorage()) https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py @api_view(['POST']) def update_employee_image(request): ... employee = Employee.objects.get(id = employee_id) employee.face_image = face_image_obj employee.save() I am using django-storages and S3Boto3Storage. My full working project is in the git links. -
Django: Trying to create a user score system
So instead of making this into a new app or actually add it to the User model I want to just calculate this in the view. So here are two lines of code that I've added to get the number of posts a user has created and then multiplying it by 10 (the value I'm giving to adding a post) in the view and then passing it into the template. However, I am getting an error. Not sure if I'm going about this in the best way, but heres what I have. Code the in the view: posts = UserPost.objects.filter(author=user) posts_count = posts.len() * 10 The error: AttributeError at /user/2/ 'QuerySet' object has no attribute 'len' I also tried with .count instead of .len() -
Automatically downloading PDF using Django running code on multiple ports
When a user uploads a PDF, it is modified using ReportLab and the modified PDF is automatically downloaded. Below is my code for processing the files and returning them. def process_report(request): # Handle file upload if request.method == 'POST': report_file = request.FILES.pop('file')[0] merged_pdf, namefinal = pdfAnalyzingFunction(report_file) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="{}"'.format(namefinal) response.write(merged_pdf.getvalue()) return response else: return HttpResponseBadRequest('Must be Post') I am using Django to render and return content. The above code worked and was able to download files automatically when I just had some simple HTML on a localhost:8000 port. However, after building a frontend on a different port, localhost:3000, I was able to successfully run and generate a modified PDF but it no longer downloaded automatically (with the PDF modifying code running on the localhost:8000 port still). On my localhost:3000 port network tab I can see the uploaded file, and am wondering why it is not downloading. Request URL: http://localhost:8000/process_report Request Method : POST Satus Code: 200 OK Host: localhost:8000 Origin: http://localhost:3000 Referer: http://localhost:3000/ Unclear as to why it appears my PDF is rendering, but not automatically downloading now. Is there something I need to know about generating a response object on one port and attempting to … -
Django admin: using inlines through a ManyToMany relationship
Consider the following models.py, where a Group contains multiple Persons who each have zero or more Phone numbers. In this particular case, Persons who share a Group will often share at least one Phone number, so a many-to-many relationship is used. class Group(models.Model): name = models.CharField(max_length=30) class Person(models.Model): group = models.ForeignKey(Group) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class Phone(models.Model): persons = models.ManyToManyField(Person) number = models.CharField(max_length=30) I would like to show these models in the Django admin, in a single view, as shown below. class PersonInline(admin.StackedInline): model = Person class PhoneInline(admin.StackedInline): model = Phone # also tried: Phone.persons.through @admin.register(Group) class GroupAdmin(admin.ModelAdmin): inlines = [PersonInline, PhoneInline] However, there is no foreign key between Group and Phone, so this raises a SystemCheckError (one of the following): <class 'myapp.admin.PhoneInline'>: (admin.E202) 'myapp.Phone' has no ForeignKey to 'myapp.Group'. <class 'myapp.admin.PhoneInline'>: (admin.E202) 'myapp.Phone_persons' has no ForeignKey to 'myapp.Group'. Is it possible to make this work through the Person model? The goal is for the Phone inline to show phone number records for all Persons in the Group (bonus: when adding a new Phone, the Person SelectMultiple widget will need to only show other Persons in the Group). I would prefer to avoid modifying any templates. A third-party … -
migrate database from Sqlite3 to Postgres = Django
I have a small app that I have build and I am planning on transfering it to a live environment. This app scales really quickly. I currently have Sqlite3 as the database stack I am using for my project. I wanted to know if it is smart for me to switch to PostgreSQL before I host my project in a live environment. My app is currently running through docker images and sqlite3 works find on docker, but I feel like later on when I am dealing with lots of requests, PostgreSQL would be better off for me. If it is a good idea to switch from sqlite3 to PostgreSQL, I know I have to do the following lines, but I am not sure what I have to change in the django settings python page...: python manage.py dumpdata > dump.json Change DB connection string in settings.py to POSTGRES python manage.py syncdb python manage.py loaddata data.json login to postgres db using psql - execute this to delete all the data in the content_types table truncate django_content_type RESTART IDENTITY CASCADE; python manage.py loaddata data.json So would the settings.py file look something like this compared to current setup: current: DATABASES = { 'default': { … -
getting checkbox value but it returned none in django templare
please help me a bit. I'm kind of stuck for a while now. Any advice would be nice. So, I want to pass a value from a checkbox to my view. Here my template that contains the checkbox. <form method="POST" action="{% url 'search:specs' %}"> {% csrf_token %} {% for page in all_page %} <div class="row"> <h1> {{ page.info }}</h1> <div class="well"> {% for item in page.searchitem_set.all %} <div class="list-group"> <input type="checkbox" id="items" name="compare" value="{{ item.id }}"> and this is my view def specs(request): compare_item = request.POST.get('compare') print(compare_item) #item1 = compare_item[1] item = get_object_or_404(SearchItem, id=compare_item) The print() command returns a None. -
the editable in django's field option
when i study the django model field, i see the "editable" in field option. says: if false,the field will not be disdplayed in the admin or any other ModelForm.They are also skipped during model validataion.Default is True. so,it means ,we can not see the value in django site? and form model can not use it ? and it will not check the value when we save it?(from the word, "They are also skipped during model validataion") Why we should use this "editable" attribute in django? or ,what is the situation should we use "editable"? i need a example ,which can guide me how to use the "editable" thanks very much. -
Django unicode has no attribute _meta
I'm a new to Python and Django! and working on django tutorial and somehow customizing the way to log in by using my own database. What I want is that a user only needs their email to login. However, when I log in my test website, I have ''unicode' object has no attribute '_meta' error. *views.py // login(request, email) is suspicious. def login_view(request): if request.method == "POST": form = LoginForm(request.POST) email = request.POST['email'] user = EmailAuthBackend.authenticate(email=email) if user is not None: login(request, email) return redirect('../mypage') else: return HttpResponse(email) else: form = LoginForm() return render(request, 'myapp/login.html', {'form': form}) *CustomBackend.py class EmailAuthBackend(ModelBackend): def authenticate(self,email=None): try: user = Customer.objects.get(email=email) return user except Customer.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except Customer.DoesNotExist: return None -
Django with celery : daemon issue
I got the following problem with theses packages : Celery 4.1.0 django-celery-beat==1.1.0 python 2.7 rabbitmq 3.6.14 Django 1.11.3 Steps to reproduce settings.py (only the part related to celery) from __future__ import absolute_import, unicode_literals # ^^^ The above is required if you want to import from the celery # library. If you don't have this then `from celery.schedules import` # becomes `proj.celery.schedules` in Python 2.x since it allows # for relative imports by default. # Celery settings # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. # http://docs.celeryproject.org/en/latest/userguide/configuration.html#new-lowercase-settings CELERY_beat_scheduler = 'django_celery_beat.schedulers:DatabaseScheduler' # use django_celery_beat instead CELERY_broker_url = 'amqp://oscar:oscar@localhost:5672/oscarRabbit' celery.py : from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oscar.settings') app = Celery('oscar') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() __init__.py: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task … -
Heroku No module named 'fcntl' when deploying locally
I'm trying to use Heroku to deploy a django project. when running >heroku local web in the cmd, it is returning [WARN] No ENV file found 23:33:05 web.1 | Traceback (most recent call last): 23:33:05 web.1 | File "C:\Python34\lib\runpy.py", line 171, in _run_module_as_main 23:33:05 web.1 | "__main__", mod_spec) 23:33:05 web.1 | File "C:\Python34\lib\runpy.py", line 86, in _run_code 23:33:05 web.1 | exec(code, run_globals) 23:33:05 web.1 | File "C:\Python34\Scripts\gunicorn.exe\__main__.py", line 5, in <module> 23:33:05 web.1 | File "C:\Python34\lib\site-packages\gunicorn\app\wsgiapp.py", line 10, in <module> 23:33:05 web.1 | from gunicorn.app.base import Application 23:33:05 web.1 | File "C:\Python34\lib\site-packages\gunicorn\app\base.py", line 12, in <module> 23:33:05 web.1 | from gunicorn import util 23:33:05 web.1 | File "C:\Python34\lib\site-packages\gunicorn\util.py", line 9, in <module> 23:33:05 web.1 | import fcntl 23:33:05 web.1 | ImportError: No module named 'fcntl' 23:33:05 web.1 Exited with exit code 1 python version - 3.4.0 django version - 1.8.0 anyone know the issue? Thank you. -
Django - POST information to Web App & Handle The Event
I recently purchased a Raspberry Pi to improve my coding skills. I have a server hosted on the Pi and I am building a small web app with Django 1.11. I have been searching for a way to POST information from a python program to the web app--and assign an event handler that is triggered whenever new information is posted. I have read that an easy method is to use the request library inside the python program to make POST requests. But how can I handle these POST requests in my Django app and how can I add an event-handler that is triggered whenever such a request is made? -
Retrieving a foreign key value
I am using Django Rest Framework to create a REST Api. My serializers: class ItemSerializer(serializers.ModelSerializer): #inherit from this class owner = serializers.ReadOnlyField(source='user.id') #owners = serializers.ReadOnlyField(source='owner') class Meta: model = Item #fields = ('id','name', 'owner', 'owners') fields = ('id','name', 'owner') class UserSerializer(serializers.ModelSerializer): items = serializers.PrimaryKeyRelatedField(many=True, queryset=Item.objects.all()) class Meta: model = User fields = ('id', 'username', 'items') The only model: class Item(models.Model): name = models.CharField(max_length=10) id = models.AutoField(primary_key=True) owner = models.ForeignKey('auth.User', related_name='items', on_delete=models.CASCADE) def __str__(self): return self.name Now if I GET the users: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 1, "username": "chuck", "items": [ 1, 2 ] } ] I receive all the items that this user has (by the way I could I get the name instead of the primary keys of the items ?). How would I go if I wanted to reverse that process and get all the owners of the objects ? Here's the response I have so far (the owners are missing) : HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 1, "name": "Vest" }, { "id": 2, "name": "Pants" } ] I have tried to add owners = serializers.ReadOnlyField(source='owner') as you … -
Using regular expressions in views.py Django?
I have a form in my Django app where one field is called url. The user can add a youtube url. On submit, I want to save only the video id. My views.py look like this: import re def video_new(request): if request.user.is_authenticated(): if request.method == "POST": form = VideoForm(request.POST) if form.is_valid(): video = form.save(commit=False) fullURL = video.url youtubeId = re.sub(r'\shttps://www.youtube.com/watch?v=\s', '',fullURL) video.url = youtubeId video.created_by = request.user video.save() return redirect('videos:video_detail', video_id=video.pk) else: form = VideoForm() else: #if user isn't logged in return redirect('login') return render(request, 'videos/video_edit.html', {'form': form}) When I output youtubeId in the console, I actually see the full Url. So I guess I'm not using re.sub correct. How to use it correctly ? -
How to get id from template on post
I want to save the comment id in 'comenatario_comentado' when the comment is commented. For that I need the comment id be the comentario_comentado id. The problem is that I do not know how to do it in the template. Look the structure below: models.py class Pregunta (models.Model): descripcion = models.CharField(max_length=150) autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE) fecha_pregunta = models.DateTimeField(auto_now_add=True) comentario_preguntado = models.ForeignKey(Comentario, null=True, blank=True, related_name="pregunta_set") def __str__(self): return (self.descripcion) views.py def ComentarioListar2 (request): aa=Puesto.objects.filter(nombre_puesto=request.user.nom_puesto).values_list('etiquetas') bb=Tags.objects.filter(id__in=aa) objects=Comentario.objects.filter(tag__in=bb).exclude(autor__id=request.user.id) form = preguntaform(request.POST or None) form.instance.autor=request.user if request.method == 'POST' and form.is_valid(): form.instance.comentario_preguntado=request.POST.get('a','') form.save() return render(request, 'home/comentario_listar.html', {'objects': objects, 'form': form}) forms.py class preguntaform(forms.ModelForm): class Meta: model=Pregunta fields = [ 'descripcion', ] labels = { 'descripcion': 'Descripción', } widgets = { 'descripcion':forms.TextInput(attrs={'class':'form-control'}), } template.html <form method="post"> {% csrf_token %} {{form.as_p}} <div class="col-md-8 col-md-offset-2"> <div class="form-group"> <button class="btn btn-primary" value="{{comentario.id}}" name="a" type="submit">Guardar</button> </div> </div></br> </form></br> How can I do to comentario id be comentario_comentado_id? thank you for your answer -
Django Restful api logger not logging
I've started using Django Restful API and one of the strangest problems I'm facing is the logging. my logger only logs when I restart the server. but doesn't log on any. my logging settings in the setting.py : LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR,'logs/debug.log'), }, 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'fedal': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, '': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } in my views.py I have the logger defined import logging logger = logging.getLogger('fedal') and in my Class ArtistList which gets called class ArtistList(generics.ListCreateAPIView): logger.debug("first logging") logger.info("info logger") queryset = Artist.objects.all() But every time I make a request to my Artist API I get the lost correctly but I don't see anything in the logs. Only when I restarted the Django server I see the logging. Can someone tell me why it's not logging? -
Handling a large number of requests that use an ML model
I am building a chat-bot where every message a user sends needs to be converted to a vector(for other ML related work). I am using a pre-trained Word2Vec model to do this. The Word2Vec model was created using the Gensim library and is saved to disk as a 600MB file and is being used in a Django/Python web-application. Every time a new message is received as an API request, a function loads the word2Vec model and uses that object to generate a vector of the message. I am worried that every time a new message is received, the application loads an instance of the Word2Vec model and this would cause a memory problem if there are too many requests coming at the same time(because there will be multiple instance of the Word2Vec model present in the RAM at that time). How do I handle the memory efficiently such that it does not use too much memory? -
Django Unit Tests doesn't run in Visual Studio Test Explorer
I'm trying to implement my Django (1.11.7, Python 3.6) unit testing in Visual Studio. When I run them in my terminal (python manage.py test) they run fine, while when executing from the VS Test Explorer it fails with an error saying: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I've read that newer Django versions require an explicit django.setup() to be called, so I've tried to add it both to setUpClass(cls) and to setUpTestData(cls). import django from datamodel.models import Engagement, BusinessUnit from django.contrib.auth.models import User from django.test import TestCase, Client class TestViewRPA(TestCase): @classmethod def setUpClass(cls): super(TestViewRPA, cls).setUpClass() django.setup() @classmethod def setUpTestData(cls): super(TestViewRPA, cls).setUpTestData() django.setup() User.objects.create_user('dummyuser') eng = Engagement.objects.create(name = 'Test Client', owner=User.objects.get(username='dummyuser')) businessunit = BusinessUnit.objects.create(name = 'Business Unit', engagement=eng) def test_get_industry_segment1(self): businessunit = BusinessUnit.objects.get(name = 'Business Unit') c = Client() response = c.get('/rpa/%d' % businessunit.id) self.assertContains(response, 'id":1,"businessunit_set":[{"id":1,', status_code=200) Result from executing from CLI ...>env\Scripts\python.exe manage.py test app Creating test database for alias 'default'... System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 3 tests in 0.028s OK Destroying test database for alias 'default'... Any ideas? Thanks in advance -
I'm trying to create an instance object of a Model in Django that was created by a ManyToManyField
There's a button in an html file that is inside a for loop: {% for activity in data%} <p class=" ">{{activity.title}}</p> <p class=" ">{{activity.description}}</p> <form method="POST" action=""> {% csrf_token %} <button type="submit" class="btn btn-primary" id="Register">Register </button> </form> {% endfor %} When this button is clicked, I need the user to be added as an attendee in this current activity. models.py: class Attendee(models.Model): student = models.ForeignKey(User, related_name="attendee") class Activity(models.Model): attendee = models.ManyToManyField(Attendee, related_name="attendees",null=True, blank=True) What shall I do to make this happen? I've tried this function in views.py but it doesnt work: def registerAttende(request): if request.method == "POST": attendee = Attendee.objects.create(student=request.user) Activity.objects.create(attendee=attendee) return render(request, 'dashboard.html') I also have this in urls.py rl(r'^$', authentication_views.registerAttende, name='register') -
excluding field in django form
i've been searching around for a way to exclude password in a form. i have then found exclude, however it does not seem to work at all. what am i doing wrong? forms.py class EditUser(UserChangeForm): class Meta: model = User exclude = ('password',) fields = ( 'username', 'email', ) template {% for field in form %} <div class="form-group"> <label>{{ field.label }}</label> {% render_field field class="form-control" placeholder=field.help_text value=user.email %} </div> {% endfor %} -
Getting 403 SignatureDoesNotMatch when uploading to Google Cloud Storage?
I am trying to upload audio files on the Client-Side directly to my Google Cloud Storage bucket, for the purpose of avoiding a server-side upload (which has file size limits). My Issue: I am getting a 403 SignatureDoesNotMatch error on upload. Here is the error from the response: <Error> <Code>SignatureDoesNotMatch</Code> <Message> The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method</Message> <StringToSign> PUT audio/mp3 1511112552 /bucketname/pathtofile/019%20-%20top%20cntndr%20V1.mp3 </StringToSign> </Error> I have created a signed url. It looks like this: https://storage.googleapis.com/google-testbucket/testdata.txt?GoogleAccessId= 1234567890123@developer.gserviceaccount.com&Expires=1331155464&Signature=BCl z9e4UA2MRRDX62TPd8sNpUCxVsqUDG3YGPWvPcwN%2BmWBPqwgUYcOSszCPlgWREeF7oPGowkeKk 7J4WApzkzxERdOQmAdrvshKSzUHg8Jqp1lw9tbiJfE2ExdOOIoJVmGLoDeAGnfzCd4fTsWcLbal9 sFpqXsQI8IQi1493mw%3D The signed url is built following the guidlines found in the Google Docs here https://cloud.google.com/storage/docs/access-control/create-signed-urls-program However, the client-side javascript portion of handling this signed url is very unclear in the documentation. Here is my python code to create and return the signed url. GOOGLE_SERVICE_CREDENTIALS = 'google-service-credentials.json' def get_signed_url(request): filename = request.GET.get('filename') expiration = request.GET.get('expiration') type = request.GET.get('type') signed_url = CloudStorageSignedURL( method='PUT', file_name=filename, expiration_m=expiration, content_type=type ) signed_url = signed_url.sign_url() return JsonResponse({ 'signed_url': signed_url }) class CloudStorageSignedURL(object): def __init__(self, method, file_name, expiration_m, content_type): self.HTTP_method = method self.content_type = 'content-type: ' + content_type self.expiration = int(expiration_m) self.file_name = file_name def sign_url(self): expiration_dt = datetime.utcnow() + timedelta(minutes=self.expiration) expiration = int(time.mktime( expiration_dt.timetuple() … -
Django and Rest Framework: How can I test a model write view without coupling the test to the model structure
I want to test a Django view that takes a JSON, deserializes it using the is_valid method of DRF serializers (which might alter some of the data e.g. by making string values lowercase), and then saves the validated data into a new model instance. Example: from .models import Foo from .serializers import FooSerializer @api_view(['POST']) def save_foo(request): foo_data = request.data s = FooSerializer(data=foo_data) if s.is_valid(): validated_foo_data = s.validated_data foo_instance = Foo.objects.create(**validated_foo_data) How can I test that this view saved all the data appropriately, what's an efficient, DRY way to test this view without coupling my test too much with the schema of the Foo model, or the validation functionality in FooSerializer? Essentially I want a test that checks that the data passed in the request gets validated and saved to the model, without having the test know about the peculiarities of the validation or the model. -
how to render to the same page when an onchange event occurs in django ajax
How to render to the same html page when an onchange event(dropdown) occurs in django. I'm able render to the same form when the event occurs, but the html page is not refreshed. Kindly suggest on it. -
Django - voting on multiple categories in the same page/form
I recently completed Django intro tutorial, I want to create a polls app where one can vote on multiple categories on the same page/form. Everything works properly, however when I click 'vote' (ie select option and submit form) the following error keeps showing: TypeError at /polls/results/ int() argument must be a string or a number, not 'QueryDict' code from my models.py: class Caty(models.Model): category_name = models.CharField(max_length=250) class Choice(models.Model): category = models.ForeignKey(Caty, on_delete=models.CASCADE) choice_text = models.CharField(max_length=250) votes = models.IntegerField(default=0) code from my views.py: from django.shortcuts import get_list_or_404, render from django.http import HttpResponse from models import Caty, Choice def index(request): caty_list = Caty.objects.all() context = {'caty_list': caty_list} return render(request, 'polls/index.html', context) def results(request): return render(request, 'polls/results.html') def vote(request): caty = get_list_or_404(Caty) for cat in caty: selected_choice = cat.choice_set.get(pk=request.GET) selected_choice.votes += 1 selected_choice.save() return HttpResponse('polls:results') I swapped get_object_or_404() in the tutorial with get_list_or_404() since I am expecting votes on multiple questions code from my index.html: {% if caty_list %} <form action="{% url 'polls:vote' %}" method="post"> {% for caty in caty_list %} {% csrf_token %} {{ caty }} <br /> <fieldset> {% for choice in caty.choice_set.all %} <input type="radio" name="{{ caty }}" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice …