Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to pass information between pages in Reactjs using navlink?
I am using a Django REST framework, storing data in a model. I am then using Reactjs to consume the API and make GET/POST requests. Inside the React frontend, I am using react-router-dom to navigate between pages. I want to be able to click on a specific link, but then also pass on information to the component towards which the link is routed. This is my index.js code import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import { BrowserRouter } from 'react-router-dom'; ReactDOM.render( <BrowserRouter> <App/> </BrowserRouter>, document.getElementById('root') ); This is my App.js code import './App.css'; import Container from '@material-ui/core/Container'; import Navigation from './Components/ToolBar' import Main from './Components/Main' function App() { return ( <> <Container maxWidth='lg' className="App"> <Navigation/> <Main/> </Container> </> ) } export default App; This is my Main.js code import { Switch, Route } from 'react-router-dom'; import Projects from './Projects'; import Tickets from './Tickets'; const Main = () => ( <Switch> <Route exact path='/projects' component={Projects}></Route> <Route exact path='/tickets' component={Tickets}></Route> </Switch> ); export default Main; This is my Toolbar.js code, which is used for navigating to different pages import { Button } from '@material-ui/core' import AppBar from '@material-ui/core/AppBar' import Toolbar … -
Parameterised decorator returning an error
I'm writing a decorator to check a certain attribute of a user. I will use this decorator over POST of GET methods of some class based APIs. The attribute is stored in the request.session["user_status']. def decorator_func(func): def wrapper_func(class_reference, request): status = request.session["user_status"] if status != value1 or status != value2: return Response(data="A dictionary") return func(class_reference, request) return wrapper_func Whenever the if condition is not satisfied and the func is accessed, it works as expected. But when the condition is satisfied and the Response() is returned, I'm getting following error: TypeError at "api path on which the decorator is applied" Object of type "custom user model of this project" is not JSON serializable I'm guessing due to not writing the decorator in the correct way I'm getting some error and when it is trying to return the error, it's also trying to return the current user object which is not JSON serializable. The user object is also stored in request.session["user"]. What am I doing wrong in this parameterized decorator function? -
How to add custom django admin site and urls without the prefix in every pattern?
I am trying to include the urls of my custom admin site of one of my apps in a Django project. I would like the path to be foo-admin/.... I managed to do so by including this prefix in all urlpatterns in the app's urls.py. However if I try to add the prefix to the project's urls.py and have only the suffixes in the app's urls, it breaks. It's something like this: This works: Project's urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('my_app.urls')), ] my_app/urls.py: urlpatterns = [ path('foo-admin/', my_app_admin_site.urls), path('foo-admin/foo/', views.some_view), path('foo-admin/foo/<slug>/', views.MyGenericView.as_view()), ] This doesn't work: Project's urls.py urlpatterns = [ path('admin/', admin.site.urls), path('foo-admin/', include('my_app.urls')), ] my_app/urls.py urlpatterns = [ path('', my_app_admin_site.urls), path('foo/', views.some_view), path('foo/bar/<slug>/', views.MyGenericView.as_view()), ] The error I'm encountering is: NoReverseMatch at /foo-admin/ Reverse for 'app_list' with keyword arguments '{'app_label': 'my_app'}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|app1|app2|django_mfa|axes)/$'] -
I want to have multiple forms in django on the same page
I am creating a mad libs application. for ppl to create new mad libs I have a field model. this is my models.py: class story(models.Model): Name = models.CharField(max_length=255) Text = models.TextField() def __str__(self): return self.Name class type_of_input(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class field(models.Model): Name = models.CharField(max_length=255,null=True) Tag = models.CharField(max_length=255) story = models.ForeignKey(story, on_delete=models.CASCADE) type = models.ForeignKey(type_of_input, on_delete=models.CASCADE, null = True) def __str__(self): return self.Tag People enter stories in a format like: "Once upon a time in {kingdom_name}" here kingdom name is a tag. I am parsing this story to get tags. I want a form on the next page with all tags having 2 attributes, name and type. how do I achieve this -
Django caching - Get is not pulling updated value while a function is in a loop
I have process in django which is streaming prices. When my application runs or certain events occur on my Django server I would like to save some variables from the database and store them in memory to use later them in my streaming process as a variable. Based on the value of this variable in the while loop every time my process tries to get the value stored in the cache. But my problems is that when I use cache.get() the update values is not pulling from the cache. The process is running by a Django Q cluster. Can someone help me what is the best way to implement in the running process to fetch the value from memory instead of continously quering the database for the same or updated value ? -
Creating a alert functionality in django wagtail
I am trying to create a alert section for a menu (similar to the menu on this page https://metageeky.github.io/mega-menu/responsive-header.html) *Each alert should have an effective date (date alert is “posted” live) and resolved date (date alert is “removed” live). Each alert will also have a maximum of one to two sentences of text describing situation. The number of active/current alerts will appear in parenthesis following the icon and ALERT link text. The icon and text are Dark Orange. When you hover over the icon and text, an underline appears. When users click on the link, they are taken to a page that lists all active alerts. At bottom of page, message displays “If you are experiencing an issue, please contact us at....” If there are no Alerts: The number of alerts in parenthesis following the icon and link text will not appear. Both the icon and alert text will be Primary Blue. When Users click on the link, they are taken to a secondary alerts page that displays a message that says “There are currently no active alerts. If you are experiencing an issue, please contact us at...” How would i achieve this? Thank you. -
Django: how to check if a field has been modified by the user?
I have a model in models.py; like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='static/images/account/avatar', default='/static/images/default-avatar.png') bio = models.CharField(max_length=300, blank=True, null=True) def __str__(self): return '@' + self.user.username in views.py i want to check if a filed (i mean avatar) from Profile model has changed or not in views.py: def editProfile(request): user = request.user.profile form = AuthorForm(instance=user) if request.method == 'POST': if ...: os.remove(request.user.profile.avatar.path) form = AuthorForm(request.POST, request.FILES, instance=user) if form.is_valid(): form.save() return redirect('dashboard') context = {'form': form} return render(request, 'account/edit.html', context) In fact, I want the default image (or any other photo) not to be deleted if the user does not change the avatar field. -
Inheritance in Python models
Having a little misunderstanding with the inheritance in Python. I have one parent class: class BaseClass(models.Model): email = models.EmailField(blank=True) phone = models.CharField(max_length=32, blank=True) name = models.CharField( max_length=64, blank=True, verbose_name=_(u'name') ) surname = models.CharField( max_length=64, blank=True, verbose_name=_(u'surname') ) class Meta: abstract = True def __str__(self): if self.name: return self.name elif self.email: return self.email else: return self.phone And I would like to use these all data in child class named SecondClass, but I dont know what I must to insert in body section of this class: class SecondClass(BaseClass): -
Get the object name in django admin
Hej! I want to have a category for turnovers in my admin area and in there I have a field with currency. It is a dropdown field with pre given currencies. My problem is, that there aren't the actual currencies shown rather their IDs. (like Object 123). Does anyone know how to solve this for an inline? # models.py class Currency(models.Model): code = models.CharField(max_length=3, unique=True) currency = models.CharField(max_length=150, unique=True) class Turnover(models.Model): currency = models.ForeignKey(Currency, on_delete=models.PROTECT) # admin.py class TurnoverInline(admin.TabularInline): model = Turnover extra = 1 classes = ["collapse"] class SomeAdmin(admin.ModelAdmin): form = SomeForm save_on_top = True inlines = [ TurnoverInline ] For a similar problem I created admin.ModelAdmins and integrated a code_str(self) and str(self) method in the model. But those aren't Inlines and in the SomeForm/SomeAdmin as fields/autocomplete_fields. -
Filter Django Models using lists of field parameters
I'd like to be able to pass any number of fields and values into a function to identify relevant rows: models.py class Player(models.Model): name = CharField(max_length = 50, default = 'Ronaldo') defender = BooleanField(default = False) midfielder = BooleanField(default = False) attacker = BooleanField(default = False) goalkeeper = BooleanField(default = False) views.py def find_player(**kwargs):#to be used in some view players = Player.objects.filters(kwargs).all() for player in players: #do something with player... find_player({defender:True, goalkeeper:True})#selects rows with players who defend and play in goal find_player({defender:True, attacker:False})#... find_player({defender:False}) What I'm trying to do above clearly doesn't work! I know that I could also use exec() to get what I want: def find_player(string_of_params): players = exec(Player.objects.filters(string_of_params).all()) for player in players: print(player) find_player('defender=True, goalkeeper=True')#prints rows with players who can defend and go in goal find_player('defender=True, attacker=False')#... find_player('defender=False'}) But I think there has to be a more natural way of unpacking the contents of a dictionary directly into filter(). Any guidance on this welcome. -
applying django forms to html template
i got a alrdy done html template , i'm trying to add register form to this template, idk hot to insert form fields. i tried to add {{ form.'fieldname' }} to input , but it doesn't effect. can't find any docs , sorry for silly question <section class="signup"> <div class="container"> <div class="signup-content"> <div class="signup-form"> <h2 class="form-title">Sign up</h2> <form method="POST" class="register-form" id="register-form" action=""> {% csrf_token %} <div class="form-group"> <label for="name"><i class="zmdi zmdi-account material-icons-name"></i></label> <input type="text" name="name" id="name" placeholder="Your Name"/> </div> <div class="form-group"> <label for="email"><i class="zmdi zmdi-email"></i></label> <input type="email" name="email" id="email" placeholder="Your Email"/> </div> <div class="form-group"> <label for="pass"><i class="zmdi zmdi-lock"></i></label> <input type="password" name="pass" id="pass" placeholder="Password"/> </div> <div class="form-group"> <label for="re-pass"><i class="zmdi zmdi-lock-outline"></i></label> <input type="password" name="re_pass" id="re_pass" placeholder="Repeat your password"/> </div> <div class="form-group form-button"> <input type="submit" name="signup" id="signup" class="form-submit" value="Register"/> </div> </form> -
django.core.exceptions.ImproperlyConfigured when trying to run a script with models
Okay so I have a Django project and I have model I want to get data from and do things with inside a python script. from django.db import models from metrics.models import Chart import django django.setup() p = Chart.objects.filter(dept_name="IT") print(p) anytime I try and run this I get the error django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I have tried setting a global variable for Django setting with the command set DJANGO_SETTINGS_MODULE=projectname.settings Any help would be greatly appreciated! Thanks in advance! -
Show only staff name in radio button and user can choose staff name, input price as well
I am trying to show only the staff lists on the radio button to the front end. Then the user can choose the staff name and then input the price and submit. So the system will take staff name (chosen by User) and price as input. So far I was trying to filter the staff name like staff = User.objects.filter(is_staff=True) but I am unable to pass the value to the front end. So I want to show a list of staff names and then the user chooses the staff name and inputs the price. As the views.py file is quite big, so I am sharing the gist file view.py Could anyone please help me out? Thank you -
how to send verification code to email and verify it in django rest framework
Please how can i send verification code to email before user's registration using django rest framework ? the idea is sending a code of 6 dgitis for example before transferring user to the registration's page, verify it if everything is okay then the user can continue the registration. Views.py class RegisterView(CreateAPIView): queryset = models.User.objects.all() serializer_class = RegisterSerializer Serializers.py class RegisterSerializer(serializers.ModelSerializer): photo = PhotoSerializer(read_only=True) announcements = AnnouncementSerializer(many=True, read_only=True) rating = SerializerMethodField('rating_avg') number_of_ratings = SerializerMethodField('rating_number') token = serializers.SerializerMethodField('get_token') class Meta: model = User fields = ['id', 'email', 'password','last_name', 'first_name', 'patronymic', 'type', 'date_joined', 'phone', 'photo', 'rating', 'number_of_ratings', 'announcements', 'token'] extra_kwargs ={ 'password':{'write_only':True} } def rating_avg(self, obj): rating = Review.objects.filter(user=obj.id).aggregate(Avg('rate')) return rating def rating_number(self, obj): number_of_ratings = Review.objects.filter(user=obj.id).count() return number_of_ratings def get_token(self, user): tokens = RefreshToken.for_user(user) refresh = text_type(tokens) access = text_type(tokens.access_token) token = { "refresh": refresh, "access": access } return token def create(self, validated_data): user = User( email=validated_data['email'] ) user.set_password(validated_data['password']) user.save() return user -
Django crontab automated setup issue in ubuntu development server
Am on a windows10 local development and has I can't use cron am testing in a development server. Am trying to setup django-crontab in a ubuntu 16.04 server and having a couple of issues. pip install django-crontab have it on my installed apps and requirements.txt INSTALLED_APPS = [ ... 'django_crontab', ... ] In the development.py settings that extend a base_settings.py have the cronjobs: Only trying to test a job that I already tested via command CRONJOBS = [ ('* * * * *', 'proregattaapi.cron.my_cron_job', '>> /var/log/django_cron_job.log'), ] then pushed to the server hosted by digital ocean. SSH into the server, activated the virtual environment and made the calls: python manage.py crontab add python manage.py crontab show python manage.py crontab run 3a55bd7591de350aa5d5d7be7758f17c in the above, got confirmation that the job was running with the crontab run command well but when I did: python manage.py runserver or left supervisior run the development server the job didn't start or logged anything Then I looked at: crontab -e and the output was: * * * * * /root/.python-virtual-environments/proregatta-django-development-new-virtualenv/bin/python /var/www/development.proregatta.com/manage.py crontab run 3a55bd7591de350aa5d5d7be7758f17c$ From my limited knowledge, I was thinking that with this crontab set activating the virtual env and running would be sufficient. Thank … -
Serializer.data gives old values, new ones visible in serializer in DRF
I wrote a custom perform_update(self, serializer) function in a ViewSet but I am having trouble updating the data. In the code below I see the data={} dictionary containing the old values (that are already in the DB) while the second print shows the data as it was posted. Can anyone please explain how I can use the updated data and why the old data shows up with serializer.data? (See the difference between 'source' and 'verwerking' values in the two prints) class RegisterlineViewSet(viewsets.ModelViewSet): queryset = Registerline.objects.all() serializer_class = RegisterlineSerializer permission_classes = [permissions.IsAuthenticated] ... def perform_update(self, serializer): print(serializer.data) print(serializer) Result: {'id': 4, 'external_reference': OrderedDict([('source', '7777777'), ('sourcekey', '77777'), ('last_updated', None)]), 'verwerking': '', 'applicatienaam': ... RegisterlineSerializer(<Registerline: @ [4]>, context={'request': <rest_framework.request.Request: PATCH '/api/registerline/4/'>, 'format': None, 'view': <core.views.RegisterlineViewSet object>}, data={'id': 4, 'external_reference': {'source': '7777gfhngtn777', 'sourcekey': '77777', 'last_updated': None}, 'verwerking': 'gnyghnj',... -
How to convert (and maybe optimize) the following raw query to Django Queryset
I have the following query: SELECT OBJ_DESC_ERRORS.description, OBJ_DESC_ERRORS.object, OBJ_DESC_ERRORS.count_errors, OBJ_ERRORS.count_total FROM (SELECT `metrics_event`.`description`, `metrics_event`.`object`, COUNT(`metrics_event`.`id`) AS `count_errors` FROM `metrics_event` INNER JOIN `metrics_session` ON (`metrics_event`.`session_id` = `metrics_session`.`id`) WHERE (`metrics_session`.`training_id` = 4 AND NOT (`metrics_session`.`completed_at` IS NULL) ) GROUP BY `metrics_event`.`description`, `metrics_event`.`object` ORDER BY `count_errors` DESC ) as OBJ_DESC_ERRORS JOIN (SELECT `metrics_event`.`object`, COUNT(`metrics_event`.`id`) AS `count_total` FROM `metrics_event` INNER JOIN `metrics_session` ON (`metrics_event`.`session_id` = `metrics_session`.`id`) WHERE (`metrics_session`.`training_id` = 4 AND NOT (`metrics_session`.`completed_at` IS NULL) ) GROUP BY `metrics_event`.`object` ORDER BY `count_total` DESC ) as OBJ_ERRORS ON OBJ_DESC_ERRORS.object = OBJ_ERRORS.object which produces the following result: As you can see I'm basically running the same query twice. The reason for that is that I need to have that count_errors broken down by each aggregation of object + description, but I also need the count_total to be only aggregated by object. This was the way I could think of. Now I'd like to: How to write this using Django Queryset language ( I get stuck at the join/subquery parts) If there's a way to optimize this query (performance or clarity or both) I hope I'm not cheating with 2 questions in 1. Felt like a duplicate to create an entire copy+paste question description for 2 different … -
Ajax code for the Add to Favorites button in Django
I want to create a button to add to favorites according to the image below View codes like this def product_favorites_user(request, product_id): product = Product.objects.get_by_id(product_id) user_favorites = get_object_or_404(User, id=request.user.id) if request.method == 'POST': if product in user_favorites.favorites.all(): user_favorites.favorites.remove(product) else: user_favorites.favorites.add(product) return redirect(product.get_absolut_url()) html code <ul class="gallery-options"> <li> <form name="favorites-form" method="post" action="{% url 'product-favorites-user' product.id %}"> {% csrf_token %} <button class="add-favorites"><i class="mdi mdi-heart"></i></button> <span class="tooltip-option">افزودن به علاقمندی</span> </form> </li> </ul> The code works properly and the product is added to favorites, but I'm not up to Ajax properly. I wanted to know what the code looks like. -
How do I run multiple sites on the same server using docker and nginx?
I'm trying to run two sites on django on the same server under different ip, an error occurs that the port is busy, I fixed the ports, but the site does not start. Tell me where is the error please? When I go to ip I get an error This site can’t be reached. I have two docker-compose files, and in each of them I run nginx, on the second it gives an error, please tell me how to configure it correctly. I heard there is an option with a common nginx file, but I don't understand how to implement it. Help me please. This is the second docker-compose file and its settings. I would be very grateful for your help .env #Django # Should be one of dev, prod MODE=prod PORT=8008 #postgres DB_NAME=xxx DB_USER=xxx DB_HOST=xxx DB_PASSWORD=xxxx DB_PORT=5432 POSTGRES_PASSWORD=mysecretpassword #WSGI WSGI_PORT=8008 WSGI_WORKERS=4 WSGI_LOG_LEVEL=debug # Celery CELERY_NUM_WORKERS=2 # Email EMAIL_HOST_USER=xxxx EMAIL_HOST_PASSWORD=xxxx docker-compose.yml version: '3' services: backend: build: ./ container_name: site_container restart: always command: ./commands/start_server.sh ports: - "${PORT}:${WSGI_PORT}" volumes: - ./src:/srv/project/src - ./commands:/srv/project/commands - static_content:/var/www/site env_file: - .env depends_on: - postgres postgres: image: postgres:12 volumes: - pg_data:/var/lib/postgresql/data env_file: - .env # environment: # - DJANGO_SETTINGS_MODULE=app.settings.${MODE} nginx: image: nginx:1.19 volumes: - ./nginx:/etc/nginx/conf.d - … -
Having Problems with redirects while using azure auth adfs module
So, I'm trying to build and app that the user logs in using azure, and am usind azure auth adfs for it, and authentication itself is working. The problem is I need my landing page (say localhost:port) to be non dependant in this authentication, or appear for all and just redirect me to login through a button or to the main app thru the login steps. I just can't figure out how to make the redirects that make this possible, can someone give some help, maybe direct me to some resources that shows how to do this while using the azure auth adfs, as I just came across solutions for the normal django authorization process. -
LoginForm django modale
I try to add on a popup(modale)who is on my header a login form based on the LoginForm fonction of django. But it do not work... I don't know what I didn't do correctly... When I use the LoginForm on a page like login.html il work but when I try on the popup page nothing. Here my page popup.html and the my page urls. Thaank you from django.urls import path from django.contrib.auth import views as auth_views from .forms import LoginForm from . import views app_name = 'account' urlpatterns = [ path('', auth_views.LoginView.as_view(template_name='shop/popup.html', redirect_authenticated_user=True, authentication_form=LoginForm), name='login'), ] <!-- Trigger/Open The Modal --> <button id="myBtn">Open Modal</button> <!-- The Modal --> <div id="myModal" class="modal"> <div class="modal-content"> <div class="modal-header"> <span class="close">&times;</span> <h2>Modal Header</h2> </div> <div class="modal-body"> {{ form }} {# <form>#} {# <div class="form-group col">#} {# <div class="col-xs-2">#} {# <label for="Email">Email address</label>#} {# <input type="email" class="form-control mb-6" id="Email"#} {# aria-describedby="emailHelp"#} {# placeholder="Enter email">#} {# </div>#} {# <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone#} {# else.</small>#} {##} {# <div class="col-xs-2">#} {##} {# <label for="exampleInputPassword1">Password</label>#} {# <input type="password" class="form-control mb-6" id="exampleInputPassword1"#} {# placeholder="Password">#} {# <div class="col-xs-2">#} {# </div>#} {# </div>#} {# </div>#} {# <button type="submit" class="btn btn-primary">Submit</button>#} {# </form>#} </div> <div class="modal-footer"> <h3>Modal … -
Google Search console seems unable to detect link to internal pages
My site Owly proposes a redesign of Wikipedia, and has potentially all Wikipedia’s pages in English. I use django i18 for internationalization. Google Search console shows that almost 90k pages are indexed, but the “link” report shows some unexpected data. In particular, only internal links to homepage are counted (60k more or less), but NO ONE of the links to internal pages are counted (es. to https://owly.wiki/Norway/). The same seems to be happening with external links. Has anyone idea of the reason? Has django internalization something to do with that? Thank you 🙏 -
Does the 'upload_to' callback in the FileField hit the db for related content?
I have an Attachment model with two ForeignKey fields and a get_attachment_path callback for the upload_to attribute.: def get_attachment_path(instance, filename): return f'{instance.owner.name}/{instance.chat.id}/{filename}' class Attachment(models.Model): owner = models.ForeignKey(..) chat = models.ForeignKey(..) file = models.FileField(upload_to=get_attachment_path, ...) This will make the get_attachment_path run: Attachment.objects.create(..., file=file) So, with the line above, will django hit the db twice (one for the .create and one another for the get_attachment_path)? Asking it because the get_attachment_path callback tries to access related data (instance.chat.id etc.). -
AlgoliaSearch: Sort items by score?
I've spent few days trying to figure out how can I sort items by a given configuration, for example we have a model that is called "Product". Product has "has_image" - boolean field, "rating" - decimal field. And I would like to sort the items in a way that: Only items with images should be in top also the second sort is rating, so the products should appear in desc order for the rating logic ("items that have the best rating"). I have created an index: @register(Product) class ProductIndex(AlgoliaIndex): custom_objectID = "pk" index_name = "Product" fields = ( "id", "title", "category_id", "category_ids", "slugified_attrs", "seller_id", "supplier_id", "rating_count", "has_image", "is_on_sale", "supplier_priority" ) settings = { "minWordSizefor1Typo": 4, "minWordSizefor2Typos": 8, "hitsPerPage": 20, "maxValuesPerFacet": 100, "version": 2, "attributesToRetrieve": None, "unretrievableAttributes": None, "optionalWords": "None", "attributesForFaceting": get_attributes_for_faceting(), "attributesToSnippet": None, "attributesToHighlight": None, "paginationLimitedTo": 1000, "attributeForDistinct": None, "exactOnSingleWordQuery": "attribute", "ranking": [ "typo", "geo", "words", "filters", "proximity", "attribute", "exact", "custom", ], "separatorsToIndex": "", "removeWordsIfNoResults": "none", "queryType": "prefixLast", "highlightPreTag": "<em>", "highlightPostTag": "</em>", "snippetEllipsisText": "", "alternativesAsExact": ["ignorePlurals", "singleWordSynonym"], "searchableAttributes": ["title"], "numericAttributesForFiltering": None, 'attributesForFaceting': [ 'filterOnly(has_image)', 'filterOnly(rating_count)', 'filterOnly(supplier_priority)', ], } And specified the attributesForFaceting for filters to work, but as I specify this search: params = { "hitsPerPage": settings.PRODUCTS_PER_PAGE, "optionalFilters": [ "rating_count<score=5000>", … -
How to build a vote option logic with two choices in Django
I have a Poller object/model that contains questions, each having two possible choices to vote for. Now I want to enable the user to vote for either of them. I thought to add two vote fields to the Poller model itself but then I wouldn't be able to figure out which user voted, right? That's why I decided to set up a Vote model to be able to link each vote to both a User and a Poller. However, this leads to my following two issues: I am not sure how to render the Vote form, since it contains two boolean fields only. My idea is to simply create two html divs containing the choice_fields of Poller model and trigger an ajax call as soon as a user clicks on one of the two choices to vote (so I wouldn't render the Vote Form at all) Doing so, I am not sure how to handle this logic in the view. My idea is to change the boolean field of the choice that was selected to True and the other to False (in case the users changes his vote from Foo to Bar). Vote Model and Form class Vote(models.Model): poller = …