Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extracting JSON from API response using .json() causes entire Django view to run multiple times
On a locally-hosted Django server, I'm using the requests module to send an request to an external API. For example, this code works fine: from django.http import HttpResponse import requests url = "https://rapidapi.com" apiKey = "MY-KEY" apiHost = "isitwater-com.p.rapidapi.com" headers = { "X-RapidAPI-Key": apiKey, "X-RapidAPI-Host": apiHost } locationParameters = { "latitude": "32", "longitude": "-26" } response = requests.get(url, headers=headers, params=locationParameters) print(response) def generatePage(request): return HttpResponse() And outputs what I'd expect: <Response [200]> But when I try to get the JSON from the (supposedly) successful request using .json(), the entire view runs twice and then throws an error. For example, this code: from django.http import HttpResponse import requests url = "https://rapidapi.com" apiKey = "MY-KEY" apiHost = "isitwater-com.p.rapidapi.com" headers = { "X-RapidAPI-Key": apiKey, "X-RapidAPI-Host": apiHost } locationParameters = { "latitude": "32", "longitude": "-26" } response = requests.get(url, headers=headers, params=locationParameters) print(response) print(response.json()) def generatePage(request): return HttpResponse() Outputs the following: <Response [200]> <Response [200]> Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Derek\Desktop\World Color Map\World_Color_Map-xFfPFma1\Lib\site-packages\requests\models.py", line 971, in json return complexjson.loads(self.text, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Derek\AppData\Local\Programs\Python\Python311\Lib\json\__init__.py", line 346, in loads return _default_decoder.decode(s) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Derek\AppData\Local\Programs\Python\Python311\Lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Derek\AppData\Local\Programs\Python\Python311\Lib\json\decoder.py", line 355, in raw_decode raise … -
django channel websocket failed
in my frontend which is built with vue js , alongside npm run serve ( running outside docker) the webscocket throw this error WebSocket connection to 'ws://localhost:8000/ws/notifications/' failed: My infrsactructure in docker , is looking like this Backend Code of Backend\Backend\asgi.py """ ASGI config for Backend project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack # Setting the default Django settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Backend.settings') # Import the WebSocket routing from your notifications app (not the Backend app) import notifications.routing # Create the ProtocolTypeRouter and include both the standard Django application # and the websocket application from the routing you've created in your notifications app. application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter(notifications.routing.websocket_urlpatterns) ), }) Code of Backend\Backend\wsgi.py """ WSGI config for Backend project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Backend.settings') application = get_wsgi_application() Code of Backend\Backend\settings.py """ Django settings for Backend project. Generated by 'django-admin startproject' using Django 4.2.4. For more information on … -
Django CORS error in media file | Nginx | React
I am trying to fetch image from my django server from my react app. Tried multiple configuration but nothing to rescue. It would be great if anyone could provide any insight or leads or something I am missing React Using react behind nginx (on client machine) so origin is always http://127.0.0.1 instead of http://localhost:3000 import axios from "axios" export async function getImageFromNginx() { const IMAGE_URL = "http://{SERVER_URL}/media/pages/64d3d8cb4d3bd545823595e4.png" const config = { mode: 'cors', // no-cors, *cors, same-origin headers: { 'Access-Control-Allow-Origin' : 'http://127.0.0.1', 'Access-Control-Allow-Credentials': 'true', }, auth: {'username': 'username', 'password':'password'}, withCredentials: true, } console.log(config) try{ const response = await axios.get(IMAGE_URL, config).then((res)=>console.log("in axios",res)) console.log('Call to Nginx') return await response.json(); }catch(error) { return []; } } Django in django settings for cors, have installed django-cors-headers and added app and middleware settings CORS_ALLOWED_ORIGINS = ['http://127.0.0.1'] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = ['Content-Type', 'Access-Control-Allow-Origin'] CORS_ALLOW_METHODS = ['GET', 'POST', 'OPTIONS'] Django Method to serve file using nginx (on server) def send_file(roots, file_name, disposition_type=None, default_file_name=None): valid = ['/download/{}'.format(root) for root in roots \ if os.path.exists(get_absolute_filename(root,file_name))] if valid: response = HttpResponse() response['Content-Type'] = '' if disposition_type is not None: end_user_filename = default_file_name and default_file_name or file_name response['Content-Disposition'] = "{}; filename={}".format( disposition_type, end_user_filename) response['X-Accel-Redirect'] = os.path.join(valid[0], file_name) response['Access-Control-Allow-Origin'] = 'http://127.0.0.1/' … -
Is returning list of app_name + codename of permissions for currently logged in user a security risk in django?
I have an app named "todos" and inside this app I have a permission code named "add_todo", Is it a bad idea to return app name + code name(todos.add_todo) as a mechanism to control which buttons and UI to show to user in the Frontend? I currently wrote an endpoint that returns all of the user's permissions as a list in this format: "app_name.permission__codename". I was wondering whether this would pose a security risk or not. Also it's worth noting that only currently logged in user can see his/her own permissions. -
Django cannot import name 'Response' from 'rest_framework'
I have a Django rest_framework project which is working fine. I am using pipenv and used it to install django_rest_framework. I can import functions such as serializer from rest_framework and use them without problems. I would like to use rest_framework's Response class as givenhere and described here, so I wrote from rest_framework import Response This is not faulted by VSCode's syntax checks. However, when I start the server I receive the message cannot import name 'Response' from 'rest_framework' All help welcome -
Is it possible to stop the PyCharm debugger from exiting after an exception from Django shell?
I started the PyCharm debugger with python manage.py shell so I could interactively debug my Django project. However, if I run into an error, the debugger just exits. If I run python manage.py shell directly in a terminal this is not an issue. The same error will happen, but it doesn't just kick me out of the shell. Is there a way to have the same functionality while debugging in PyCharm? -
Secure way to use API keys and Client Secrets in the frontend of a django app
I have a django application with a react frontend. The frontend connects to a websocket server at one point with the following code client.send('PASS ${password}');. What is a safe secure way to keep that password in the backend and then access it when I need to connect to the websocket. Currently I just have it set as an environment variable and use an api request to my REST API to retrieve it when I want to connect. This works but I feel like its not the best way to do this. -
Deploying a Django web application that uses SQL Server
I am getting ready to deploy my Django app, with a SQL Server backend, but I'm not sure where to even start. I've done a lot of research and reading, but I have not found any clear path to follow. Does it have to be hosting with AWS, Azure, or the like? Can it instead be hosted on my Windows Server (on-prem)? -
Apache2 not starting on Debian server after following dev.to guide
I am trying to host my Django website on my Debian 12 server but I am encountering an error even after following the guide on dev.to. The error is that Apache2 is not starting and is showing the following message: Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xeu apache2.service" for details. After running systemctl status apache2.service it is showing that without matching section. I have tried the following steps to fix the problem: I have checked that the Apache2 service is not running everytime restarting the server. I have checked that the port 80 is not being used by another process. I have cleared the Apache2 configuration files. I have reinstalled Apache2. However, I am still getting the same error. Can anyone help me to fix this problem? <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) … -
Django with djangorestframework-simplejwt results in POST error 403: Forbidden (CSRF cookie not set.): on /api/token/
i want to set up a simple Django Backend with a rest api. If i'am trying to login with the supplied urls, but everytime i try to login i get a 403 error: CSRF Verficatoin failed. CSRF cookie not set. This are my used apps: Django==4.1.10 # Rest Framework djangorestframework==3.14.0 djangorestframework-api-key==2.3.0 djangorestframework-simplejwt==5.2.2 markdown==3.4.4 # CORS for rest api django-cors-headers==4.2.0 and my settings: ALLOWED_HOSTS='*, localhost' ALLOWED_ORIGINS='http://*, https://*' CSRF_COOKIE_AGE=31449600 CSRF_COOKIE_NAME='csrftoken' CSRF_USE_SESSIONS=False CSRF_TRUSTED_ORIGINS='http://*, https://*' CSRF_COOKIE_HTTPONLY=False CSRF_COOKIE_SECURE=False CSRF_COOKIE_DOMAIN = None CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN' CORS_ALLOW_ALL_ORIGINS=False CORS_ALLOWED_ORIGIN_REGEXES='' CORS_ALLOWED_ORIGINS='http://localhost:8888, http://127.0.0.1:8888' the server runs on port 8888 with the command: python3 manage.py runserver 0.0.0.0:8888 The Middleware: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] and the Settings for the Rest Framework: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework_api_key.permissions.HasAPIKey', 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', # 'rest_framework.authentication.TokenAuthentication', # 'rest_framework.authentication.SessionAuthentication', # 'rest_framework.authentication.BasicAuthentication', # only for testing ], "DEFAULT_PARSER_CLASSES": [ "rest_framework.parsers.JSONParser", "rest_framework.parsers.FormParser", "rest_framework.parsers.MultiPartParser", ], } and these urls are in the introduction of the app: path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'), and now, if i try following request: curl \ -X POST \ -H "Content-Type: application/json" \ -d '{"username": "my_username", "password": "my_password"}' \ http://localhost:8888/api/token/ i get the error code 403, as described … -
Django a problem that chatgpt can not solve :-) i am newbie [closed]
`Django 4.2.3 I have a problen when i try to create a window. First i create a quote then when i want to add a window to the quote, the connection field between class Quote and class Windows is "quot" field. This field is shown to the user at the moment the user want to create a new window At the moment the form is sent to the function function create_window do not enter in the if form.is_valid() so it gives an error "This field is required" <ul class="errorlist"><li>quot<ul class="errorlist"><li>This field is required.</li></ul></li></ul> VIEW.py def create_window(request, quote_id): quote = get_object_or_404(Quote, pk=quote_id) if request.method == 'POST': form = WindowForm(request.POST) print(form.errors) if form.is_valid(): window = form.save(commit=False) window.quot = quote # Assign the related Quote form.cleaned_data['quot'] = quote window.save() return redirect('detail_quote', pk=quote_id) else: form = WindowForm(initial={'quot':quote}) context = {'form':form} return render(request, 'create_window.html', context) create_window.html <!DOCTYPE html> <html> <head> <title>Create New Window</title> </head> <body> <h1>Create New Window</h1> <form method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Create"> </form> </body> </html> MODELS.py class Quote(models.Model): quote_number = models.PositiveBigIntegerField(null=True, blank=True, unique=True) client = models.ForeignKey(Client, on_delete=models.CASCADE) slug= models.SlugField(max_length=100, unique=True) def save(self, *args, **kwargs): if not self.quote_number: self.quote_number = generate_next_quote_number() super(Quote, self).save(*args, **kwargs) def __str__(self): return f"Nro Presupuesto: {self.quote_number}" def … -
pydev debugger: unable to find translation for: (please revise your path mappings)
I have a problem using debugpy with vscode on Windows with the repository on a local server. I have a dockerized django app with the following dockerfile and docker-compose: FROM python:3.6.15-slim-bullseye ARG ENVIRONMENT=master # Python logs to STDOUT ENV PYTHONUNBUFFERED=1 \ PIP_NO_CACHE_DIR=off \ PIP_DISABLE_PIP_VERSION_CHECK=1 \ TZ=America/Santiago \ DEBIAN_FRONTEND=noninteractive WORKDIR /app COPY requirements.txt . RUN set -x \ && buildDeps=" \ git \ build-essential \ libpq-dev \ libssl-dev \ locales \ gnupg \ wget \ " \ && runDeps=" \ pkg-config \ unzip \ lsb-release \ libcairo2-dev \ libpangocairo-1.0-0 \ " \ && apt-get update \ && apt-get install curl tzdata -y \ && apt-get install -y --no-install-recommends $buildDeps $runDeps \ && ln -fs /usr/share/zoneinfo/${TZ} /etc/localtime \ && dpkg-reconfigure -f noninteractive tzdata \ && locale-gen es_CL.UTF-8 \ && sed -i -e 's/# es_CL.UTF-8 UTF-8/es_CL.UTF-8 UTF-8/' /etc/locale.gen \ && wget http://dev.mysql.com/get/mysql-apt-config_0.8.26-1_all.deb \ && echo 'mysql-apt-config mysql-apt-config/select-product select Ok' | debconf-set-selections \ && dpkg -i mysql-apt-config_0.8.26-1_all.deb \ && rm mysql-apt-config_0.8.26-1_all.deb \ && apt-get update \ && apt-get install -y libmysqlclient-dev \ && pip install -r requirements.txt --no-dependencies \ && apt-get clean \ && apt-get autoremove -y \ && rm -rf /var/lib/apt/lists/* \ && rm -Rf /tmp/* version: "3.8" services: django: image: "django:dev" build: … -
Change the url that search_form hits during search in Django admin changelist page
I have a custom implementation for the changelist page in the Django admin, such that a custom query parameter is provided in the url. For example, it is like this: admin/app_label/model_name/?custom_parameter=value Although I have made the changes I needed to filters and action to work using this url, I have an issue with search. Hitting the search in changelist page, I see that it hits the normal url admin/app_label/model_name/ . This is an issue since I need the custom parameter in the GET request to appropriately handle things in the django admin backend. I have also seen the search_form.html file that renders the search element. Is there a way to define the url that the search will hit, either from the backend or somehow via the javascript of the search_form.html, since I also have the custom_parameter provided in the context of the html page? -
(admin.E030) The value of 'prepopulated_fields["slug"][0]' refers to 'name', which is not a field of 'store.Category'
I'm making an ecommerce app with Django. The command terminal keeps popping the above error whenever I try to run a command with it. models.py: from django.db import models from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length = 150, db_index = True), slug = models.SlugField(max_length = 150, unique = True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name class Product(models.Model): category = models.ForeignKey(Category, related_name = 'product', on_delete = models.CASCADE) created_by = models.ForeignKey(User, on_delete = models.CASCADE, related_name= 'product_creator') title = models.CharField(max_length = 150) author = models.CharField(max_length = 150, default = 'admin') description = models.TextField(blank = True) image = models.ImageField(upload_to = 'images/') slug = models.SlugField(max_length = 150) price = models.DecimalField(max_digits = 4, decimal_places = 2) in_stock = models.BooleanField(default = True) is_active = models.BooleanField(default = True) created = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now = True) class Meta: verbose_name_plural = 'Products' ordering = ('-created',) def __str__(self): return self.title admin.py: from django.contrib import admin from .models import Category, Product @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ['name', 'slug'] prepopulated_fields = {'slug' : ('name',)} @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ['title', 'author', 'slug', 'price', 'in_stock', 'created', 'updated'] list_filter = ['in_stock', 'is_active'] list_editable = ['price', 'in_stock'] prepopulated_fields = {'slug' : ('title',)} It's also worth noting that for … -
Django gunicorn nginx 111 connection refused while connecting to upstream
A fresh Django application is running on the Debian server, configured via gunicorn and nginx. After setup i tried to connect to it, but i can reach it only by server ip. The only error i found is in nginx log: 2023/08/10 16:08:48 [error] 19252#19252: *9 connect() failed (111: Connection refused) while connecting to upstream, client: x.xx.xxx.xxx, server: mydomain.ru, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "xxx.xxx.xxx.xxx:80" or sometimes host: "mydomain.ru" my nginx configuration: server { listen 80; server_name mydomain.ru; access_log /var/log/nginx/example.log; location /static/ { root /home/alex/myproject; expires 30d; } location /media/ { root /home/alex/myproject; expires 30d; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } my gunicorn.conf bind = '127.0.0.1:8000' workers = 2 user = 'alex' timeout = 120 mydomain.ru is in django settings ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS, but anyway, when i python3 manage.py runserver django shows some activity only accessing it by server ip. when i stop project with supervisor there are no other servers in netstat -tpln Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:10050 0.0.0.0:* LISTEN 324/zabbix_agentd tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 20083/nginx: master tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 358/sshd tcp … -
Django - try to refresh the page when the basket is empty
I'm sort of new with Django and I ran through an issue. I'm doing a E-commerce project. I'm sending a post request to django basket view and return the function back with HttpResponse in order to change the product details in the basket. The issue is: once the product quantity went from 1 to 0, the page is not displaying an empty basket in the default way. Is that impossible to return a HttpResponseRedirect and JsonResponse at the same time, right? Do you guys have any idea how to do it?Can I do something in the ajax part to refresh the basket page? Here's are the codes: Views.py def basket_delete(request): basket = Basket(request) basketqty = basket.__len__() if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) basket.delete(product=product_id) basketqty = basket.__len__() #calculating the basket quantity baskettotal = basket.get_total_price() response = JsonResponse({'qty':basketqty, 'subtotal':baskettotal}) return response Ajax in the html template <script> $(document).on("click", ".delete-button", function (e) { e.preventDefault(); var prodid = $(this).data("index"); $.ajax({ type: "POST", url: '{% url "basket:basket_delete" %}', data: { productid: $(this).data("index"), csrfmiddlewaretoken: "{{csrf_token}}", action: "post", }, success: function (json) { $('.product-item[data-index="' + prodid + '"]').remove(); if (json.qty == 0) { total = 0 subtotal = 0 } else { total = (parseFloat(json.subtotal) + … -
Uncaught (in promise) TypeError: this.resolveComponent is not a function | Inertia, Django & Vue
I have a Vue page (FormTest.vue): <template> {{ user }} <form @submit.prevent="submit"> <input type="text" v-model="user.first_name" label="First name" /> <input type="text" v-model="user.last_name" label="Last name" /> <button type="submit">Save</button> </form> </template> <script setup lang="ts"> import {User} from '@/types/users'; import {router} from '@inertiajs/vue3'; const props = defineProps<{ user: User; }>(); function submit() { router.post('/form-test', { first_name: props.user.first_name, last_name: props.user.last_name, }); } </script> Then a Django view: def form_test(request): user_instance = get_object_or_404(CustomUser, pk=request.user.id) if request.method == "POST": form_data = dict_to_querydict(json.loads(request.body)) form = CustomUserForm(form_data) if form.is_valid(): user_instance.first_name = form.cleaned_data["first_name"] user_instance.last_name = form.cleaned_data["last_name"] user_instance.save() return render( request, "FormTest", props={"user": CustomUser.objects.get(id=request.user.id)}, ) The update works, it correctly stores the values in the db and on the page I see them change within the {{ user }} as well. Just running into an error in the console upon submission: router.ts:452 Uncaught (in promise) TypeError: this.resolveComponent is not a function at C.setPage (router.ts:452:33) at router.ts:390:21 setPage @ router.ts:452 (anonymous) @ router.ts:390 XMLHttpRequest.send (async) dispatchXhrRequest @ xhr.js:251 xhr @ xhr.js:49 dispatchRequest @ dispatchRequest.js:51 request @ Axios.js:148 wrap @ bind.js:5 visit @ router.ts:342 post @ router.ts:527 submit @ FormTest.vue:20 (anonymous) @ runtime-dom.esm-bundler.js:1328 callWithErrorHandling @ runtime-core.esm-bundler.js:158 callWithAsyncErrorHandling @ runtime-core.esm-bundler.js:166 invoker @ runtime-dom.esm-bundler.js:278 Show 13 more frames Somewhere within the render function something goes … -
frozen importlib._bootstrap error i can't import that package
[ In the main also have some isue how can i clear the bug .help me this is my first website . -
Having two users....here i want to one user does'nt allow to edit and delete process and another user allows all in django
```Created Website in Django...Here the user can login and use the pages....Here I'm having two users first user can access the whole pages I mean they can View,Edit and Delete operations but another user allows only View only how? Can anyone explain me No,I don't Know how to do. -
NoReverseMatch at / Reverse for 'conference' not found. 'conference' is not a valid view function or pattern name
I'm working on my project and I got stuck on this issue and have no ideas how to solve it. <li class="nav-item"> <a class="nav-link {% if 'conference' in segment %} active {% endif %}" href="{% url 'conference' %}"> <i class="ni ni-collection text-blue"></i> <span class="nav-link-text">Конференц зал</span> I got error here. my views.py from django import template from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.urls import reverse @login_required(login_url="/login/") def index(request): context = {'segment': 'conference'} html_template = loader.get_template('conference/conference.html') return HttpResponse(html_template.render(context, request)) @login_required(login_url="/login/") def pages(request): context = {} # All resource paths end in .html. # Pick out the html file name from the url. And load that template. try: load_template = request.path.split('/')[-1] if load_template == 'admin': return HttpResponseRedirect(reverse('admin:index')) context['segment'] = load_template html_template = loader.get_template('home/' + load_template) return HttpResponse(html_template.render(context, request)) except template.TemplateDoesNotExist: html_template = loader.get_template('home/page-404.html') return HttpResponse(html_template.render(context, request)) except: html_template = loader.get_template('home/page-500.html') return HttpResponse(html_template.render(context, request)) my urls.py of my app from django.urls import path from .views import * urlpatterns = [ path('conference/', index, name='conference'), # Other URL patterns for your app's views... ] All my apps are in apps folder. I have one folder for all templates of apps and inside of that I have templates with … -
unable to access admin panel django
I have changed my views and more specifically the request-mappings to "spring-like request mappings for djang". There for I had to change my urls to work as follows link to Pypi documentation of spring-like request mappings for django. After that change tho, Im unable to access admin panel, even tho I have it registered in my project urls.py. Project urls.py: from myapp.views import UserView from django.contrib import admin urlpatterns = UrlPattern() urlpatterns.register(UserView) urlpatterns += [path('', include('myapp.urls'))] urlpatterns += [path('admin/', admin.site.urls)] Of course I have it imported in my settings, it used to work before that url refactoring I did. I just want to mention that I like this way of work and my question is specifically how do I fix the access to the admin panel, if it is possible ofc. The error Im getting is: The current path, admin/, didn’t match any of these. -
Using the Tnymce Responsive File Manager in Django
How can I use Tnymce File Responsive Manager in Django? I can't use it in any way! I tried writing some code but it didn't work. Please help me! ` Full content {{ new.full_info }} ` <script type="text/javascript"> tinymce.init({ selector: 'textarea#myTextarea', plugins: [ 'advlist', 'autolink', 'link', 'image', 'lists', 'charmap', 'preview', 'anchor', 'pagebreak', 'searchreplace', 'wordcount', 'visualblocks', 'visualchars', 'code', 'fullscreen', 'insertdatetime', 'media', 'table', 'emoticons', 'template', 'help', ], toolbar: 'undo redo | styles | bold italic | alignleft aligncenter alignright alignjustify | ' + 'bullist numlist outdent indent | insertfile link image | print preview media fullscreen | ' + 'forecolor backcolor emoticons | help', menu: { favs: { title: 'My Favorites', items: 'code visualaid | searchreplace | emoticons' } }, menubar: 'favs file edit view insert format tools table help ', tinydrive_upload_path: '/upload', // content_css: 'css/content.css', file_picker_callback: function(callback, value, meta) { if (meta.filetype === 'file') { // Fayl tanlash dialogini ochish tinymce.activeEditor.windowManager.openUrl({ url: '/admin/filepicker/', // Fayl tanlash uchun Django view URL title: 'Fayl tanlash', onMessage: function(dialogApi, details) { // Tanlangan faylni fayl tanlash dialogidan olib kelib, callback ga uzatish callback(details.file); dialogApi.close(); } }); } } }); </script> -
drf-yasg : How can we use doc-string of different methods other than standard http method for swagger api documentation
I am using drf-yasg and django-rest-framework. I am having one common parent class which is having all http method defined, which will be inherited in sub-classes where business logic methods will be overided. I want subclass overrided method docstring in swagger api documentation class BaseAPIView(APIView): """ Base API View. """ def get(self, request): """ Base API get method description. """ result = self.process_get() # Call the overridden method return Response(result) def process_get(self): raise NotImplementedError class DerivedAPIView(BaseAPIView): """ Derived API View. """ def process_get(self): """ List all items. """ items = [ {"name": "Item 1", "description": "Description of Item 1", "price": 10.99}, {"name": "Item 2", "description": "Description of Item 2", "price": 20.99} ] return Response(items) Here in swagger document for DerivedAPIView get method i want DerivedAPIView process_get method docstring as api documentation. -
DRF: Redirect unauthenticated users to login form
Is there a way to redirect users who didn't pass through rest_framework.permissions.IsAuthenticated permission to login page? I can achieve it by rewriting dispatch method of my ApiView and adding extra NotAuthenticated exception catcher, but is there a softer way to do this? class IndexView(APIView): permission_classes = [ IsAuthenticated, ] def get(self, request, format=None): ... def dispatch(self, request, *args, **kwargs): self.args = args self.kwargs = kwargs request = self.initialize_request(request, *args, **kwargs) self.request = request self.headers = self.default_response_headers # deprecate? try: self.initial(request, *args, **kwargs) # Get the appropriate handler method if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed response = handler(request, *args, **kwargs) except NotAuthenticated: "<---- added by me" return redirect("/login") except Exception as exc: response = self.handle_exception(exc) self.response = self.finalize_response(request, response, *args, **kwargs) return self.response -
Change city slug on django-cities to only have city name with hyphens
I am using django-cities in my project, and I am stuck at an issue which I can't seem to be able to overcome on my own. I basically need the slug field of the City model to only list the city name, with hyphens if the name has spaces. This is the standard behaviour of the Country model slug. Instead, the City model returns something like [id]-[city]. So the slug for Country is: United-Arab-Emirates But the slug for City is: 292968-Abu-Dhabi I think I've identified where this is generated in django-cities. The BaseCity model has a field slug_contains_id which is set to True, then the slugify method adds it to the slug before the city name: django-cites.models: class BaseCity(Place, SlugModel): slug_contains_id = True name_std = models.CharField(max_length=200, db_index=True, verbose_name="standard name") country = models.ForeignKey(swapper.get_model_name('cities', 'Country'), related_name='cities', on_delete=SET_NULL_OR_CASCADE) region = models.ForeignKey(Region, null=True, blank=True, related_name='cities', on_delete=SET_NULL_OR_CASCADE) subregion = models.ForeignKey(Subregion, null=True, blank=True, related_name='cities', on_delete=SET_NULL_OR_CASCADE) location = PointField() population = models.IntegerField() elevation = models.IntegerField(null=True) kind = models.CharField(max_length=10) # http://www.geonames.org/export/codes.html timezone = models.CharField(max_length=40) class Meta: abstract = True unique_together = (('country', 'region', 'subregion', 'id', 'name'),) verbose_name_plural = "cities" @property def parent(self): return self.region def slugify(self): if self.id: return '{}-{}'.format(self.id, unicode_func(self.name)) return None But what I'm unable to …