Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Compare vlaue in django template
I want to compare a value in Templete if it is same insert data in database and if not leave it empty. {% if {{DB_product_query.exec_summary}} == 'True' %} <div class="form-group row"> <label class="col-sm-2 col-form-label">Executive summary</label> <div class="col-md-10 col-sm-10 col-xs-12"> {{ form.executive_summary }} </div> </div> {% endif %} Error::: Could not parse the remainder: '{{DB_product_query.exec_summary}}' from {{DB_product_query.exec_summary}}' already checked DB_product_query.exec_summary return True -
Django View Test With PUT Method
I am testing my Django App and I have used APIView to have all HTTP requests go to one endpoint. I have managed to test the GET and POST but testing the PUT I am getting {"detail":"Unsupported media type \\"application/octet-stream\\" in request."} when I print response.content with AssertionError: 415!=200. Below is my code; def test_view_province_exists(self): user = User.objects.create_superuser(firstname='John', lastname='Doez', email='johndoez@mail.com', role='System Admin', access_url='chikoloadmin.kodkon.com', password='Passwordz123') self.client.login(email='johndoez@mail.com', password='Passwordz123') prov = Province.objects.create(province='Southern', created_by=user) response = self.client.put(self.province_url, data={'province': 'Southern Province', 'public_key': prov.public_key}) print(response.content) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Province Updated.') -
Font-face imported font not loading on webpage (django)
I've got a django web app running and am trying to upload a custom font. I'm using @font-face in the style sheet to grab the font files and then am using inline styling in the html template to apply the font (for some reason using body{} in the style sheet doesn't apply styles to the entire page). @font-face code in style sheet: @font-face { font-family: 'D3 Digitalism'; src: local('D3 Digitalism') url('static/chatswap/font/d3-digitalism-font/D3Digitalism.woff2') format('woff2'), local('D3 Digitalism'), url('static/chatswap/font/d3-digitalism-font/D3Digitalism.woff') format('woff'), local('D3 Digitalism'), url('static/chatswap/font/d3-digitalism-font/D3Digitalism.eot'), local('D3 Digitalism'), url('static/chatswap/font/d3-digitalism-font/D3Digitalism.ttf') format('truetype'); font-weight: normal; font-style: normal; font-display: swap; } index.html template: <body style="background-color: rgb(20,20,20); font-family: D3 Digitalism"> I've tried changing the name of the font in the CSS file to something without a number or space character in the name, did not help. -
How to efficiently display objects related to specific foreign key?
I have separate models for authors and theses and the author model has a foreign key to the thesis model. My question is how can I efficiently display the authors for each thesis? This is my models.py for the author and thesis class thesisDB(Model): thesis_id = models.AutoField(primary_key=True, blank=True, null=False) title = models.CharField(max_length=200, blank=True, null=True, unique=True) adviser = models.CharField(max_length=200, blank=True, null=True) published_date = models.DateField(blank=True, null=True) class Authors(Model): thesis = models.ForeignKey(thesisDB, on_delete=models.CASCADE,) first_name = models.CharField(max_length=200, blank=True, null=True) last_name = models.CharField(max_length=200, blank=True, null=True) middle_initial = models.CharField(max_length=2, blank=True, null=True, validators=[initial_validator]) I am currently doing this method where I loop through all the authors and match their foreign key id to the thesis id in thesisdb model so I can display the right authors for each thesis. {% for post in thesis_details %} <p class="m-0"><i class="bi bi-person pe-1"></i>Authors: {% for author in authors %} {% if author.thesis.thesis_id == post.thesis_id %} <span class="me-1">{{author.first_name}} {{author.middle_initial}} {{author.last_name}}</span> {% endif %} {% endfor %} </p> {% endfor %} But this doesn't seem efficient. Is there a better way of doing it? -
Django, nginx StreamingHttpResponse Giving 502 Time Out
I am not able to figure it out why server is crashing below is the code class Echo: def write(self, value): return value @api_view(['GET']) @permission_classes([AllowAny, ]) def export_report(request): import csv from django.db import connection cursor = connection.cursor() try: cursor.execute('select query here') except Exception: cursor.close() raise echo_buffer = Echo() def cursor_generator(cursor, selected_fields, echo_buffer, arraysize=30): 'An iterator that uses fetchmany to keep memory usage down' writer = csv.writer(echo_buffer) header = True while True: if header: header = False yield writer.writerow(['first_nama', 'last_name']) results = cursor.fetchmany(arraysize) if not results: cursor.close() break for result in results: yield writer.writerow(result) response_list = [] response = StreamingHttpResponse(cursor_generator(cursor, selected_fields, echo_buffer), content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="report.csv"' return response -
Django admin show user who uploaded document
Can anyone please send me in the right direction? I have a django project without frontend so to speak. At the moment all I need is admin page. My users are able to upload documents, but there is no way for me to show for users who uploaded any given document. I managed to get a dropdown menu where user can choose who uploaded it. But that is not the goal. I want to achieve "uploaded by xxx" where "xxx" is the active (logged in) user. I fail to find correct keywords for google search and such. Can anyone drop a link to some tutorial/documentation? I have added this line to my "document" model. uploaded_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) After I add "uploaded_by" to fieldsets in admin.py I get a dropdown menu where I can choose form all users. -
In Dajngo, Class based views does not render HTML in template-Is context missing?
``I started to work with class based views, but the codes that I've written initially does not render in the template when I use class based views. The data that is in main_c.main_categories.url, main_c.name (see template) simply does not show up when I use class based views. When I change back to function based views and refresh the page, the HTML code in the template shows up without any problems. Could someone explain what causes this error? I've read something about context not been found by the template but I don't really understand what it means and how context resolves the issue. Thanks in advance!` views.py class MainCategoryDeleteView(DeleteView): model = MainCategory success_url = reverse_lazy("main_category") template_name = 'admin_dashboard/categories/maincategory_confirm_delete.html' class MainCategoryUpdateView(UpdateView): model = MainCategory fields = '__all__' success_url = reverse_lazy("main_category") template_name = 'admin_dashboard/categories/main_category_edit.html' class MainCategoryCreateView(CreateView): model = MainCategory fields = '__all__' success_url = reverse_lazy("main_category") template_name = 'admin_dashboard/categories/main_category.html' def get_context_data(self, **kwargs): context = super(MainCategoryCreateView, self).get_context_data(**kwargs) context['main_categories'] = MainCategory.objects.all() print(MainCategory.objects.all()) return context urls.py path('BaitSouq/MainCategory/', views.MainCategoryCreateView.as_view(), name="main_category"), path('BaitSouq/MainCategory/<int:pk>/Delete/', views.MainCategoryDeleteView.as_view(), name="main_category_delete"), path('BaitSouq/MainCategory/<int:pk>/Change/', views.MainCategoryUpdateView.as_view(), name="main_category_update"), templates <div class="col-lg-2 d-none d-lg-flex"> <div class="categories-dropdown-wrap style-2 mt-30"> <div class="d-flex categori-dropdown-inner" style="font-size: x-small"> <ul> {% for main_c in main_categories %} <li> <a href="#"> <img src="{{ main_c.main_categories.url }}" alt=""/>{{ main_c.name }}</a> </li> … -
How to show history of orders for user Django
I will pin some screenshots of my template and admin panel I have history of orders in admin panel but when im trying to show it in user profile in my template that`s not working and i got queryset Im sorry for russian words in my site, i can rescreen my screenshots if you need that models.py class Order(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='orders', verbose_name='Заказы', default=1) username = models.CharField(max_length=50, verbose_name='Имя пользователя') email = models.EmailField() vk_or_telegram = models.CharField(max_length=255, verbose_name='Ссылка для связи', default='vk.com') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False, verbose_name='Оплачено') class Meta: ordering = ['-created',] verbose_name = 'Заказ' verbose_name_plural = 'Заказы' def __str__(self): return 'Заказ {}'.format(self.id) def get_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='order', on_delete=models.CASCADE) product = models.ForeignKey(Posts, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price views.py @login_required def profile(request): user_orders = Order.objects.filter(user=request.user) data = { 'user_orders': user_orders, } return render(request, 'store/main_pages/profile.html', data) Шаблон выведения истории заказов {% for item in user_orders %} {{ item }} {{ item.order.all }} {% endfor %} Profile template admin order panel -
How to get multiple clicks or multiple enter keys in django form?
I have a post form in Django. When this form submits, I want a 2nd submit event not to occur until the result is returned. For this, I added the button disable property after it was clicked. Even if the button is disabled, when the button is pressed repeatedly while the page is loading, or when it is entered, the same actions are recorded in the database. How can I prevent this? This is my HTML form <form action="{% url 'neworder' %}" method="POST"> <!-- <form action="#" method="POST"> --> {% csrf_token %} <div class="form-group"> <label for="username">Kullanıcı Adı</label> <hr> <input type="text" placeholder='Kullanıcı adınız' class="form-control" name="username" id="username" required> <br> <label for="bonustur">Bonus Türü</label> <hr> <select name="orders" id='ordervalue' class="form-control" required> {% for x in orders %} {% if x.status == True %} <option value="{{x.orderid}}" style="font-weight: bolder;">{{x.ordername}}</option> {% endif %} {% endfor %} </select> <br> <button type="submit" class="btn btn-success btn-load form-control" type="submit" id="button"> <span class="d-flex align-items-center"> <span class="flex-grow-1 me-2">Check</span> <span class="spinner-border flex-shrink-0" role="status" style="display: none;"> </span> </span> </button> <!-- <button type="submit" class="btn btn-success form-control" id="button">Talep Et </button> --> </div> </form> The JQuery codes I've tried to prevent this multiple clicks <script> jQuery(function($){ $("#button").click(function(){ $.ajax({ type:'POST', success: function(data){ console.log(data); } }).done(function(){ setTimeout(function() { $("#button").prop('disabled', 'true'); $("#button").text('Checking'); $(".spinner-border").css('display', … -
Django broken pipe 56528
enter image description here Can't store data in db using psql please help . Made django project for first time . -
mediafile not working nginx server and aws infrastructure, Django
i have this messege when i click url of the image: this is my log nginx: this is my nginx configuration: this is my route of media file. My settings.py MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' i try show image with: {{MEDIA_URL}}{{instance.image.url}} -
its showing me that "book() got an unexpected keyword argument 'name'"
its showing me that "book() got an unexpected keyword argument 'name' " my views.py def book(request): if request.method=='POST': name=request.POST['name'] email=request.POST['email'] password=request.POST['password'] type=request.POST['r'] ticket_from=request.POST['ticket_from'] ticket_to=request.POST["ticket_to"] dept_date=request.POST['dept_date'] ret_date=request.POST['ret_date'] adults=request.POST['adults'] children=request.POST['childern'] tck=book(name=name,email=email,password=password,type=type,ticket_from=ticket_from,ticket_to=ticket_to,dept_date=dept_date,ret_date=ret_date,adults=adults,children=children) tck.save() return HttpResponse("Booked") else: return render(request,"book.html",) models.py # Create your models here. class book(models.Model): name=models.CharField(max_length=100) email=models.EmailField(max_length=100) password=models.CharField(max_length=100) type=models.CharField(max_length=100) ticket_to=models.CharField(max_length=100) ticket_from=models.CharField(max_length=100) dept_date=models.DateField() ret_date=models.DateField() adults=models.IntegerField() children=models.IntegerField() i dont know what is this error and how can i solve this plzz help me with this -
Why value is not changing in the database using django
I want to insert value in the database from checklist. it print me the value but does't show anything in the database. it's empty. sample output what I'm getting if ISMS(which is on the third place) is checked [00100] the zero changes accordingly but this data is not inserting in the data base below is my code:: Views.py from collections import Counter from .models import details from django.shortcuts import render from .forms import CheckBoxForm # Create your views here. def home(request): return render(request, 'home.html', {"text": "hello home"}) def about(request): return render(request, 'about.html', {"text": "hello about"}) def checkbox(request): if request.method == 'POST': exec_summary = request.POST.get('Executive_summary') scope = request.POST.get('Scope') isms = request.POST.get('ISMS') methodology = request.POST.get('Methodology') recommendation = request.POST.get('Recommendation') print(f'{exec_summary}{scope}{isms}{methodology}{recommendation}') return render(request, 'checkbox.html') def form_checkbox(request): if request.method == 'POST': form = CheckBoxForm(request.POST or None) if form.is_valid(): print(form.cleaned_data) else: form = CheckBoxForm() context = {'form': form} return render(request, 'checkbox.html', context) urls.py: from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home), path('about/', views.about), path('checkbox/', views.checkbox) ] forms.py from django import forms from .models import details class CheckBoxForm(forms.Form): exec_summary = forms.BooleanField(required=False) scope = forms.BooleanField(required=False) isms = forms.BooleanField(required=False) methodology = forms.BooleanField(required=False) recommendation = forms.BooleanField(required=False) class Meta: … -
Image field form not validating
I have this view with two forms. def anunciocreateview(request): anuncio_form = AnuncioForm(request.POST or None) producto_form = ProductoForm(request.POST or None) if request.method == "POST": if all([anuncio_form.is_valid(), producto_form.is_valid(), imagen_form.is_valid()]): anuncio = anuncio_form.save(commit=False) anuncio.anunciante = request.user anuncio.save() producto = producto_form.save(commit=False) producto.anuncio = anuncio producto.save() return HttpResponse(status=204, headers={'HX-Trigger' : 'eventsListChanged'}) else: anuncio_form = AnuncioForm() producto_form = ProductoForm() context = { 'anuncio_form' : anuncio_form, 'producto_form' : producto_form, } return render(request, 'buyandsell/formulario.html', context) This view works OKAY; it allows the user to create instances of both models with the correct relation. I'm trying to add another form for the image of the product. I tried adding this: def anunciocreateview(request): anuncio_form = AnuncioForm(request.POST or None) producto_form = ProductoForm(request.POST or None) imagen_form = ImagenForm(request.POST, request.FILES) if request.method == "POST": if all([anuncio_form.is_valid(), producto_form.is_valid(), imagen_form.is_valid()]): anuncio = anuncio_form.save(commit=False) anuncio.anunciante = request.user anuncio.save() producto = producto_form.save(commit=False) producto.anuncio = anuncio producto.save() imagen = imagen_form.request.FILES.get('imagen') if imagen: Imagen.objects.create(producto=producto, imagen=imagen) return HttpResponse(status=204, headers={'HX-Trigger' : 'eventsListChanged'}) else: anuncio_form = AnuncioForm() producto_form = ProductoForm() imagen_form = ImagenForm() context = { 'anuncio_form' : anuncio_form, 'producto_form' : producto_form, 'imagen_form' : imagen_form } return render(request, 'buyandsell/formulario.html', context) But this happens: 1- The 'Image upload' form field shows error 'This field is required' at the moment of rendering the form. … -
Django Admin - Fill inline field after autocomplete selection
I have a model with an inline model (see screenshot). The user selects a product via autocomplete and I would then like to fill in the purchasing price, that comes from the product. Here are my models. The PoItem-Model: class PoItem(models.Model): po = models.ForeignKey(PurchaseOrder, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.IntegerField() purchasing_price = models.DecimalField(decimal_places=2, max_digits=5, default=0) Here the product model. These ones here are listed in the autocomplete. And the purchasing_price from the product should be listed in purchasing_price field of the inline form, once a product has been selected via autocomplete class Product(models.Model): sku = models.CharField(primary_key=True, max_length=40, unique=True) name = models.CharField(max_length=250) purchasing_price = models.FloatField(null=True, blank=True) And here is my admin view. I have not listed the PurchaseOrder model as it's of no relevance: @admin.register(PurchaseOrder) class PurchaseOrderAdmin(admin.ModelAdmin): class PoItemInline(admin.TabularInline): model = PoItem fields = ["product", "quantity", "purchasing_price"] extra = 1 autocomplete_fields = ["product"] form = PoItemInlineForm inlines = [PoItemInline] I would need some kind of even that gets triggered once a product has been selected. -
How to achieve Dependent Dropdown between Country and State in Django inside Admin Panel
So i have created a customer portal in django admin panel and i am not using any html because i will use the django default template throughout as of now. But there is a slight issue which i am getting and that is not able to get dependent dropdown between the states and country. Refer this image --> As you can see every city is popping up in the drop down. I want the user to select country and then according to that country states should appear and then finally the user can manually enter the city name which he desires. I have heard something related to ajax (js) in this scenario since i am a newbie i am not really good in javascript so can anyone help me on how to implement it or any other possible solutions for my problem. Thankyou <3 My code: models.py class Country(models.Model): id = models.AutoField(primary_key=True) parent_id = models.IntegerField(null=False) name = models.CharField(null=False, max_length=255) status = models.CharField(null= True, choices=Status_Choices, max_length=11, default="--Select Status--") added_by = models.IntegerField() updated_by = models.IntegerField(null=True) created_on = models.CharField(default=get_current_datetime_str , max_length=255) updated_on = models.CharField(default=get_current_datetime_str, max_length=255) def __str__(self): return self.name class State(models.Model): Country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(null=False, max_length=255) status = models.CharField(null= True, … -
how to update a document then find the updated values in one mongodb using django?
I'm trying to update some values to a document in a collection using dbconn.collectionName.update_one( {'_id': ObjectId('6396c654efd251498ea4ebbc')}, {'$addToSet': { 'updateHistory': { "key":"Text", "key":"date" "key":ObjectId("633456783er5t672342134") } } }, {'$set': { "key":"Text", "key":ObjectId("633456783er5t672342134") } } ) so what I'm trying to achieve is get the updated values from the same collection with single query after its updated, is that possible? I've tried findAndModify() & findOneAndUpdate() -
Update single row of table in template page using ajax in Django
I am working on Django project and I have no idea of ajax that how to implement it. The scenario is my db contains a table name "demo" which contains the column stat_id. My database contains the following details: table name = demo id int primary key NOT NULL, stat_id int(11) NOT NULL #value is 1 Now, the scenario is that I am getting the stat_id value from database and its purpose to show the running and complete button. If python script is running then it will display the running button and if python script has executed it will display the completed button. status.html: <td> <form action = "/modules" method="get"> {% if status == 1 %} {% csrf_token %} <button link="submit" class="btn btn-default btn-sm"> <span class="badge badge-dot mr-4"> <i class="bg-success"></i>Completed</button> </form> {% else %} <button type="button" class="btn btn-default btn-sm"> <span class="badge badge-dot mr-4"> <i class="bg-warning"></i>Running</button> {% endif %} views.py: def process(request): hash_id = request.session.get('hash_id') print(hash_id) check = request.session.pop('check_status',) if hash_id and check: stat = status_mod.objects.filter(hash_id = hash_id).order_by('-id').first() if stat: stat = stat.stat_id print(stat) return render(request, 'enroll/status.html', {'status': stat}) urls.py: path('status', views.process, name='process') models.py: class status_mod(models.Model): id = models.BigIntegerField(primary_key=True) stat_id = models.BigIntegerField() class Meta: db_table = "demo" jquery / ajax in … -
About python environment
How can I install html and css formats in python environment when using Django framework? How would be in cmd? I used to pip freeze in environment, and there was a few installed things then out environment -
Django Permissions on WSL Ubuntu with Symlinked project folder
Hi I am fairly new to WSL and working in this environment. I am trying to run a Django project within a project folder that is Symlinked within Ubuntu. The location is on C:/projects. When I create a project I get the following error: Notice: Couldn't set permission bits on /mnt/c/projects/websites/vahana/manage.py. You're probably using an uncommon filesystem setup. No problem. Notice: Couldn't set permission bits on /mnt/c/projects/websites/vahana/vahana/urls.py. You're probably using an uncommon filesystem setup. No problem. Notice: Couldn't set permission bits on /mnt/c/projects/websites/vahana/vahana/wsgi.py. You're probably using an uncommon filesystem setup. No problem. Notice: Couldn't set permission bits on /mnt/c/projects/websites/vahana/vahana/settings.py. You're probably using an uncommon filesystem setup. No problem. Notice: Couldn't set permission bits on /mnt/c/projects/websites/vahana/vahana/asgi.py. You're probably using an uncommon filesystem setup. No problem. Notice: Couldn't set permission bits on /mnt/c/projects/websites/vahana/vahana/__init__.py. You're probably using an uncommon filesystem setup. No problem. Error Shown when creating a project or app Thanks I looked at trying to set permissions on the windows system to have full access. But I cannot resolve this error. -
Internal Server Error using apache django mod_wsgi or 500 internal server error mod_wsgi apache
wsgi.py import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gis_api.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() httpd.conf ServerName 127.0.0.1:81 LoadFile "C:/Users/test/AppData/Local/Programs/Python/Python310/python310.dll" LoadModule wsgi_module "C:/Users/test/AppData/Local/Programs/Python/Python310/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Users/test/AppData/Local/Programs/Python/Python310" WSGIPythonPath "C:/Users/test/AppData/Local/Programs/Python/Python310/lib/site-packages/" <VirtualHost *:81> WSGIScriptAlias / "D:/django_project/gis_api/gis_api/gis_api/wsgi.py" <Directory "D:/django_project/gis_api/gis_api/gis_api/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "D:/django_project/gis_api/gis_api/static/" <Directory "D:/django_project/gis_api/gis_api/static/"> Require all granted </Directory> Alias /media "D:/django_project/gis_api/gis_api/media/" <Directory "D:/django_project/gis_api/gis_api/media/"> Require all granted </Directory> </VirtualHost> error.log mod_wsgi (pid=20212): Failed to exec Python script file 'D:/django_project/gis_api/gis_api/gis_api/wsgi.py'., referer: http://127.0.0.1:81/ mod_wsgi (pid=20212): Exception occurred processing WSGI script 'D:/django_project/gis_api/gis_api/gis_api/wsgi.py'., referer: http://127.0.0.1:81/ Traceback (most recent call last):\r, referer: http://127.0.0.1:81/ ModuleNotFoundError: No module named 'gis_api'\r, referer: http://127.0.0.1:81/ version : Django 4.1.1 mod-wsgi 4.9.4 os window 10 I have try to all solution. But getting error. I am beginner to deployment in django apache. Pl guide me best path of deployment. -
Firestore integration with Django
I have a Firebase Firestore database connected to a Flutter mobile application. I want to build a web application to manage the users' data and handle new users. I have decided to use Django for my web application, but I have two questions if anyone can help. First, is it actually reliable to use Django as the framework for this purpose? Second, I was trying to make a connection between Django and my existing DB to just try to call some values but I was getting this error: google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. Here is the code I am using for the connection db = firestore.Client() config={ "apiKey": "******************", "authDomain": "*******.firebaseapp.com", "projectId": "*******", "storageBucket": "*******.appspot.com", "messagingSenderId": "*******", "appId": "******************", "databaseURL": "https://***********.firebaseio.com", } firebase = pyrebase.initialize_app(config) auth = firebase.auth() database = firebase.database() def index(request): doc = db.collection('test').document('test1').stream() weight= doc['weight'] return render(request, 'index.html', { "weight":weight, }) -
How can we Integrate Nuxtjs and Django?
Hello I'm having a trouble Integrating Nuxtjs together with Django, can't find any related resources. -
Pass POST data in form with no action url Django
I have here a form with two buttons in it and when submitting, it doesn't pass the data on another page. <form method="post"> #some form inputs here... <a class="btn btn-success" href="{% #url_here %}">published</a> <a class="btn btn-secondary" href="{% #url_here %}">save as draft</a> </form> Does anyone know how to pass a post data in tag in Django, if the form tag has no action URL? thanks in advance! -
"Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)". How to fix Error
I'm trying to submit post form data to an my api using react and I'm passing through JSON data like so. ` function AddSong() { const [title, setTitle] = useState(""); const [artist, setArtist] = useState(""); const [release_date, setReleaseDate] = useState(""); const [album, setAlbum] = useState(""); const [genre, setGenre] = useState(""); let handleSubmit = async (e) => { e.preventDefault(); try { let res = await fetch("http://127.0.0.1:8000/api/music_library/?format=json", { method: "POST", body: JSON.stringify({ title: title, artist: artist, album: album, release_date: release_date, genre: genre, }), }); let resJson = await res.json(); if (res.status === 200) { setTitle(""); setArtist(""); setReleaseDate(""); setAlbum(""); setGenre(""); } } catch (err) { console.log(err); } }; ` Here is my submit form. ` return ( <div className="App"> <form onSubmit={handleSubmit}> <input type="text" value={title} placeholder="Title" onChange={(e) => setTitle(e.target.value)} /> <input type="text" value={artist} placeholder="Artist" onChange={(e) => setArtist(e.target.value)} /> <input type="text" value={release_date} placeholder="Year" onChange={(e) => setReleaseDate(e.target.value)} /> <input type="text" value={album} placeholder="Album" onChange={(e) => setAlbum(e.target.value)} /> <input type="text" value={genre} placeholder="Genre" onChange={(e) => setGenre(e.target.value)} /> <button type="submit">Create</button> </form> </div> ); } export default AddSong; ` When I click submit on the form, Chrome gives me an error saying "Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)". I know it has …