Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django hide password fields on user creation form
I have a custom user model and a form that allows admins to add users without having to go to the admin section. I want hide the password fields and set the password to a random generated string. Then send an email to the new user with a link to reset their password. So far I haven't been able to figure out the first part - hiding the password fields. The form.py: from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class AddCompanyEmployeeForm(UserCreationForm): class Meta: model = CustomUser fields = UserCreationForm.Meta.fields + ('email', 'full_name', 'age') the view: from django.views.generic import CreateView, ListView from django.urls.base import reverse from .forms import CustomUserCreationForm, AddCompanyEmployeeForm from .models import CustomUser class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' class AddCompanyEmployee(CreateView): model = CustomUser template_name = 'manage/add_employee.html' form_class = AddCompanyEmployeeForm #success_url = reverse_lazy('directory') def get_success_url(self): return reverse('userprofile_detail', kwargs={'pk': self.object.userprofile.pk}) I have tried a number of approaches including changing the form to class AddCompanyEmployeeForm(UserCreationForm): class Meta: model = CustomUser fields = ('email', 'full_name', 'age') So far the password fields continue to be visible regardless of what I try. Any suggestions? -
Someone help me in this error TypeError at /contact 'method' object is not subscriptable
Views.py # Create your views here. def home(request): return render(request, 'home.html') def about(request): return render(request, 'about.html') def project(request): return render(request, 'project.html') def contact(request): if request.method=='POST': name=request.POST.get['name'] email=request.POST.get['email'] phone=request.POST.get['phone'] concern=request.POST.get['concern'] print(name,email,phone,'concern') obj=Contact(name='name', email='email',phone='phone',concern='concern') obj.save() return render(request, 'contact.html') I am trying to connect my contact form with database but after post method it doesn't allow me. -
I am trying to render docx file in my django project, using the data from JSON field, but it couldn't find the docx file in my system
This is my views.py from pathlib import Path from django.conf import settings from rest_framework import viewsets from rest_framework import mixins from rest_framework.decorators import action from django.http import HttpResponse from . import models from . import serializers from docxtpl import DocxTemplate import pypandoc class TemplateViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet, ): queryset = models.Template.objects.all() serializer_class = serializers.TemplateSerializer def get_serializer_class(self): return { 'list': serializers.TemplateSerializer, 'retrieve': serializers.TemplateSerializer, 'generate_document': serializers.DocumentGenerateSerializer, }.get(self.action, serializers.TemplateSerializer) @action(detail=True, url_name='generate-document', methods=['POST', 'GET']) def generate_document(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) context_data = serializer.data['context'] document_extension = serializer.data['extension'] instance = self.get_object() versions = instance.versions.all() documents = versions.get(id=instance.id) document = DocxTemplate(open('src/media/{}'.format(documents.upload.name.split('.')[0] + '.docx'))) # document = documents.upload document.render(context_data) if document_extension == 'docx': response = HttpResponse(document, content_type='application/vnd.openxmlformats-officedocument' '.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename="{}"'.format(document.name.split('.')[0] + '.docx') return response else: pypandoc.convert_file(document, 'pdf', outputfile=document) response = HttpResponse(document, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="{}"'.format(document.name.split('.')[0] + '.pdf') return response This is my forms.py, where I am getting JSON field from django import forms from django.contrib.auth import get_user_model from .models import Template, Version User = get_user_model() class TemplateCreationForm(forms.ModelForm): class Meta: model = Template fields = ('name',) def save(self, commit=True): self.instance.user = self.request.user return super().save(commit) class VersionCreationForm(forms.ModelForm): class Meta: model = Version fields = ('template', 'upload', 'start_from', 'end_to') Template is being created through my … -
Api for Shoping App (Flutter) with Python
I need to make an Api to use for a shopping app built with Flutter and i want to use Python to as i already have decent exprince in and i heard that it could be done using Python and Django as a database I never tried to do so before -
Why shows this error when adding the file "Object of type InMemoryUploadedFile is not JSON serializable"?
My target is to build a form that besides charfields will have a file field and all data of the fields will be stored in the database. The form does store the charfield's data, but after adding a new field as filefield It not working when I submit, and shows the below error😥. Why is not store the filefield's data? views.py: def employeeListView(request): if request.method == 'POST': serializer = EmployeeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return redirect("/") def InsertAndInfo(request): if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') file = request.FILES['filedf'] #if 'filedf' in request.FILES else None data = { 'name':name, 'email':email, 'phone':phone, 'file':file } headers = {'Content-Type': 'application/json'} requests.post('http://127.0.0.1:8000/api/employees/',json=data,headers=headers) return redirect("/api/") employeeInfoApiLink = requests.get('http://127.0.0.1:8000/api/AllElmployeeInfo/').json() context = { "employeeInfo":employeeInfoApiLink } return render(request, 'InsertAndInfo.html',context) models.py: class Employee(models.Model): name = models.CharField(max_length=30) email = models.EmailField(max_length=30) phone = models.CharField(max_length=30, null=True) file = models.FileField(upload_to="file/",null=True) serializer.py: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = "__all__" form.html: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="text" class="form-control" name="name" id="name"> <input type="email" name="email" class="form-control" id="email" aria-describedby="emailHelp"> <input type="text" name="phone" class="form-control" id="phone"> <input type="file" name="filedf" class="form-control" id="file"> <button type="submit" class="btn btn-primary">Submit</button> </form> -
Django Channels on azure
I can't connect to the websocket in my azure app. To be concise my issue is exactly same as this question. I saw its answer too and it says that custom port 6379 is not allowed. Is there any way for this to work. How can I add the port 6379 to my web app. Or if not Are there any alternatives? -
Getting the average rating from a book in a bookstore api
Written in python. I am having an issue that the average won't work on my code. I don't know if I can use annotate or aggregate. I want it so I can choose what book I want and show the average once I choose it. class AverageRatingViewSet(generics.ListAPIView): serializer_class = BookratingsSerializer def get_queryset(self): queryset = Bookratings.objects.all() try: user_input = self.request.query_params.get('rating') except AttributeError as abc: return Bookratings.objects.none() if user_input is not None: **** ***queryset = queryset.filter(bookid=user_input).aggregate(Books_average=Avg('rating')*)**** ** return queryset I started messing around with the queryset.filter but I keep getting error on the local host -
Trigger python script with Django user input
I am trying to trigger a pyfirmata script that will load onto an arduino device when a user checks a checkbox on a django view. I am trying to implement some comparison code in my view that will check if user submitted check box is true then trigger pyfirm.py. Background: Py firmata will drive the arduino pins directly without needing an arduino IDE. Should I hard code my pyfirmata in my view or can I trigger a full script some how? Iam using a raspberry pi as a single board computer that is connected to arduino as a device driver. I am considering the pi device as a user. Any tips on this? I have my check box working and i am printing the POST results to the terminal. just need to check if box is true and trigger script some how. Haven't had any luck triggering a script. I see a couple questions related to this but i am curious for pyfirmata specific directions on this. -
Loading choices from utils.py results in unexpected error: TypeError: 'CharField' object is not iterable in Django
I have a models.py file in Django, and it was working perfectly. I have an extensive model named Media, and since it contains quite some columns with elaborate choices in nested tuples, I decided to move these nested tuples to an utils.py file located in the same app. I found that it is working for all columns in my Media model, except for one. It is shown below: #This was how it was initially and working: #Umbrella UMBRELLA = ( ("DH", "DH"), ("SE", "SE"), ("PA", "PA"), ("PF", "PF") ) class Media(models.Model): umbrella = models.CharField(max_length=20, choices=UMBRELLA, default='Undefined', null=True, blank=True) second_umbrella = models.CharField(max_length=20, choices=UMBRELLA, default='Undefined', null=True, blank=True) #Problematic? Changed it to: utils.py: #Umbrella def UMBRELLA(): UMBRELLA = ( ("DH", "DH"), ("SE", "SE"), ("PA", "PA"), ("PF", "PF")) return(UMBRELLA) models.py: from database.utils import * umbrella=UMBRELLA() class Media(models.Model): umbrella = models.CharField(max_length=20, choices=umbrella, default='Undefined', null=True, blank=True) #This one is not problematic second_umbrella = models.CharField(max_length=20, choices=umbrella, default='Undefined', null=True, blank=True) #This one is problematic The strange thing here is that if I only change (first) umbrella choiches to umbrella from utils.py it works fine. However, if i change choices from second_umbrella to umbrella from utils.py it crashes?? I meticulously checked the db.sqlite3 with django admin, but the choices … -
Django AttributeError: 'list' object has no attribute 'sort_values'
I'm getting AttributeError: 'list' object has no attribute 'sort_values' in below code, task.py: from __future__ import absolute_import,unicode_literals from celery import shared_task from time import sleep import eda import os @shared_task def aync_task(amz_columns_dict, download_path, file_name, data): sleep(10) eda_object = eda.eda(col_dict=amz_columns_dict) save_path = download_path name_of_file = file_name file_path = os.path.join(save_path, name_of_file+".html") eda_object.create_report(data=data, filename=file_path) return 'task complete' views.py : def eda_flow(request): path = '/Unilever/satyajit/us_amz.csv' mode = 'rb' df = pd.read_csv("/home/satyajit/Desktop/opensource/data/us_amz.csv", low_memory=False) df = df.head(100) json_records = df.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) context = {'data': data, 'message': 'data loaded successfully.'} if request.method == 'POST': id_col = request.POST.get('id_col') file_name = request.POST.get('file_name') download_path = request.POST.get('download_path') amz_columns_dict = {'id_col': id_col} try: if os.path.exists(download_path): status = aync_task.delay(amz_columns_dict, download_path, file_name, data) return render(request,'home/index.html', {'message': 'Save Complete'}) else: return render(request,'home/index.html', {'message': 'download path is not exist'}) except Exception as e: print('error is---->', e) return render(request,'home/index.html', {'message': 'Error while generating EDA'}) return render(request, "home/tables-simple.html", context) The error of this code on below as screenshot: I've also tried to search similar question here (similar question) but that does not helpful to me. Any help would be much appreciated. thanks in advance. -
How to modify a Django date with SQL code?
I have a Django model with a number of minutes. These minutes must be added to a date. The date being before 0 B.C., I want to work with SQL code. I don't know if I'm writing it the right way, I don't have a desired result. How could I improve it? datetri = models.FloatField(db_column='DateTri', blank=True, null=True) @property def event_sql(self): query = '''DECLARE @StartTime DATETIME = '-500, 1, 1' SELECT DATEADD(MINUTE(@StartTime), @datetri)''' with connection.cursor() as cursor: cursor.execute(query) return event_sql -
Every form validation in formset
Some troubles with validation. I'm using this construction in my template: <form method="POST"> {% csrf_token %} {{ formset.media.js }} {% for form in formset %} <p>{{ form }}</p> {% endfor %} <button type="submit" class="btn btn-primary">Send</button> And this validation in views: def flow_type(request): patternFormset = modelformset_factory(CashFlowPattern, fields='__all__') if request.method == 'POST': formset = patternFormset(request.POST) if formset.is_valid(): formset.save() formset = patternFormset() template = 'cash_table/index.html' context = { # 'form': form, 'formset': formset } return render(request, template, context) I get form at page but nothing happens after submit. But if I use another template construction it works: <form method="POST"> {% csrf_token %} {{ formset.media.js }} {{ formset }} <button type="submit" class="btn btn-primary">Send</button> </form> But then I get all fields of new form at the same line. -
django rest freamwork comment
I have two questions about creating messages about products. My first question is why do I have to provide the user and product fields in Insomnia. Because in the creation function, I specified how the user and the product should be stored in the database. My second question is why should I use valve because if I don't use it, it gives me the following error: Field 'rate' expected a number but got <BoundField value=5 errors=None>. class CommentProduct(APIView): serializer_class = CommentSerializer def post(self, request, *args, **kwargs): product = Product.objects.get(id=kwargs['pk']) serializer = self.serializer_class(data=request.POST) if serializer.is_valid(): Comment.objects.create(user_id=request.user.id, product_id=product.id, comment=serializer['comment'].value, rate=serializer['rate']) return Response(serializer.data) return Response(serializer.errors) -
How to fetch object in create method?
Need help on fetching the value in my view method. Hello! I'm trying to fetch the value of my requesterid. I want to create a condition that if requesterid is equal to a certain value, it will allow the create method. I don't know how I will access the variable. Can someone help me on this? I have this in my code so far, but it says that "Error": "'Request' object has no attribute 'requesterid'" Here's my views.py class RequestListCreateView(ListCreateAPIView): queryset = requestTable.objects.all() serializer_class = RequestCreateSerializer def create(self, request, *args, **kwargs): if request.requesterid.userroleid == 3: write_serializer = RequestCreateSerializer(data=request.data) write_serializer.is_valid(raise_exception=True) instance = self.perform_create(write_serializer) headers = self.get_success_headers(write_serializer.data) return Response({"Request ID": write_serializer.instance.requestid, "Parts ID": [p.partsid for p in write_serializer.instance.parts.all()]},headers=headers) raise ValidationError("Sorry! Your role has no permission to create a request.") Here's my models.py class userTable(models.Model): userid = models.UUIDField(primary_key=True, default = uuid.uuid4, editable=False) username = models.CharField(max_length=50, null=False, unique=True) userroleid = models.ForeignKey(roleTable, on_delete=models.CASCADE) class roleTable(models.Model): roleid = models.IntegerField(null=False, primary_key=True) role = models.CharField(max_length=255, null=False) class requestTable(models.Model): rid = models.AutoField(primary_key=True) requesterid = models.ForeignKey(userTable, on_delete=models.CASCADE) (...) -
Django - how to update multiple rows using a checkbox
I want to update a boolean to 'True' in bulk for all the rows in a table. I want to update the age of which the people have a qualified age using a form checkbox for multiple rows The code is Class Age(models.Model) Name = models.CharField(max_length=100) age = models.IntegerField() qualified_age = models.BooleanField(default='False) Views.py def Home(request): context = [] list = Age.objects.all() if request.method == 'POST': list_data = request.POST.getlist('instance') for data in list_data: Age.objects.filter(id=data).update(qualified_age=True) return redirect(Home) context{ list:'list', } return render(request, 'index.html', context) Index.html <tr> <th> Change Bool Value </th> <th> Names </th> <th> Ages </th> </tr> <form method='post', action=' '> {% for data in List %} <tr> <td> <input type="checkbox", value=" {{data.id}} ", name="instance"> </td> <td> {{data.Name}} </td> <td> {{data.age}}</td> </tr> {% endfor %} </input type="submit", value="Update"> </form> I want to update all the rows all at once but it's not working... Could anyone please assist...¿ -
Is is possible to use ThreadPoolExecutor inside django views?
I have a view that has to cooperate with another service and thus make a bunch of requests to that third-party service. In my project I use Django==1.1.16 and python 3.6 Is is possible to use ThreadPoolExecutor from concurrent.futures inside a django view to concurrently make a bunch of requests to another service and take advantage of this I/O operation inside my view? Any tips or advices? Celery is not an option in that case. Out simple infrastructure do not support that. -
POST json object but QueryDict is empty
I want to post an obj to Django server, but the QueryDict is always empty. Client side: function makeRequest (method, url, data, datatype) { function msg (err, datums) { if (err) { throw err; } console.log(datums); } var xhr = new XMLHttpRequest(); xhr.open(method, url,true); // X-CSRFToken xhr.setRequestHeader('X-CSRFToken', csrftoken); xhr.setRequestHeader("Content-Type", datatype); xhr.onload = function () { msg(null, xhr.response); }; xhr.onerror = function () { msg(xhr.response); }; xhr.send(data); } var params = { "range":"Sheet1!A4:C4", "majorDimension": "ROWS", "values": [ ["Hello World","123", "456"] ], } makeRequest('POST', "http://127.0.0.1:8000/update_student/1/",JSON.stringify(params) , 'application/json'); Server side: def update_student(request,pk): if request.method =="POST": print("update_student entered") breakpoint() return HttpResponse("a post method", status=200) else: return HttpResponse("This should be a POST method", status=400) I checked the payload when the post is sent, it's not empty. -
Selecting HTML datalist option does not trigger search event
I am developing a search engine for a website; now it's working fine and responding to input search keywords with no issues in its interaction with the (Django-based) local web server. The problem (well there are actually two, but I'm presenting only one here) is with the datalist. When I select an option from the list, although it goes into the search input field, nothing happens until I click the submit button. I have written an event listener for each option, but I'm clearly missing something (important). Here's my minimal working code: HTML <form id="search-form" action ="{% url 'search' %}" method='POST'> {% csrf_token %} <input id="enter" type="search" list="options" name="query" /> <datalist id="options"> <option class="option" value="Happy"> <option class="option" value="Puzzled"> </datalist> <button id="go" type="submit"><strong>&#x1F50E;&#xFE0E;</strong></button> <button id="reset" type="reset"><strong>X</strong></button> </form> JavaScript <script> const searchForm = document.getElementById('search-form'); const enter = document.getElementById('enter'); let options = document.querySelectorAll(".option"); options.forEach((item, index) => { item.addEventListener("click", () => { return searchForm.action; }) }) </script> Maybe the event should be something else; I've tried "keydown" and clicking twice but nothing has worked. Your help would be most appreciated. -
media files stores files in MEDIA_ROOT, but serves them from app folder
I'm having trouble bending the media_root to my will. When I try to serve an image, a suffix is appended to the file path, more precisely, it tries to point to an app (yoga) even though I want it to point to BASE_DIR / media. For example it will give me this: http://localhost:8000/yoga/media/images/satori.jpg But the media folder is (auto-generated) one folder up from that in the dir hierarchy. I've been wracking my brain, because I just can't see where that "yoga/" line is appended to the path, and I don't understand why or how it got there, lest of course we consider, that the model that it stems from lives inside the yoga app directory. Here's what I think might be relevant. Please let me know if you want to see more of the goods. Tree: . ├── boofers.txt ├── db.sqlite3 ├── dos_env ├── manage.py ├── media ├── static ├── yoga └── yoga_dos In settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' in the model @ yoga/models.py: ex_img = models.ImageField(upload_to='media/images', blank=True, default='yogapose.jpg') -
How to make collections like Instagram saves posts in custom collections in django
I am currently working on a social media website with Django , here I can like, comment and save posts without having to go to a post's detail page {can do it like Instagram allows user} , now having the ability for a user to save certain posts , I want to allow the users to save those posts into their own custom collections {for example if user likes a post with cats in it they can make a collection name "cats" and save post there } I want to know how I would go about doing that , please explain some logic and if possible can you guide me to some code snippets or a blogpost thank you -
Django HttpResponse attachment filename when non-english character occurs the file downloads improper
I am downloading a file from a django server and it downloads correctly when the filename consists of all english characters like "ready.csv". However, i am having difficulties when the filename contains other than english characters like "ılgaz.csv". It downloads the file as "download.csv". response=HttpResponse(content_type='text/csv') response['Content-Disposition']="attachment; filename=" + str(filename) + "_" + str(datetime.datetime.now()) + ".csv" This is how i create my response object. -
xhr always send request without payload (django
The QueryDict is always a emptye dictionary. Client side: function makeRequest (method, url, data, datatype) { function msg (err, datums) { if (err) { throw err; } console.log(datums); } var xhr = new XMLHttpRequest(); xhr.open(method, url,true); // X-CSRFToken xhr.setRequestHeader('X-CSRFToken', csrftoken); // xhr.setRequestHeader('Content-Type', datatype); xhr.setRequestHeader("Content-Type", datatype); xhr.onload = function () { msg(null, xhr.response); }; xhr.onerror = function () { msg(xhr.response); }; xhr.send(data); } var params = 'orem=ipsum&name=binny'; makeRequest('POST', "http://127.0.0.1:8000/update_student/1/",params , 'application/x-www-form-urlencoded'); Server side: def update_student(request,pk): if request.method =="POST": print("update_student entered") breakpoint() return HttpResponse("a post method", status=200) else: return HttpResponse("This should be a POST method", status=400) I observe the breakpoint() line, and discover the request didn't send anything. What's wrong? Thanks:) p.s. I hate django. HOw can disable the stupid csrf_token when I'm developing. -
Serializer for Recursive Comment in Django
models.py class Comments(models.Model): content = models.CharField(max_length=500) sub_comment_id = models.ForeignKey('self', related_name='sub_comments', null=True, blank=True, on_delete=models.CASCADE) author_id = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user_comments', on_delete=models.CASCADE) article_id = models.ForeignKey(Article, related_name='article_comments', on_delete=models.CASCADE) like = models.IntegerField(default=0) dislike = models.IntegerField(default=0) is_sub = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() def __str__(self): return self.content what can i do for showing all recursive comments in Comment Serializer? i use django rest framework-recursive but does not work -
A few generic views under one URL
I'm facing a issue with setting up a few generic views on this same certain URL. I would like to have a modeled my API as below: GET /cars/ <- car list POST /cars/ <- add new car GET /cars/uuid/ <- get particular car PUT /cars/uuid/ <- edit particular car DELETE /cars/uuid/ <- delete specific car So finally my issue is that the first include in urlconfig is able to perform the HTTP method, on rest of them I'm always getting "Method Not Allowed:". In above example it's occurs for PUT and DELETE. Is it possible to resolve URL as above or should I add prefixes like /cars/get/uuid? urls.py urlpatterns = [ path('', CarListApi.as_view(), name='list'), path('', CarCreateApi.as_view(), name='create'), path('<uuid:uuid>/', CarDeleteApi.as_view(), name='delete'), path('<uuid:uuid>/', CarUpdateApi.as_view(), name='update'), path('<uuid:uuid>/', CarDetailApi.as_view(), name='detail'), ] partial views.py class CarUpdateApi(generics.UpdateAPIView, generics.GenericAPIView): permission_classes = (IsOwnerOrReadOnly,) lookup_field = 'uuid' http_method_names = ['delete', 'get', 'post', 'put'] @extend_schema_serializer(component_name="CarUpdateInputSerializer") class InputSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ['plate', 'make', 'model', 'uuid'] @extend_schema(request=InputSerializer, responses={201: InputSerializer}) def put(self, request, uuid): serializer = self.InputSerializer(data=request.data, context={'request': request}) if serializer.is_valid(raise_exception=True): car = car_update(serializer.validated_data, uuid) return Response(self.InputSerializer(car).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class CarDeleteApi(generics.DestroyAPIView, generics.GenericAPIView): http_method_names = ['delete', 'get', 'post', 'put'] @extend_schema_serializer(component_name='CarDeleteInputSerializer') class InputSerializer(serializers.ModelSerializer): class Meta: model = Car … -
The field returns null even though it contains a value
When creating a new object (music track), I specify the name of the playlist in one of the fields. However, after saving the data from the form, the value of the playlist field in the frontend is null, although there is a value in this field in the admin panel. I do not understand how I can get the name of the object (playlist) that I specify when creating, for some reason it is always null in the frontend. my models: class Composition(models.Model): title = models.CharField(max_length=500) artist = models.CharField(max_length=500) playlist = models.ForeignKey('PlayList', on_delete=models.CASCADE, blank=False) time_length = models.DecimalField(blank=True, max_digits=20, decimal_places=2) audio_file = models.FileField(validators=[validate_is_audio]) cover_image = models.ImageField() def save(self, *args, **kwargs): if not self.time_length: # логика для получения длины музыкального трека audio_length = get_audio_length(self.audio_file) self.time_length = audio_length return super().save(*args, **kwargs) class PlayList(models.Model): name = models.CharField(max_length=500) my views def addSong(request): form = AddCompositionForm() if request.POST: form = AddCompositionForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) playlist = form.cleaned_data.get('playlist') music_playlist = PlayList.objects.get_or_create(name=playlist) instance.playlist = music_playlist[0] instance.save() return redirect("music_player:home_page") return render(request, 'addSong.html', { 'form': form }) my frontend function const setSRC = () => { player.src = `{{ MEDIA_URL }}/${musics[compositionIndex].audio_file}` song_title.textContent = musics[compositionIndex].title artist.textContent = musics[compositionIndex].artist music_img.setAttribute('src', `{{ MEDIA_URL }}/${musics[compositionIndex].cover_image}`) if (musics[compositionIndex].playlist != null) { // …