Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Arbitrarily set position/order of ManyToMany field in django admin?
I have the below models: """ Child class Media (models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=128,unique=True) file = models.FileField() enabled = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name """ Parent class Gallery(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=128,unique=True) description = models.TextField(max_length=254,null=True) medias = models.ManyToManyField(Media,related_name='medias') enabled = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = "gallery" verbose_name_plural = "galleries" def __str__(self): return self.name I would like to be able to sort the child table by setting it in junction table; therefore not affecting the child table. I'm thinking of setting position field in junction table, is manually adding it in DB the only way of doing that? I'm fairly new to Django and I'm sorry in advance if this happens to be just a basic question. -
How to use Select2 in Django custom SimpleListFilter
I've created a custom SimpleListFilter class (code below) and managed to have the options be displayed as a select input. What I'd like to add is the functionality that Select2 offers, namely being able to search for options within the select input. Can anyone tell me how to achieve this? Custom SimpleListFilter class: class AnswerTreeKnowledgeCodeListFilter(admin.SimpleListFilter): template = 'admin/dropdown_filter.html' title = _('Kenniscode') parameter_name = "knowledge_code" def lookups(self, request, model_admin): return [(instance.pk, str(instance)) for instance in AnswerTreeRepository.filter_by_level(0)] def queryset(self, request, queryset): # Custom queryset filtering here dropdown_filter.html: (copied from source that I forgot, so I take no credit for this code) {% load i18n %} <script type="text/javascript">var go_from_select = function(opt) { window.location = window.location.pathname + opt };</script> <h3>{% blocktrans with title as filter_title %} By {{ filter_title }} {% endblocktrans %}</h3> <ul class="admin-filter-{{ title|cut:' ' }}"> {% if choices|slice:"4:" %} <li> <select class="form-control" style="width: 95%;margin-left: 2%;" onchange="go_from_select(this.options[this.selectedIndex].value)"> {% for choice in choices %} <option{% if choice.selected %} selected="selected"{% endif %} value="{{ choice.query_string|iriencode }}">{{ choice.display }}</option> {% endfor %} </select> </li> {% else %} {% for choice in choices %} <li{% if choice.selected %} class="selected"{% endif %}> <a href="{{ choice.query_string|iriencode }}">{{ choice.display }}</a></li> {% endfor %} {% endif %} </ul> -
Do you know Alternatives to PHPliteadmin or PHPAdminer? Create one with Django?
I'm struggling to find an Open Source Webinterface in Order to have a variety of options to interact with SQlite3 database. What I'm looking for is a webinterface, where I can have tables linked with keys to each other and a possibility to put SQL queries, that can output what I'm searching for in the tables. When it shows all the data it found with the queries I want to edit those right when it shows them to me - not by going back and searching the table where it is inside. I hope you understand what I'm trying to search. Phpliteadmin and adminer don't support it, do you know an alternative or a django example that goes in that direction that I'm searching for? Maybe I could program the code so that it could fullfill the needs. I thank you very much for your help, I really appreacciate it! -
Update Twilio CallStatus dynamically with Django template
I'm using Twilio to make outgoing and receive incoming voice calls from browser with Django, I'm trying to show user the callStatus dynamically. this is my view: @csrf_exempt def call(request): response = VoiceResponse() dial = response.dial(caller_id=settings.TWILIO_NUMBER, answer_on_bridge=True) if 'phoneNumber' in request.POST: dial.number(request.POST['phoneNumber'], status_callback_event='initiated ringing answered completed', status_callback='https://my-web-app/call-status', status_callback_method='POST') else: caller_number = request.POST.get('Caller') response = VoiceResponse() dial_incoming = response.dial(caller_id=caller_number) dial_incoming.client('agent') return HttpResponse( str(response), content_type='application/xml; charset=utf-8' ) I'm receiving the callStatus without any problems, I can print it doing: print(request.POST.get('CallStatus')) What is the best way to show user the callStatus dynamically? Javascript Websocket? Websocket using Django channels? -
Unable to deploy Django app in Heroku due to requirements.txt error
I am trying to deploy a django app I created to heroku. When i do git push heroku master an error shows remote: cp: cannot create regular file '/app/tmp/cache/.heroku/requirements.txt': No such file or directory. here is the full log: Enumerating objects: 35, done. Counting objects: 100% (35/35), done. Delta compression using up to 2 threads Compressing objects: 100% (32/32), done. Writing objects: 100% (35/35), 12.68 KiB | 405.00 KiB/s, done. Total 35 (delta 2), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: cp: cannot create regular file '/app/tmp/cache/.heroku/requirements.txt': No such file or directory remote: -----> Installing python-3.6.10 remote: -----> Installing pip remote: -----> Installing SQLite3 remote: Sqlite3 successfully installed. remote: -----> Installing requirements with pip remote: Collecting asgiref==3.2.7 remote: Downloading asgiref-3.2.7-py2.py3-none-any.whl (19 kB) remote: Collecting astroid==2.3.3 remote: Downloading astroid-2.3.3-py3-none-any.whl (205 kB) remote: Collecting colorama==0.4.3 remote: Downloading colorama-0.4.3-py2.py3-none-any.whl (15 kB) remote: Collecting dj-database-url==0.5.0 remote: Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) remote: Collecting Django==3.0.5 remote: Downloading Django-3.0.5-py3-none-any.whl (7.5 MB) remote: Collecting django-heroku==0.3.1 remote: Downloading django_heroku-0.3.1-py2.py3-none-any.whl (6.2 kB) remote: Collecting gunicorn==20.0.4 remote: Downloading gunicorn-20.0.4-py2.py3-none-any.whl (77 kB) remote: Collecting isort==4.3.21 remote: Downloading isort-4.3.21-py2.py3-none-any.whl (42 kB) remote: Collecting lazy-object-proxy==1.4.3 remote: Downloading lazy_object_proxy-1.4.3-cp36-cp36m-manylinux1_x86_64.whl (55 kB) remote: Collecting … -
Django - How do I filter profile by user group?
How do I filter profile by user group? So far I have this: class StaffManager(models.Manager): def get_queryset(self): return ?? # should filter user group by staff class Operator(models.Model): user = models.OneToOneField( User, to_field='id', primary_key=True, related_name='operator', on_delete=models.CASCADE) ... staffs = StaffManager() def group(self): return ", ".join(list(self.user.groups.values_list('name', flat=True))) -
Python, passing object in html not working [closed]
def index(request): dest1= Destination() dest1.name ='kathmandu' dest1.desc = 'Golden city in the world' dest1.img = 'destination_2.jpg' dest1.price= 2000 dest2 = Destination() dest2.name ='Pokhara' dest2.desc = 'Beautiful city in Nepal' dest2.img = 'destination_3.jpg' dest2.price= 2500 dest3 = Destination() dest3.name ='Biratnagar' dest3.desc = 'Old city in the world' dest3.img = 'destination_1.jpg' dest3.price= 1000 dests = [dest1, dest2, dest3] return render(request, 'index.html', {'dests': dests}) by doing this its not working data is not displaying in the index page but if I pass like return render(request, 'index.html', {'dest1': dest1, 'dest2': dest2,'dest3': dest3}) IF I DO THIS THAN IT SHOWS THE DATA IN THE OUTPUT.. WHAT IS WRONG AS THE YOUTUBER WHO TEACHES IN HIS VIDEO IT SHOW IT WORKED IN THE FIRST ONE. CAN ANYONE HELP ME EXPLAINING THIS PLEASE -
Updating in Pipenv
I have a problem regarding pipenv. Maybe it is only my understanding, but we will see. I have a project that uses python 3.7 and Django 2.1. Now the latest version of Django is 3.0.5. I now want to update my Django version, but I have no idea how. pipenv update does nothing it only tells me that my requirements are already met. Even uninstalling Django an reinstalling it, does not update the version. I have no idea, how to do this. Thanks for the help. -
What is the proper way to write permission_required in a view in django?
I am trying to implement a web app in django where I have a class based view that inherits from PermissionRequiredMixin and generics.View. Here is an example model: class SomeModel(models.Model): # Here I will put some model attributes class Meta: permissions = ( ('some_permission', 'Can do some job'), ) Until now I am not confused yet. However, when I am trying to write the view, I am confused. I read some Stack Overflow questions and also the django documentation, but I did not understand well because they are writing something like this: class MyView(PermissionRequiredMixin, View) permission_required = ('polls.can_open', 'polls.can_edit') I tried to figure out what to write in my case, and I ended up in writing this: class SomeView(PermissionRequiredMixin, View): permission_denied_message = 'You don\'t have permission' permission_required = 'app_name.some_permission' What made me in doubt is that PyCharm did not auto-complete when I wrote the last line which is: permission_required = 'app_name.some_permission'. Also, I am not sure whether django will know which permission that I am talking about here. Did I understand how to do the job? or I am wrong? Should I write it like this: permission_required = 'app_name.SomeModel.some_permission'? -
OperationalError at /admin/account/profile/no such table: account_profile
OperationalError at /admin/account/profile/no such table: account_profile After adding «Profile» to your UserModel u can see this Error. I don’t know why, but Django doesn’t create new table to your model. This is my models.py: from django.db import models from django.apps import AppConfig from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class UserConfig(AppConfig): name = 'users' class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) @receiver(post_save, sender = User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user = instance) @receiver(post_save, sender = User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() All, that u need: download «DB Browser for SQLite» and: Copy your ‘db.sqlite3’ to different Folder. Delete your ‘db.sqlite3’. Run ‘python3 manage.py make migrations’, then ‘python3 manage.py migrate’. Open your new ‘db.sqlite3’ in «DB Browser for SQLite» and find table ‘account_profile’ Then do like 1st image. U should export ‘account-profile’ table to CSV file. Delete your new ‘db.sqlite3’ and return you old ‘db.sqlite3’ Open your DB in «DB Browser for SQLite», then «File—>Import—>Tables from file CSV..» and choose ‘account_profile.csv’ Then U will see, that in this table u should change columns ‘field1’ to ‘id’ and ‘field2’ to ‘user_id’. I did it on second and third images. Last, what should u … -
Django rename column when multiple tables are joined
I have this class in models.py: class Customer(models.Model): code = models.CharField(unique=True, max_length=10) user = models.OneToOneField(User, on_delete=models.PROTECT) phone = models.CharField(max_length=20) address = models.TextField(blank=True) balance = models.PositiveIntegerField(default=20000) The Customer has one to one relationship with User class. The User class is the default User class in Django: from django.contrib.auth.models import User I want to return result like this: "customers": [ { "code": a1, "username": "arashb91", "email": "arash@example.com", "phone": "111111", "address": "somewhere", "balance": 20000 }, but when I use this code: result = Customer.objects.all().values("code", 'user__username', 'user__email', "phone", "address", "balance") my result will be like this: "customers": { "code": a1, "user__username": "arashb91", "user__email": "arash@example.com", "phone": "111111", "address": "somewhere", "balance": 20000 }, I can rename fields by F method: result = Customer.objects.all().values("code", username=F('user__username'), email=F('user__email'), "phone", "address", "balance") But I get this error on "phone", "address","balance": Positional argument after keyword argument "code" is ok because it is before F methods. Order in results are important for me. I can't use this code either (F for other fields): result = Customer.objects.all().values("code", username=F('user__username'), email=F('user__email'), phone=F("phone")) because I get this error: The annotation 'phone' conflicts with a field on the model. I don't want my result be like this: othertable__field for solving my problem I used a python code … -
How to speed up loading lot of images in django templates?
I want to speed up the process of loading images in django templates. Now, i'm in a situation that the page will "GET" all the images and then render the page. part of index.html: {% extends 'base.html' %} {% load thumbnail %} {% block content %} {% for new in news_list %} <div class="card"> {% thumbnail new.image "250x250" as im %} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"> {% endthumbnail %} </div> {% endfor %} {% endblock %} part of view.py from .models import News def home(request): news_list = News.objects.all() return render(request, 'index.html', news_list) i used chrome "F12" to see what is happened. It takes so long for 'GET' all images. I think it's not the issue of getting a large models. Is there another way to display some images in templates instead of get all the images? Thankyou so much. -
how to change background color with tags?
i have built a campaign app that shows some campaign just like blog posts. each campaign has a tag. it is either active or deactive. i used django taggit for the tags. i want the active posts to have a green background color and deactive posts with a red background. please help me with the code and THANKS! this is my campaign model: class Campaign(models.Model): objects = jmodels.jManager() name = models.CharField(max_length=200) slogan = models.CharField(max_length=200) summary = models.TextField(max_length=500) tags = TaggableManager() slug = models.SlugField(unique=True, max_length=100) -
How to redirect from one question to another having same forignkey (quiz name)
I m building quiz app I have 3 models ( Quiz, Question,Answers) Question foreign key with Quiz,and Answee foreign key with Questions. I m successful in showing each question on separate page according to their pk. But to redirect from one question to another until last question -
making duplicate entries without ids using django
I'm making a django dashboard where the users can upload their experience certificates. The problem is the certification section sends duplicate entries to the django view with empty ids and the logic in the views make duplicate entries in thedatabase. The problem I found that the form is sending duplicate entris without the ids. certificate.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for c in cert %} <div class="form-body"> <div class="row"> <div class="col-md-12"> <div data-role="dynamic-fields"> <div class="form-content"> <input type="text" name="id" value="{{c.id}}"> <div class = "row"> <div class="col-md-6"> <div class="form-group"> <label>Month</label> <input type="text" class="form-control" id="field-value" name = "month" value = "{{c.month}}"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label>Year</label> <input type="text" class="form-control" id="field-value" name = "year" value = "{{c.year}}"> </div> </div> </div> <div class="col-md-12"> <div class="form-group"> <label>Company</label> <select class="form-control" id="field-value" name = "company"> {% if c.company %} <option value = "{{c.company}}">{{c.company}}</option> {% endif %} <option value="Microsoft">Microsoft</option> <option value="TEDx">TEDx</option> <option value="Business Standard">Business Standard</option> <option value="EF Standard English Test">EF Standard English Test</option> <option value="Open2Study">Open2Study</option> <option value="eMarketing Institute">eMarketing Institute</option> <option value="Amazon">Amazon</option> <option value="Airbnb">Airbnb</option> <option value="Adobe">Adobe</option> <option value="Paypal">Paypal</option> <option value="Intel">Intel</option> <option value="eBay">eBay</option> <option value="Beats">Beats</option> </select> </div> </div> <div class="col-md-12"> <div class="form-group"> <label>Title</label> <input type="text" class="form-control" id="field-value" name = "title" value="{{c.title}}"> </div> </div> <div class="col-md-12"> <div class="form-group"> … -
While running on Server i am getting HTML code on my browser
When i am running my Django project on local server. It is returning whole html code on webpage. Like after executing command python manage.py runserver and copy and pasting url on browser i am getting whole HTML file code instead element i have used. My Html file {% extends "wfhApp/base.html" %} {% block body_block %} <div class="jumbotron"> {% if registered %} <h1>Thank you for registration</h1> {% else %} <h1>Register here!</h1> <h3>Fill out the form:</h3> <form enctype="multipart/form-data" method="post"> {% csrf_token %} {{ user_form.as_p }} <input type="submit" name="" value="Register"> </form> {% endif %} </div> {% endblock %} My views.py from django.shortcuts import render from wfhApp.forms import UserForm def register(request): registered = False if request.method == 'POST': user_form = UserForm(data = request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() registered = True else: print(user_form.errors) else: user_form = UserForm return render(request, 'wfhApp/registration.html', {'user_form': user_form}, {'registered': registered}) Above is from template inheritance. -
Invalid HTTP_HOST header: '0.0.0.0:8000'. You may need to add '0.0.0.0' to ALLOWED_HOSTS
Django does not seem to find my host 0.0.0.0 I have already added "0.0.0.0" to my ALLOWED_HOSTS. In fact, if I print(ALLOWED_HOSTS) I get ['localhost', '127.0.0.1', '0.0.0.0', '[::1]']. I am working in docker. Is there anything I am overlooking? .env.dev DEBUG=1 SECRET_KEY=foo DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 0.0.0.0 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=xxxx SQL_USER=xxxx SQL_PASSWORD=xxxx SQL_HOST=db SQL_PORT=5432 DATABASE=postgres env_settings.py import os # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! # DEBUG = True DEBUG = int(os.environ.get("DEBUG", default=0)) ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ") # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) settings.py from core.env_settings import * print(ALLOWED_HOSTS) """ print(ALLOWED_HOSTS) returns ['localhost', '127.0.0.1', '0.0.0.0', '[::1]'] """ NB: I have carefully reviewed all similar questions posted here and there's none with this specific problem. -
access media root in server from local django
How could I make media root to access path in server when I work local Django ? path I want to access in sever: /var/test/ this is my local media root and media url: MEDIA_ROOT = '/home/test/' MEDIA_URL = '/media/' -
Accept customized input and customized output using Django Rest Framework
I am getting this part input and output successfully & documentation is also available for this type of problems input { "someid:"1" "lecture_id": 1, "subject_name": "English", "teacher_id": 1, "teacher_name": "Cirillo Kierans", "room": "Room A", "schedule": "1534567899" } output posting--> { "id:1, "someid" :1 "lecture_id": 1, "subject_name": "English", "teacher_id": 1, "teacher_name": "Cirillo Kierans", "room": "Room A", "schedule": "1534567899", } but my data is not coming like above format and i need to get post response not like above , i am expecting this input and { "someid:"1" "lectures": [{ "lecture_id": 1, "subject_name": "English", "teacher_id": 1, "teacher_name": "Cirillo Kierans", "room": "Room A", "schedule": "1534567899" }] } output { "lectures": [{ "id:1, "lecture_id": 1, "subject_name": "English", "teacher_id": 1, "teacher_name": "Cirillo Kierans", "room": "Room A", "schedule": "1534567899", "someid" :1 }] } I have succeeded in getting the listing of data by overriding def list this function serializers--> class LecturesSerializer(serializers.ModelSerializer): schedule_timestamp=serializers.IntegerField() class Meta: model=Lectures fields = ('id','lecture_id','schedule_timestamp','subject_name','teacher_id','teacher_name','room') def validate(self, attrs): travel_date = Lectures.to_date_time(attrs.pop('schedule_timestamp')) attrs.update({'schedule_date': travel_date}) attrs = super().validate(attrs) return attrs def to_representation(self, instance): data = super(LecturesSerializer, self).to_representation(instance) result_data={} result_data["lectures"]=data return result_data views--> class LecturesViewSet(viewsets.ModelViewSet): queryset = Lectures.objects.all() def get_serializer_class(self): return LecturesSerializer def list(self, request, *args, **kwargs): self.object_list = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(self.object_list, many=True) return Response({'lectures': … -
Getting AttributeError for body tag in Json parsing Python
Getting this error when parsing data AttributeError: 'str' object has no attribute 'body' Generating data json like this data = { 'params': { 'content': { 'mail': self.email_address } } } And parsing that data like this param = json.loads(request.body) content = param['params']['content'] mail = content['mail'] How to create Data properly which I can get in response.body? -
save serial number generated after form submission and displayed in django database?
I have created the model as class Personal_Detail(models.Model): message=models.CharField(max_length=100,blank=True, null=True) def __str__(self): return self.beneficiary_aadhaar_name and views as from django.contrib import messages import datetime import random @login_required def personal_detail(request): now=datetime.datetime.now() messages.success(request,now.strftime("SKPMMVY%Y%m%d%H%M%S")+str(random.randint(0,99))+str(":\tYour form has been submitted successfully")) beneficiary_adhaar_name=request.POST.get('beneficiary_adhaar_name') apply_online = Personal_Detail(beneficiary_adhaar_name=beneficiary_adhaar_name) apply_online.save() return render(request,'users/applyonline.html') I don't know how can i do the same for messages so that the displayed serial number after form submission will also get saved in the database.(for messages.success i don't know how to proceed like other cases) -
Django form for entering user id and product id
So, There's a button on my products results page. It's function is supposed to put the user id(request.user.id) and product id(request.product.id) (which is in the html) into a junction table between users and product tables. I've tried the code below. I'm not getting any errors but it doesn't save to the database. I don't want it to redirect to other page so the target is an iframe models.py class UserProductTracking(models.Model): id = models.AutoField(primary_key=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) class Meta: verbose_name_plural = "Trackings" def __str__(self): return str(self.product) forms.py class TrackingForm(forms.ModelForm): class Meta: model = UserProductTracking widgets = {'any_field': HiddenInput(),} exclude = {'id'} views.py def result(request): form = TrackingForm(request.POST) if request.method == "GET": rawquery = request.GET.get('q') #gets the product name to search from a form Product_set = Product.objects.filter(name__icontains=rawquery).distinct() #get all products with name ccontainingthe search term 'q' products = [] # create a blank set for product in Product_set: # for every item in Product_set price = Scan.objects.filter(product=product.id).first() # get price price_max = Scan.objects.filter(product=product.id).aggregate(Max('price')) price_min = Scan.objects.filter(product=product.id).aggregate(Min('price')) products.append({ #append adds to an existing list 'name': product.name, #context name = name column in product table 'store_name': product.store_name, # '' 'image_link': product.image_link, 'id': product.id, 'price': price.price, #'' 'price_max': … -
How to display no record using ListView in Django?
I'm using ListView to display objects of model but i want when there is no object in model so I display No records or products. What I need to do write a new function for it or there is any built-in function in ListView for this purpose. views.py class StockView(ListView): template_name = 'stock/stock.html' model = Product paginate_by = 3 -
Django ValueError for deleted fields when running migrations
My models.py file is as follows: from django.db import models from django.utils import timezone from random import randint # Create your models here. class File(models.Model): fileName = models.CharField(max_length = 30) description = models.CharField(max_length = 100) dateUploaded = models.DateTimeField(default = timezone.now) doc = models.FileField(default = None) serial = models.CharField(max_length = 6, default = randint(100000000, 999999999), unique = True) id = models.AutoField(primary_key=True) I used to have code = models.CharField(default = 'A13S34', max_length = 6, unique = True but it kept giving the error ValueError: Field 'code' expected a number but got '236E96'. Thus, I replaced it with the serial field. However, now when I try to makemigrations and migrate, I get the same error ValueError: Field 'code' expected a number but got '236E96'. What can I do when I no longer even have the code field? -
Action attribute in html form tag is not sending the data in django
I want to send song.id from each song in an album model but every time I send it, I get A KeyError This is what I wrote in details.html {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <form action="{% url 'music:favorite' album.id %}"> {% csrf_token %} {% for song in album.song_set.all %} <input type="radio" id="song{{ song.id }}" name="song" value="{{ song.id }}"> <label for="song{{ song.id }}"> {{ song.song_title }} {% if song.is_favorite %} <img src="https://png.pngtree.com/png-vector/20190726/ourmid/pngtree-cute-light-star-with-black-frame-png-image_1633374.jpg"> {% endif %} </label> <br> {% endfor %} <input type="submit" value="Favorite"> </form> This is my views.py def favorite(request, album_id): album = get_object_or_404(Album, pk=album_id) try: selected_song = album.song_set.get(pk=request.POST['song']) except (KeyError, Song.DoesNotExist): return render(request, 'music/detail.html', { 'album':album, 'error_message':"You did not select a valid song", }) else: selected_song.is_favorite = True selected_song.save() return render(request, 'music/detail.html', {'album':album})