Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'stripeToken' error when attempting to submit payment form
I'm following an outdate django e-commerce course using django and stripe. The course is about 4 years old so a lot has changed with django and stripe, which has allowed me to do a ton of research on both. I'm at the end of the tutorial and have run into an issue while creating the checkout page and more importantly using stripe to 'Create Charge'. I am receiving the following error message: django.utils.datastructures.MultiValueDictKeyError django.utils.datastructures.MultiValueDictKeyError: 'stripeToken' I read in the documentation for Creating Charge which states token = request.POST['stripeToken'] # Using Flask is for Flask (I think), however when i remove ['stripeToken'], I receive this error message: stripe.error.InvalidRequestError stripe.error.InvalidRequestError: Request req_kikB88HKbEkq9W: Could not find payment information I need a way to pass Stripe the payment information when the form is submitted. Also, I came across this post but the publisher was receiving error message do to multiple forms view.py from django.conf import settings from django.contrib.auth.decorators import login_required from django.shortcuts import render import stripe stripe.api_key = settings.STRIPE_SECRET_KEY # Create your views here. @login_required def checkout(request): publish_key = settings.STRIPE_PUBLISHABLE_KEY if request.method == 'POST': token = request.POST['stripeToken'] stripe.Charge.create( amount=999, currency='usd', description='Example charge', source=token, statement_descriptor='Custom descriptor', ) context = {'publish_key': publish_key} template = 'checkout.html' return … -
overriding __getattr__ on model breaks django-model-utils InheritanceManager
I am using django-model-utils package and I am trying to override getattr on a model for which i am also defining a InheritanceManager on. I have multiple models inheriting from this same model and i am calling .select_subclasses() on the parent model to get a queryset of child models. The problem is that the InheritanceManager is doing a try/except on ObjectDoesNotExist exception while my getattr raises a AttributeError exception (which is the standard). This causes the queryset to fail since the AttributeError is not caught by the InheritanceManager. Any ideas on how i can resolve this. I don't think i want to raise ObjectDoesNotExist in my getattr method.. but am not sure what else to try. Thanks! -
space between paragraph missing after looping in a <div>?
Im trying to make it so that if my textfield has a {startformat}, it will make the following text look like code and with the change the background. But once it goes in and out of the , any space between paragraph goes missing, making everything one big text. <h2 class="article-title">{{ object.title }}</h2> <p class="article-content"> {% for line in object.content.splitlines %} {% if line == '{startformat}'%}<div class="card-header"><code class="text-dark"> {% elif line == '{stopformat}'%}</code></div> {% else %}{{line}} {% endif %}{% endfor %} </p> Output!!! Quo inani quando ea, mel an vide adversarium suscipiantur. Et dicunt eleifend splendide pro. Nibh animal dolorem vim ex, nec te agam referrentur. Usu admodum ocurreret ne. Quo inani quando ea, mel an vide adversarium suscipiantur. Et dicunt eleifend splendide pro. Nibh animal dolorem vim ex, nec te agam referrentur. Usu admodum ocurreret ne. Quo inani quando ea, mel an vide adversarium suscipiantur. Et dicunt eleifend splendide pro. Nibh animal dolorem vim ex, nec te agam referrentur. Usu admodum ocurreret ne. Quo inani quando ea, mel an vide adversarium suscipiantur. Et dicunt eleifend splendide pro. Nibh animal dolorem vim ex, nec te agam referrentur. Usu admodum ocurreret ne. Quo inani quando ea, mel an vide adversarium suscipiantur. … -
Add custom fields in Django admin for every model
I'm working on my personal website and wanted to handle both frontend and database translations (ie having everything in 2-3 languages). While there are already quite a few third-party apps for handling translation in the database, I thought it'd be both fun and interesting to build my own. I'm at the last step. So far, everything's been working fine. Here's a quick recap on how it works (skipping over a few things): I have a "translation" app in my django project It provides a few different tables, most notably : Language: list of available languages Item: equivalent to saying "This is the 'name' field for the instance 33 of the 'Job' model" Translation: a ManyToMany between Languages and Items. Basically all the translations for a given item. This app provides an abstract model called "Translation model" Every model from your regular apps that have fields to be translated must inherit from this model Through signals and FK relationship, the app then handles both the creation and deletion of entries in the Item and Translation tables (automatically) Ok so let's say we have a "Job" model that has 2 fields that must be translated: title and description. Now whenever I create … -
Limiting the queryset RelatedFields to only currently related objects
I am overriding the get_queryset function in serializers.PrimaryKeyRelatedField to something like this achieve what I described in the title: def get_queryset(self): queryset = self.queryset return queryset.filter(**{str(self.root.instance._meta.verbose_name_plural) : self.root.instance}) This feels like an extremely hacky way to achieve it. Is there a cleaner syntax for getting related objects given a queryset and a root instance? I want the function to be generic so I can use it elsewhere. Or is there a rest framework's recommended way of setting queryset? -
The requested URL / was not found on this server. (Django)
While deploying my Django project using apache2 following this tutorial: https://pythonprogramming.net/deploying-to-server-django-tutorial/ I am getting Not Found The requested URL / was not found on this server. /var/www/portfolio/portfolio/urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from main.views import blog_detail, project_detail urlpatterns = [ path('', include('main.urls')), path('admin/', admin.site.urls), path('tinymce/', include('tinymce.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) /etc/apache2/sites-available/portfolio.conf <VirtualHost *:80> ServerName myhostname ErrorLog ${APACHE_LOG_DIR}/portfolio-error.log CustomLog ${APACHE_LOG_DIR}/portfolio-access.log combined WSGIDaemonProcess portfolio processes=2 threads=25 python-path=/var/www/portfolio WSGIProcessGroup portfolio WSGIScriptAlias / /var/www/portfolio/portfolio/wsgi.py Alias /robots.txt /var/www/portfolio/static/robots.txt Alias /favicon.ico /var/www/portfolio/static/favicon.ico Alias /static/ /var/www/portfolio/static/ Alias /static/ /var/www/portfolio/media/ <Directory /var/www/portfolio/portfolio> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/portfolio/static> Require all granted </Directory> <Directory /var/www/portfolio/media> Require all granted </Directory> </VirtualHost> I've tried going to /admin and it still 404s -
Exception Type: MultiValueDictKeyError Exception Value: 'username'
I get this error: Exception Type: MultiValueDictKeyError Exception Value: 'username' in POST method in the form. This is the HTML code: <form action="login" method="POST" class="needs-validation" novalidate> {% csrf_token %} <div class="col-md-6 mb-3"> <label for="validationTooltip01">Username</label> <input type="text" class="form-control" id = "username" placeholder = "Username" name="username" required> <div class="valid-tooltip"> </div> </div> <div class="col-md-6 mb-3"> <label for="validationTooltip03">Password</label> <input type="password" class="form-control" id = "pwd" placeholder = "Password" name="pwd" required> <div class="invalid-tooltip"> </div> </div> <button class="btn btn-primary" type="submit">LOGIN</button> </form> and this views.py from django.contrib.auth.models import auth, User from django.http import HttpResponse from django.contrib import messages def login(request): if request.method == "POST": user=request.POST['username'] pwd=request.POST['pwd'] User=auth.authenticate(username=user, password= pwd) if user is not None: auth.login(request,User) return redirect("dashboard") else: messages.info(request, 'Invalid credentials') return redirect('') elif request.method == "GET": return render(request,'login.html') Even I change user=request.POST['username'] pwd=request.POST['pwd'] by user=request.GET['username'] pwd=request.GET['pwd'] there is no change. -
How to use annotate in query set to extract a count of type in a location?
I can't seem to properly use annotate to extract the information I need from my models. I have the follow .model structure: class ArtistWorkPlaceQuerySet(models.QuerySet): def with_related(self): return self.select_related('artist','work', 'place') class ArtistWorkPlaceManager(models.Manager): pass class PersonWorkPlace(models.Model): artist = models.ForeignKey(Artist, verbose_name=_('artist'), related_name='work', on_delete=models.CASCADE) work = models.ForeignKey(Work, verbose_name=_('work'), related_name='place', on_delete=models.CASCADE) place = models.ForeignKey(Place, verbose_name=_('place'), on_delete=models.CASCADE) objects = PersonWorkPlaceManager.from_queryset(PersonWorkPlaceQuerySet)() class Work(models.Model): piece_type = models.CharField(max_length=100, null=True, blank=True) //This is like paintings or sculptures class Artist(models.Model): name = models.CharField(max_length=100) class Place(models.Model): name = models.CharField(max_length=200, null=True, blank=True) Through this query I can get all of the work by this artist: works = PersonWorkPlace.objects.filter(person=self.kwargs['pk']) How do I go further and search for the number (a count) of works of the same the 'piece_type' at a particular place by the same artist? I would like to pass or extract from context for a particular view the following information: Artist A has 2 painting and 2 sculpture at Place A and 4 paintings at Place B 'context': { (place: 'Place A', painting: '2', sculpture: '2'), (place: 'Place B', painting: '4') } -
How to register new user with curl using djoser?
I am new to djoser and while following a tutorial, I tried to register a new user using the command : curl -X POST http://127.0.0.1:8000/api/users/ --data 'username=example%26password=mysecret' but unfortunately I am getting the output as : {"username":["This field is required."],"password":["This field is required."]} instead of: {"email":"","username":"example","id":1} my urls.py file urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^api/', include('djoser.urls')) ] my settings.py file REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.BasicAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', ] } -
Django Admin custom foreign key select box
I want to customize Django admin select box and show thumbnail in the select box next to the image title I have a class called Image and another class called News, that has a foreign key to the Image. Note: I use Django jet as admin template. class Image(models.Model): alternate = models.CharField( verbose_name=_('Alternate'), max_length=255, null=True, blank=True ) title = models.CharField( verbose_name=_('Title'), max_length=255, null=True, blank=True ) artist = models.ManyToManyField( 'Artist', verbose_name=_('Artist'), blank=True ) image = models.ImageField() def __str__(self): return "({}) {}".format(self.pk, self.title) class Meta: verbose_name = _('Image Attachment') verbose_name_plural = _('Image Attachments') @staticmethod def autocomplete_search_fields(): return 'title', class News(BaseModel): title = models.CharField( verbose_name=_('Title'), max_length=255, null=True, blank=True ) summery = RichTextField( verbose_name=_('Summery'), null=True, blank=True, ) main_image = models.ForeignKey( Image, verbose_name=_('Main Image'), on_delete=models.SET_NULL, null=True, blank=True, related_name='images' ) Now I want to show the thumbnail of the image in choices in Django admin when I want to add news. Now my select box look like this -
Custom filter in Django admin for calculated fields
# models.py class Author(models.Model): name = models.CharField(max_length=50) class Book(models.Model): title = models.CharField(max_length=50) created_time = models.DateTimeField(auto_now=False, auto_now_add=True) writer = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books') # admin.py @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super(AuthorAdmin, self).get_queryset(request) return qs.annotate(books_count=Count('books')) def books_count(self, inst): return inst.books_count list_display = ['author', 'books_count'] Now I have two columns in admin: Author and Books count. I need to add DateFieldListFilter, but for a calculated field (not for model field). For example, to have a possibility show created books count by each author for last_week, last_month, last_year, etc. -
Trouble Installing React as an App within Django
I am using this tutorial to install React for the front with an API built in Django. https://sweetcode.io/how-use-djang-react-ap/ My repository for this projects so far is here: https://github.com/AlexMercedCoder/DjangoReactCRM I am at the point in the tutorial where you install react by running "npm run dev" This is the error I get and no tinkering with the relative file page seems to fix it: > webpack --mode development ./frontend/src/components/index.jsx --output ./frontend/static/frontend/main.js Insufficient number of arguments or no entry found. Alternatively, run 'webpack(-cli) --help' for usage info. Hash: 097c83a63f327afef15a Version: webpack 4.39.3 Time: 80ms Built at: 09/07/2019 4:16:05 PM ERROR in Entry module not found: Error: Can't resolve './frontend/src/components/index.jsx' in 'C:\Users\alexm\projects\DjangoReactCRM\drcrm' npm ERR! code ELIFECYCLE npm ERR! errno 2 npm ERR! drcrm@1.0.0 dev: `webpack --mode development ./frontend/src/components/index.jsx --output ./frontend/static/frontend/main.js` npm ERR! Exit status 2 npm ERR! npm ERR! Failed at the drcrm@1.0.0 dev script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\alexm\AppData\Roaming\npm-cache\_logs\2019-09- 07T20_16_05_497Z-debug.log -
How to use Django-import-export ImportForm and ConfirmImportForm outside admin
I want to use django-import-export's forms to implement the import feature for regular users, so it needs to be outside the admin section. So far, all the implementations I have found are about a) extending the feature inside the admin or b) reimplementing the default views outside the admin. But since the default forms work perfectly I would like to subclass them as part of my project (outside admin) without reimplementing the whole view's logic, if such thing is even possible. So far I tried (foolishly, I'm afraid) to subclass the import_export.admin.ImportMixin as a class view to import a model Period with resource PeriodResource: # staging/views.py from django.views import generic from import_export.forms import ImportForm, ConfirmImportForm from import_export.admin import ImportMixin from .models import Period from .admin import PeriodResource class PeriodImportView(ImportMixin, generic.View): template_name = 'period/import.html' resource_class = PeriodResource def get_import_form(self): return ImportForm def get_confirm_import_form(self): return ConfirmImportForm def get_form_kwargs(self, form, *args, **kwargs): # pass on `author` to the kwargs for the custom confirm form if isinstance(form, ImportForm): if form.is_valid(): company = form.cleaned_data['company'] kwargs.update({'company': company.id}) return kwargs and then just show the forms in the template: # staging/templates/period/import.html {{ import_form }} {{ confirm_import_form }} and my urls.py looks like this: # staging/urls.py from django.urls … -
How start background periodic task with django-background-tasks
I want to create periodic task for check values in my SQLite file. I tried to create repeating task with django-background-tasks but it doesn't work. It works fine when I used python manage.py process_tasks in cmd. How start this task with start django and without use this command? I develop my web app on Windows 10. urls.py from django.contrib import admin from django.urls import path, include from client import tasks as task urlpatterns = [ path('admin/', admin.site.urls), path('', include('client.urls')), path('account/', include('account.urls')), ] task.check_groups(repeat=10, repeat_until=None) tasks.py from background_task import background from django.utils import timezone from client.models import StudyGroup, Account @background() def check_groups(): check_active_groups() check_inactive_groups() -
How to convert Django source installation to package like installation
OS : CentOS, Redhat New to Django and python, we basically built a monitoring tool using python and Django framework. Below is the project folder structure. |-- Makefile |-- monitor-pycodes `-- web |-- content |-- __init__.py |-- manage.py |-- monitor_templ | |-- __init__.py | |-- templates | |-- templatetags | |-- urls.py | `-- views.py |-- packmonitor.wsgi |-- settings.py `-- urls.py Didnt mentioned the certain folders content to simplify the view. We used Makefile to copy our codes to system folders as below All python codes in "monitor-pycodes" --> /usr/lib/python2.7/site-packages/packmonitor/ and compile it Django templates in "web" --> /var/www/packmonitor for web UI. scritps such as packmontior & packmonitord to --> /usr/bin When run make install inside the project directory, above copying process take place and application started. My employer doesnt want this tool to be install from source. How to convert this install from source to package installation ? Thanks, Mohan -
how to fix "unorderable types: NoneType() > float()" error in django
im trying to generate a pdf of a list of employees, everything was alright until i tried to make a rowspan that groupe all the employees that are in the same department, and then i got an error, form the view i send a 3 dimensional array, employees infos inside a list of departments i tried to get the size of the group from the view and send it in l2.6 and i tried to get it from l1|length <table style="border: 1px solid black;"> <tr style="border: 1px solid black;"> <th style="border: 1px solid black;"> Service</th> <th style="border: 1px solid black;"> Nom et prenom</th> <th style="border: 1px solid black;width: 160px;"> Conge 1</th> <th style="border: 1px solid black;width: 160px;"> Conge 2</th> <th style="border: 1px solid black;width: 160px;"> Conge 3</th> <th style="border: 1px solid black;width: 160px;"> Conge 4</th> <th style="border: 1px solid black;width: 180px;""> Total</th> </tr> {% for l1 in liste %} {% for l2 in l1 reversed %} <tr> {% if l2.6 != 0%} <td rowspan="{{l1|length}}" style="border: 1px solid black" > {{ l2.0 }} </td> {% endif %} <td style="border: 1px solid black" > {{ l2.0 }} </td> <td style="border: 1px solid black;"> {{ l2.1 }} </td> <td style="border: 1px solid black;"> … -
Docker django runs only if I specify the command
I am new to docker and I was trying to create an Image for my django application. I have created the image using the following Dockerfile FROM python:3.6-slim-buster WORKDIR /app COPY . /app RUN pip install -r Requirements.txt EXPOSE 8000 ENTRYPOINT ["python", "manage.py"] CMD ["runserver", '0.0.0.0:8000'] The problem is, when I run the image using docker run -p 8000:8000 I am unable to access the app in my localhost:8000 But if I run the container using the command docker run -p 8000:8000 runserver 0.0.0.0:8000 I can see my app in localhost:8000 -
How to update two models in one form in django?
Okay, so first of all the situation is not quite easy as in the title. So I want to create form which can create object based on Cycle model and update only one field in Post model (field in question is 'cycle_title'). What is more its isn't only one post where this post have to be updated but there are several of it (all post's titles are saved in Cycle.post). views class CycleCreateView(LoginRequiredMixin, BSModalCreateView): template_name = 'blog/cycle_form.html' form_class = CycleForm def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update(user=self.request.user) return kwargs def form_valid(self, form, **kwargs): form.instance.author = self.request.user return super().form_valid(form) def get_success_url(self): reverse_user = self.request.user return reverse('profile', kwargs={'username': reverse_user}) forms class CycleForm(BSModalForm): def __init__(self, *args, user=None, **kwargs): super().__init__(*args, **kwargs) if user is not None: self.fields['posts'].queryset = Post.objects.filter(author=user) class Meta: model = Cycle fields = ['title', 'description', 'posts'] widgets = { 'posts': forms.CheckboxSelectMultiple(), } models class Post(models.Model): title = models.CharField(max_length=100, unique=True) content = MDTextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) cycle_title = models.CharField(max_length=100, default='') class Cycle(models.Model): title = models.CharField(max_length=100, unique=True) description = models.TextField(max_length=500, default="Brak opisu") date_created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) posts = models.ManyToManyField(Post) I was thinking about a solution like this: for i in form.cleaned_data['posts']: post = Post.objects.get(title=form.cleaned_data['title'][i]) post.cycle_title = form.cleaned_data['title'] … -
Import error somehow connected with app_labels
Django==2.2.3 Python 3.7 I get this error: from yandex.models import YandexGoals ImportError: cannot import name 'YandexGoals' from 'yandex.models' (/home/michael/PycharmProjects/ads1/ads_manager/yandex/models.py) When I stop in my IDE at the event of the exception (namely, I stop at any exception) and evaluate the expression "from yandex.models import YandexGoals", I get this: RuntimeError: Model class yandex_campaigns.models.YandexCampaignCommonTemplate doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Well, the message differs. Let's investigate what we have: INSTALLED_APPS = [ ... 'yandex', 'yandex_campaigns', ] yandex.apps.py class YandexConfig(AppConfig): name = 'yandex' yandex_campaigns.apps.py class YandexCampaignsConfig(AppConfig): name = 'yandex_campaigns' To the best ob my ability, I can't see any flaw here. Could you give me a kick? -
An elegant way to send multiple url query string from different UI
I have a table page. It has page size selector, search input and pagination links at the end. When changing page size it should refresh whole page with new page size; When press enter in search input, it will submit the search string and refresh page; Based on the count of search results and page size, it will adjust pagination links. When clicking pagination link, it will refresh page, but we need to keep the current page_size and current search string and show them after refreshing page. This is a part of a Django project. Usually, I would put them together into a form, then every time the submit can carry them and send to backend. But I feel like, the page_size on the top, the pagination links on the bottom, I don't want to put a form to expand so far. Or, without a form(that's what I am doing now), I can write javascript for onChange event of selector, then it can get current search string and then refresh page (no need to save current page link as page_size going to change); then another javascript for pagination link to get current page_size and search string then send. In the … -
How can I trigger a function when a user registers in django?
I took over a django web app and am still relatively new to django. I want to trigger a function whenever a new user registers on the website. But there is no code in the project to process the user registration. It all seems to happen under the hood. So I don't know where could put such a function call. The web app uses django.contrib.auth. Additionally: How can I trigger a function when an account is activated? -
Tackling Dynamic Models/Data with Django
I'm about to start working on a Django project where my data is not going to be very structured, and am having some trouble on deciding how to approach storing it. The basic premise of my project is to create a database manager that abstracts away the SQL bits away from the user. Basically a user will create fields, and define their type. Then users will have the option to populate these fields with rows of data. For example, a user could create two fields: first would be name and the user could set it to be a text field, followed by age, and have that be an integer field. This would essentially create two columns: name and age. Up to this point I can visualize what my schema structure should look like. However, when it comes to having the user enter rows of data that correlates with these columns, I am not sure how to approach storage with this regard. Furthermore, I want users to have the option to add additional columns at any point. Any ideas on how I should tackle this problem? -
How to fix migration when upgrading from django-ldapdb 0.9.0 to django-ldapdb 1.3.0 (in debian buster)?
I ran into an issue when upgrading my web application from django-ldapdb 0.9.0 to 1.3.0 (because it is packaged in Debian Buster). It creates migrations that fail. It seems that django-ldapd enforce dn as a primary key for the models (see here, but I don't want to hack django-ldapdb nor can I avoid migrations in my app ), so I tried removing the existing primary key in the model, but that didn't work... Here is an example of one of the models creating buggy migrations (worked fine in 0.9.0) : class LdapServiceUserGroup(ldapdb.models.Model): """ Class for representing an LDAP userservice entry. Un group user de service coté ldap. Dans userservicegroupdn (voir dans settings_local.py) """ # LDAP meta-data base_dn = LDAP['base_userservicegroup_dn'] object_classes = ['groupOfNames'] # attributes name = ldapdb.models.fields.CharField( db_column='cn', max_length=200, ) members = ldapdb.models.fields.ListField( db_column='member', blank=True ) def __str__(self): return self.name So when running makemigrations it creates a migrations which set dn as a primary key. And then : File "/usr/lib/python3/dist-packages/MySQLdb/connections.py", line 292, in query _mysql.connection.query(self, query) django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server ver sion for the right syntax to use near ')' at line 1") (full error … -
If statement in django template
I have a if statement to test if the categorie of the file is audio and I want to show the html audio tag if it is true. I tried to remove the if statement juste to test the audio tag and it is working just fine. {% if medias.categorie_media == "Audio" %} <audio controls src="{{medias.fichier_media.url}}">Votre navigateur ne supporte pas la lecture audio, veuillez télécharger le fichier.</audio> {% endif %} The output is when it is an audio file it show nothing. I inspected the code in the browser and the audio line is not showing. -
Django Audio Player
I am working on a django music app and I have a model called Song. class Song(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) ... audiotrack = models.FileField(upload_to=upload_image_path) likes = models.ManyToManyField(settings.AUTH_USER_MODEL,blank=True,related_name='track_likes') It gets passed in the template as an object list. def list_view(request): songs = Song.objects.all() context = { 'tracks_list' : songs } return render(request,"musica/list.html",context) In the template, I for-loop through the objects and link them to the audio player. <audio id="player" src="{{ object.audiotrack.url }}"></audio> <button onclick="document.getElementById('player').play()"></button> And this is the problem. The buttons remain the same, and play always one and the same track. I have a like button already for the songs, which is a ManyToMany Field. class TrackLikeToggle(RedirectView): def get_redirect_url(self,*args,**kwargs): id = self.kwargs.get("id") obj = get_object_or_404(Song,id=id) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated(): if user in obj.likes.all(): obj.likes.remove(user) else: obj.likes.add(user) return url_ Do I need to make something similar for the play button? A OneToOne Field called playing which toggles the audio player? But how is this going to work in the template, considering the player link: <button onclick="document.getElementById('player').play()"></button> Thank you for any suggestions