Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-tables2 package show cached data
I have this installed package: django-tables2==2.4.1 The table shows some deleted objects as if the information is cached. views.py: class CustomListView(LoginRequiredMixin, PermissionRequiredMixin, SingleTableView, FilterView, CustomBaseView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'table': self.table_class(self.queryset), }) return context list.html: {% load render_table from django_tables2 %} ... <div class="card-body custom-card-body"> <div class="table-responsive"> {% render_table table %} </div> </div> Anybody could help me please? Thanks in advance. -
Is rolling out Django on WSL a valid option?
I am currently facing the challenge to rollout a Django/MySQL application on a windows computer without internet access. Though rolling out django on windows is possible, having a linux environment would be preferrable, since some mechanisms we would like to use do not run on windows. Sadly, a linux server is not an option for our customer. The question, that came to my mind now is: Would it be possible to host the django application on WSL? I have seen many topics about using wsl for django development. But i wonder if it would be a stable, secure and maintainable option for a django app in production. Do you have any experience with this setup? Are there any show stoppers I am missing? What would your recommendation be regarding django rollouts on windows? Thank you for your input. -
Set MYSQL date format from YYYY-MM-DD to DD/MM/YYYY - Django
I have a Django App with a MYSQL database and wanted to check is it possible to change the date format in MYSQL to accept dates input as DD-MM-YYYY rather than YYYY-MM-DD? I can change the date fine in Django but when I go to save my form data I currently get a date validation error stating that the date must be yyyy-mm-dd. (['“24/05/2022” value has an invalid date format. It must be in YYYY-MM-DD format.']) It works fine if I change the date to the format it wants YYYY-MM-DD but I would like the output to be DD-MM-YYYY. I read a few comment and suggestions saying to alter the settings.py file to allow different date formats (as below) but this did not seem to work either. # Date formats DATE_INPUT_FORMATS = ('%d/%m/%Y') # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-AU' TIME_ZONE = 'Australia/Melbourne' USE_I18N = True USE_L10N = True USE_TZ = True Appreciate any help anyone can offer on this. -
Django Celery Periodic task is not running on given crontab
I am using the below packages. celery==5.1.2 Django==3.1 I have 2 periodic celery tasks, in which I want the first task to run every 15 mins and the second to run every 20 mins. But the problem is that the first task is running on time, while the second is running on random timing. Although I'm getting a message on console on time for both tasks: Scheduler: Sending due task <task_name> (<task_name>) Please find the following files, celery.py from celery import Celery, Task app = Celery('settings') ... class PeriodicTask(Task): @classmethod def on_bound(cls, app): app.conf.beat_schedule[cls.name] = { "schedule": cls.run_every, "task": cls.name, "args": cls.args if hasattr(cls, "args") else (), "kwargs": cls.kwargs if hasattr(cls, "kwargs") else {}, "options": cls.options if hasattr(cls, "options") else {} } tasks.py from celery.schedules import crontab from settings.celery import app, PeriodicTask ... @app.task( base=PeriodicTask, run_every=crontab(minute='*/15'), name='task1', options={'queue': 'queue_name'} ) def task1(): logger.info("task1 called") @app.task( base=PeriodicTask, run_every=crontab(minute='*/20'), name='task2' ) def task2(): logger.info("task2 called") Please help me to find the bug here. Thanks! -
[FreeTDS][SQL Server]SQL Anywhere Error -265: Procedure 'SERVERPROPERTY' not found
I'm trying to connect to sybase database with pyodbc. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'mssql_database': { 'ENGINE': 'django_pyodbc', 'NAME': 'blabla', 'USER': 'blabla', 'PASSWORD': 'blabla', 'HOST': '10.65.1.20', 'PORT': '1433', 'OPTIONS': { 'driver': 'FreeTDS', 'host_is_server': True, }, }, 'sybase_database': { 'ENGINE': 'django_pyodbc', 'NAME': 'blabla', 'USER': 'blabla', 'PASSWORD': 'blabla', 'HOST': '10.60.1.6', 'PORT': '2638', 'OPTIONS': { 'driver': 'FreeTDS', 'host_is_server': True, }, }, } Connection to mssql_database works. But connection to sybase_database ends with this error message: django.db.utils.DatabaseError: ('42000', "[42000] [FreeTDS][SQL Server]SQL Anywhere Error -265: Procedure 'SERVERPROPERTY' not found (504) (SQLExecDirectW)") $ pip list Package Version ------------- ------- Django 1.8 django-pyodbc 1.1.3 pip 21.3.1 pyodbc 4.0.32 setuptools 59.6.0 sqlany-django 1.13 sqlanydb 1.0.11 wheel 0.37.1 -
djang many to many relationship with self referencing
How can I do a many to many relationship in django with the same class but disable the possibility to do a relationship with the same Person. Like a boss can have a relationship with many persons but shouldn't be possible to do a relationship with him self, but they are in the same class. -
Django Ajax pass data with primary key to view
Help been trying to pass data between views using ajax and a primary key. Example a view and a detailView of object in my database. I am able to Get & Post data. Below is my Js Code. Thanks. // CSRF TOKEN // function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); // Create // var form = document.getElementById('form-wrapper') form.addEventListener('submit', function(e){ e.preventDefault() console.log('Nimetuma') var url = 'http://127.0.0.1:8000/swimmers-create/' var title = document.getElementById('tester').value var date = document.getElementById('date-time').value fetch(url, { method:'POST', headers: { 'Content-type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'sessions':title,'date_from':date}) }).then(function(response){ apiList() document.getElementById('form-wrapper').reset() }) }); // More Details // Thank you all for the help and support much appreciated. -
Adaptive Server is unavailable or does not exist
I'm trying to connect to mssql server via FreeTDS. First I tried it via ODBC Driver 17 for SQL Server and it works. Here is my configuration in settings.py. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'mssql_database': { 'ENGINE': 'django_pyodbc', 'NAME': 'blabla', 'USER': 'blabla', 'PASSWORD': 'blabla', 'HOST': '10.65.1.20', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } According to this guide I installed FreeTDS on Ubuntu 18.04. Here is my /etc/odbcinst.ini [ODBC Driver 17 for SQL Server] Description=Microsoft ODBC Driver 17 for SQL Server Driver=/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.9.so.1.1 UsageCount=1 [FreeTDS] Description = TDS driver (Sybase/MS SQL) Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so CPTimeout = CPReuse = And here is the new settings.py section DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'mssql_database': { 'ENGINE': 'django_pyodbc', 'NAME': 'blabla', 'USER': 'blabla', 'PASSWORD': 'blabla', 'HOST': '10.65.1.20', 'PORT': '', 'OPTIONS': { 'driver': 'FreeTDS', 'host_is_server': True, 'extra_params': "TDS_VERSION=8.0" }, }, } And I have this error message pyodbc.OperationalError: ('08S01', '[08S01] [FreeTDS][SQL Server]Unable to connect: Adaptive Server is unavailable or does not exist (20009) (SQLDriverConnect)') How can I fix the error? The connection works with ODBC Driver 17 for SQL Server. So why doesn't it work with … -
Django Project Directory Structure
in my django project structure, i want all my django apps in a separate Apps Folder, but when i include it in settings.py it raises an error, raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Cannot import 'TestApp'. Check that 'Apps.TestApp.apps.TestappConfig.name' is correct. INSTALLED_APPS = [ ... 'Apps.TestApp' ] But when i only include TestApp, i raises no module named 'TestApp' Error. INSTALLED_APPS = [ ... 'TestApp' ] -
keep getting Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. error
I want to implement password reset functionality on my web page but I am getting NoReverseMatch at /accounts/password_reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. error. please help me to solve this error url.py Code: app_name="accounts" urlpatterns=[ path('password_reset/', auth_views.PasswordResetView.as_view(template_name="password_reset.html",success_url=reverse_lazy('accounts:password_reset_done')), name='password_reset'), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password_reset_confirm.html",success_url=reverse_lazy('accounts:password_reset_complete')), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="password_reset_done.html"), name="password_reset_complete"), ] passwrd_reset.html {% extends 'base.html' %} {% block title %}Password Reset Page{% endblock %} {% load crispy_forms_tags %} {% block body %} <div class="container"> <div class="row mt-5 pt-3"> <div class="col-md-8 offset-md-2"> <div class="card my-3 shadow"> <div class="card-body"> <h4>Password Reset Page</h4> <hr> <div class="alert alert-info"> Enter email and a mail will be sent with instructions to reset password </div> <form method="POST"> {% csrf_token %} {{ form|crispy }} <input class="btn btn-primary btn-block" type="submit" value="Reset Password"> </form> <hr> </div> </div> </div> </div> {% endblock body%} -
How to add dynamically add apps in install apps in django settings.py by using apps.py of app directory?
I am trying to add app automatically after python manage.py startapp command in installed app in django-settings.py file. -
Django queryset to show values every month
I'm making a Django APP (required) to calculate every month the profits and losses. There's a feature that I wanted to put that in N months you'll be paying the value/N (i.e: $100/5 that equals to $20 per month). This feature would be like a Bank APP shows how many you have yet to pay (i.e: from this month to October) By the way, there's only one record from the losses (I'm trying not to change this) So far so good, but the record appear only in the month of my search (view below) and when I try to use: Account.objects.filter(date__year__gte=y) or Account.objects.filter(date__month__gte=m) or Account.objects.filter(date__year__lt=y) or Account.objects.filter(date__month__lt=m) The record shows the entire year or the months whose are greater or less than the month saved (with no filter, so if it's from July to November, it'll show until December or in January) View.py def account(request, pk): search = f"{datetime.now().year} - {datetime.now().month:02}" account = Account.objects.get(id=pk) ctx = { 'search': search } if request.GET.get('month'): search = request.GET.get('month') y, m = search.split('-') ctx.update({ 'search': search }) date_loss = filter_by_model_date(Loss, m, y) date_profit = filter_by_model_date(Profit, m, y) profit = filter_by_account(date_profit, account) loss = filter_by_account(date_loss, account) ctx.update({ 'profit': profit, 'loss': loss }) return render(request, 'account/account.html', … -
Send data to html and get choose part it back in the same views
I work on api weather project and by POST i send from website city name to views and I send back like possible locations (like "name" London have more than one city). I want choose one and send this one back to my view and in the same view still works on it (if is one location by coords we miss this stage). Code: cities_locations = [] if request.method == 'POST': form = CityForm(request.POST) if form.is_valid(): new_add_city = form.cleaned_data['name'] get_location_for_new_city = get_city_location(new_add_city) if len(get_location_for_new_city) == 1: pass #If is one location only else: for counter_cities in range(len(get_location_for_new_city)): city_location = { 'city': new_add_city, 'lat': get_location_for_new_city[counter_cities]['lat'], 'lon': get_location_for_new_city[counter_cities]['lon'], 'country': get_location_for_new_city[counter_cities]['country'], 'state': get_location_for_new_city[counter_cities]['state'], 'number': counter_cities, } cities_locations.append(city_location) print(cities_locations) form = CityForm() context = { 'cities_locations': cities_locations, 'form': form, } return render(request, 'weatherapp/yourweather.html', context) Can you help me with an example or some tips? Thank you for help. -
Pass the data to python script from frontend and fetch it back
Let's say I have trivial x and y variables (user input in frontend made in vue, Javascript) and we need to pass it to the python Script, which will return the result of calculation, let's say: Sum of x+y =... Multiplication of x*y = ... I know how to return these calculations either to the terminal output either to the file. Is there an easier way to use some API to read the response of the python script and show it on frontend to the user? Current system is: Frontend: vue Backend: Django with REST API. -
How do you select a particular object from a django model and use it to retrieve a url? (CS50 Project 2)
I am doing CS50 Project 2 and have a django model called Listing that has an object called Category that the user can pick using a dropdown list. All the categories are listed on the categories page and need to link to the categories_page page that displays all the listings in that category. Can you help me with the href and variable for the categories page to link it to the categories_page page? categories views.py def categories(request): return render(request, "auctions/categories.html",{ "Miscellaneous": Listings.objects.all().filter(category=Miscellaneous) }) categories.html (I need to link all the categories on this page to their own categories_page.) {% block body %} <h1>Categories</h1> <a href="{% url 'categories' Miscellaneous.category %}" style = "color: rgb(58, 58, 58);"><h5>Miscellaneous</h5></a> <h5>Movies and Television</h5> <h5>Sports</h5> <h5>Arts and Crafts</h5> <h5>Clothing</h5> <h5>Books</h5> {% endblock %} categories_page views.py def categories_page(request, category): listings = Listings.objects.all().filter(category=category) return render(request, "auctions/categories_page.html",{ "listings": listings, "heading": category }) categories_page.html {% block body %} <h1>{{ heading }}</h1> {% for listing in listings %} <a href="{% url 'listing' listing.id %}" style = "color: rgb(58, 58, 58);"> <img src ="{{ listing.image }}" style = "height: 10%; width: 10%;"> <h4 class = "text">{{ listing.title }}</h4> <h6>Description: {{ listing.description }}</h6> <h6>Category: {{ listing.category }}</h6> <h6>Price: ${{ listing.bid }}</h6> </a> {% … -
whats the correct way of using get_or_create with django?
how can it be that get_or_create results in: pymysql.err.IntegrityError: (1062, "Duplicate entry '...blabla' for key 'descriptor'") please have a look on how i call get_or_create: for key in keys: files_obj, created = Files.objects.get_or_create(file_path=key, file_name=Path(key).name, libera_backend=resource_object) if created: files_obj_uuids.append(files_obj.pk) resource_objects.append(resource_object.pk) thanks in advance -
(help) Django: no such table: users_company
i was trying to create a user's company profile but i got the following error: OperationalError at /admin/users/company/ Exception Value: no such table: users_company I think theres something wrong in my user' model.py because when i try to make migrations myapp> it shows No changes detected in app model.py: class Company(models.Model): name = models.CharField(max_length=100) about = models.TextField(gettext_lazy('about'), max_length=500, blank=True) role = models.CharField(max_length=100) address=models.CharField(max_length=100) contact=models.CharField(max_length=100) def __str__(self): return f'{self.user.username} Company' Does anyone can help me with this? I am new to django, lmk if you need any other information. Thanks ! -
How to automatically create subdomains after creating a tenants in Django on digital ocean
Please i have created a droplet in digital ocean. the project is a SaaS project which the user can create a subdomain for them automatically. when the sub domain is created, it is not recognize on the server. unless i go and add a subdomain in digital ocean. is there a way to create a sub domain without creating it at domain panel at the digital ocean dashboard -
How to set default size to photos in ckeditor container
So i am using ckeditor in my django project and i want to set the default size to the photos that i drag and drop into the ckeditor container because currently the photos are too big and it looks ugly. I would like them to be fixed 400px and not their original size. -
How to apply an arbitrary filter on a specific chained prefetch_related() within Django?
I'm trying to optimize the fired queries of an API. I have four models namely User, Content, Rating, and UserRating with some relations to each other. I'm going to the respective API to respond all of the existing contents alongside their rating count as well as a the score of given by a specific user to that. I used to do something like this: Content.objects.all() as a queryset but I realized that in the case of the huge amount of data tons of query will be fired. So I've done some efforts to optimize the fired querie using select_related and prefetch_related. However I'm dealing with an extra python searching that I hope remove that by a controlled prefetch_related() — applying a filter just for a specific prefetch in a nested prefetch and select. Here are my models: from django.db import models from django.conf import settings class Content(models.Model): title = models.CharField(max_length=50) class Rating(models.Model): count = models.PositiveBigIntegerField(default=0) content = models.OneToOneField(Content, on_delete=models.CASCADE) class UserRating(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE ) score = models.PositiveSmallIntegerField() rating = models.ForeignKey( Rating, related_name="user_ratings", on_delete=models.CASCADE ) class Meta: unique_together = ["user", "rating"] Here's what I've done so far: contents = ( Content.objects.select_related("rating") .prefetch_related("rating__user_ratings") .prefetch_related("rating__user_ratings__user") ) for c … -
Why is only the first React component rendering in my multi-page in Django app?
I am trying to render a secondary component to a different URL in my React frontend of my Django app. The URLs seem to be set up correctly, as the page title is changing accordingly and no errors are thrown, but the page itself is blank. My components are being loaded by importing in index.js in the components directory. #index.js import App from './components/App'; import Viz from './components/Viz'; #urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), path('viz/', views.getviz) ] For the simplicity of testing, I made the components a copy so I know it works. // App.js import React, { Component, Fragment } from 'react'; import ReactDOM from 'react-dom'; import Header from './layout/Header'; import Dashboard from './splits/Dashboard'; import Alerts from './layout/Alerts'; import { Provider } from 'react-redux'; import { Provider as AlertProvider } from 'react-alert'; import AlertTemplate from 'react-alert-template-basic'; import store from '../store'; //Alert Options const alertOptions = { timeout: 3000, position: 'bottom center' } class App extends Component { render() { return ( <Provider store={store}> <AlertProvider template={AlertTemplate} {...alertOptions}> <Fragment> <Header /> <Alerts /> <div className="container"> <Dashboard /> </div> </Fragment> </AlertProvider> </Provider> ); } } ReactDOM.render(<App />, document.getElementById('app')) The only difference with the other … -
How to use media files during deployment (django)?
Need help with managing media files during deployment. I've read several articles and documentation regarding to subject, but can't fix my particular site: tis, this and django documentation. Guess I've missed some obvious thing, or it could be misprint in code (link to media files). So, I've deployed site on django, using gunicorn and nginx. When users download some picture on site it save in media directory. models.py class News(models.Model): title = models.CharField(max_length=128) content = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True) settings.py DEBUG = False ... STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media/' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('news/', include('news.urls')), ... ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Try to add urlpatterns = [...]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) but it doesn't work for me. I guess it could be some problem in pass to media file. I've checked link in page - it's correct. <img src="photos/2022/05/10/kitten.jpg"> And this file is there. Can't download picture on page. How to download and use media files correct? I'll be glad to get advice or link to any documentation regarding to this subject. Thank you in advance. -
Django Blog - edit/delete user comments functions help needed pls
I am quite new to software development and quite new to django and python. I am currently working on a project to develop blog, which needs to have functions for users to edit and delete their own comments. Whilst I have developed the blog, I am struggling with getting the functions correctly coded and wired up to URLS file. I have added icons below user comments to either delete or edit their comments. My question is what is the correct code for creating functions in views file and also how can i correctly wire it up to URL file. I am not sure if I am missing any packages to get the edit/delete functionality developed. I have enclosed details of my model, views and urls files. Any guidance/support will be highly appreciated. Models file from django.db import models from django.contrib.auth.models import User from cloudinary.models import CloudinaryField STATUS = ((0, "Draft"), (1, "Published")) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts") updated_on = models.DateTimeField(auto_now=True) content = models.TextField() featured_image = CloudinaryField('image', default='placeholder') excerpt = models.TextField(blank=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) likes = models.ManyToManyField(User, related_name='blog_likes', blank=True) class Meta: ordering = ['-created_on'] def __str__(self): return … -
Reverse for 'add_comment' with keyword arguments '{'pk': ''}' not found. 2 pattern(s) tried:
This question searching internet for a week but i can't fix it Error_Message Reverse for 'add_comment' with keyword arguments '{'pk': ''}' not found. 2 pattern(s) tried: ['shopping_mall/top_cloth/(?P<pk>[0-9]+)/comment\\Z', 'top_cloth/(?P<pk>[0-9]+)/comment\\Z'] Error_60 line <a class="btn btn-success" href="{% url 'add_comment' pk=product.pk %}">add comment</a> MY urls urlpatterns = [ path('', views.index, name='index'), path('top_cloth/', views.top_cloth), path('top_cloth/<int:pk>/', views.cloth_detail, name='top_cloth_pk'), path('top_cloth/<int:pk>/comment', views.add_comment, name='add_comment'), path('top_cloth/<int:pk>/remove/', views.comment_remove, name='comment_remove'), path('top_cloth/<int:pk>/modify/', views.comment_modify, name='comment_modify'), ] My views def cloth_detail(request, pk): post = ProductList.objects.get(pk=pk) product = Comment.objects.order_by() return render( request, 'shopping_mall/cloth_detail.html', { 'post': post, 'product': product } ) def add_comment(request, pk): product = get_object_or_404(ProductList, pk=pk) if request.method == "POST": form = CommentFrom(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.product = product comment.save() return redirect('index', pk=product.pk) else: form = CommentFrom() return render(request, 'shopping_mall/add_comment.html', {'form':form}) Traceback Request Method: GET Request URL: http://127.0.0.1:8000/shopping_mall/top_cloth/1/ Django Version: 4.0.4 Python Version: 3.9.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'crispy_forms', 'shopping_mall', 'single_pages', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'django_summernote'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template D:\github\kys-shoppingmall\shopping_mall\templates\shopping_mall\cloth_detail.html, error at line 60 Reverse for 'add_comment' with keyword arguments '{'pk': ''}' not found. 2 pattern(s) tried: ['shopping_mall/top_cloth/(?P<pk>[0-9]+)/comment\\Z', 'top_cloth/(?P<pk>[0-9]+)/comment\\Z'] 50 : {{ comment.text|linebreaks }} 51 : </p> 52 : </dlv> 53 : {% endif %} … -
How to properly catch fetch request in django
I started studying django. I have js code that calls fetch when I click the button button = document.querySelector('.button') button.addEventListener('click', function(){ fetch('http://127.0.0.1:8000/test_fetch/', { method: 'GET', headers: { 'Content-Type': 'application/json', "X-Requested-With": "XMLHttpRequest", "HTTP_X_REQUESTED_WITH": "XMLHttpRequest" } }) }) <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button class="button">hello</button> {{ ajax }} <script src="{% static 'train_app/js/test_fetch.js' %}"></script> </body> class TestFetch(TemplateView): template_name = 'train_app/test_fetch.html' def get(self, request): ajax = request.headers data = { 'name': 'Yura', 'age': 20, 'list': [1,2,3,4], 'ajax': ajax } return render(request, self.template_name, context=data) I tried to catch the fetch request using request.META and request.headers. But they return to me information only about the first get request which is caused through urls.py. How do I get information that this was a fetch request and its Content-Type attribute.