Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python/Django - How to check url endpoint with an attached JWT?
I need to connect to a server from my Django application (Connection Test). The problem is that the server I'm trying to connect to only returns http_200 if an attached JWT token at the Authorization Header is given. How can I attach a JWT to a request I send from my application? Currently, I generate the JWT for the test connection like so: user = self.context['request'].user jwt_payload = jwt_payload_handler(user) access_token = str("Bearer " + jwt_encode_handler(jwt_payload)) Thanks in advance -
I want to get current url in settings.py file in django
I want to set an if condition in settings.py in my django app, to check the url and apply correct GOOGLE_RECAPTCHA_SECRET_KEY for the site. because of difference in local host and web server domin. I used requests._current_scheme_host but get an error: File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/registry.py", line 136, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
template tags is showing duplicate items in template
I am building a Blog App and I built a template tag to sort posts by likes. Template tag I working fine, But when I sort by likes then it is showing duplicate items according to likes. I mean, If a post got 3 likes then it is showing that post thee times. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=1000) body = models.CharField(max_length=1000) likes = models.ManyToManyField(User, related_name='likes') template_tags.py from django import template register = template.Library() @register.filter def sort(queryset, order): return queryset.order_by(order) views.py def posts(request): posts = BlogPost.objects.filter(user=request.user) context = {'posts':posts} return render(request, 'posts.html', context) posts.html {% load template_tags %} {% for post in posts|sort:'likes' %} {{post.title}} {% endfor %} I have also tried by using distinct() in both template_tags.py and views.py but it is making no effect on query. Any help would be much Appreciated. Thank You -
ERROR when i run pip install mssql-django
Running setup.py install for pyodbc ... error ERROR: Command errored out with exit status 1: command: 'C:\Users\Admin\env\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-8lp5uvpv\\pyodbc_fab15be00b0e459faaa8c78be119016d\\setup.py'"'"'; __file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-8lp5uvpv\\pyodbc_fab15be00b0e459faaa8c78be119016d\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-clbuf4z_\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\Admin\env\include\site\python3.10\pyodbc' cwd: C:\Users\Admin\AppData\Local\Temp\pip-install-8lp5uvpv\pyodbc_fab15be00b0e459faaa8c78be119016d\ Complete output (12 lines): running install running build running build_ext building 'pyodbc' extension creating build creating build\temp.win-amd64-3.10 creating build\temp.win-amd64-3.10\Release creating build\temp.win-amd64-3.10\Release\src C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DPYODBC_VERSION=4.0.32 -IC:\Users\Admin\env\include -IC:\Users\Admin\AppData\Local\Programs\Python\Python310\include -IC:\Users\Admin\AppData\Local\Programs\Python\Python310\Include -IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include /EHsc /Tpsrc\buffer.cpp /Fobuild\temp.win-amd64-3.10\Release\src\buffer.obj /Wall /wd4514 /wd4820 /wd4668 /wd4711 /wd4100 /wd4127 /wd4191 /d2FH4- buffer.cpp C:\Users\Admin\AppData\Local\Temp\pip-install-8lp5uvpv\pyodbc_fab15be00b0e459faaa8c78be119016d\src\pyodbc.h(19): fatal error C1083: Cannot open include file: 'windows.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.29.30133\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2 ---------------------------------------- ERROR: Command errored out with exit status 1: 'C:\Users\Admin\env\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-8lp5uvpv\\pyodbc_fab15be00b0e459faaa8c78be119016d\\setup.py'"'"'; __file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-8lp5uvpv\\pyodbc_fab15be00b0e459faaa8c78be119016d\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-clbuf4z_\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\Admin\env\include\site\python3.10\pyodbc' Check the logs for full command output. -
how to get specific field in serialiser with related_name by Django rest
i have model named ContactPhone and in the model link to Lead model with field lead_id and ralated_name phones class ContactPhone(models.Model): phone_number = PhoneNumberField(blank=True, default='') phone_type = models.CharField( max_length=100, blank=True, choices=ContactPhoneInterface.phone_number_types, default=PhoneNumbers.mobile.name ) contact_id = models.ForeignKey( Contact, on_delete=models.CASCADE, null=True, related_name='phones_c' ) lead_id = models.ForeignKey( Lead, on_delete=models.CASCADE, null=True, related_name='phones' ) by this serilizer class i got id of ContactPhone table, but i need got phone_number field in ContactPhone. class LeadListSerializer(serializers.ModelSerializer): class Meta: model = Lead fields = ( 'id', 'full_name', 'responsible_id', 'phones', 'emails', ) tried different options to solve this problem but it doesn't help. In the screenshot you can see response of this moment, id of ContactPhone -
how can i login with local url in Django administration and add user?
i tried for make a django userprofile but i can't Enter to login page there is my error when i enter to my local url TypeError at /account/login/ __init__() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/account/login/ Django Version: 3.2.9 Exception Type: TypeError Exception Value: __init__() takes 1 positional argument but 2 were given Exception Location: /home/pantea/.local/lib/python3.6/site-packages/django/core/handlers/base.py, line 181, in _get_response Python Executable: /usr/bin/python3 Python Version: 3.6.9 Python Path: ['/home/pantea/tutorial', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/pantea/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] here is my url file from django.conf.urls import url from django.contrib.auth.views import LoginView,LogoutView from accounts import views # from accounts import views urlpatterns = [ url(r'^$',views.home), url(r'^login/$', LoginView, {'template_name': 'accounts/login.html'}), url(r'^logout/$', LogoutView, {'template_name': 'accounts/logout.html'}), url(r'^register/$',views.register, name ='register'), url(r'^profile/$',views.view_profile, name ='view_profile'), url(r'^profile/edit/$',views.edit_profile , name ='edit profile'), ] and also my views file from django.contrib.auth.views import PasswordChangeDoneView from django.shortcuts import render,redirect from accounts.forms import NewUserForm from django.contrib.auth.models import User from django.contrib.auth.forms import PasswordChangeForm, UserChangeForm def home(request): numbers = [1,2,3,4,5] name = 'max' args = {'myName': name,'numbers':numbers} return render(request, 'accounts/home.html',args) def register(request): if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): form.save() return redirect('/account') else: form = NewUserForm() args = {'form':form} return render(request,'accounts/reg_form.html',args) def view_profile(request): args ={'user':request.user} return render(request,'accounts/profile.html',args) def edit_profile(request): … -
How to return ajax response as well as redirection in the views.py Django
I am trying to response the ajax when it successfully gets login but on the other hand, I want to check based on what user profile, it will redirect to the profile. Following is my function in views.py @csrf_exempt def login_view(request): next = request.GET.get('next') email = request.POST.get("email") password = request.POST.get("password") user = authenticate(username=email, password=password) if user is not None and user.is_active: login(request,user) if user.is_male: return redirect('/male_profile') elif user.is_female: return redirect('/female_profile') elif user.is_other: return redirect('/other_profile') data_json = {"error" : False, "errorMessage" : "Login Successful!"} return JsonResponse(data_json, safe=False) else: data_json={"error":True,"errorMessage":"Username or password is incorrect!"} return JsonResponse(data_json,safe=False) What the problem I am facing is it only return Ajax response or redirect to user based profile.. but not both together. Can anyone please help me out with how can I first send the response to ajax and then I redirect it to another page in views.py based on user profile. Thanks. -
How to mask IP address during verification email in Django-Rest-Framework backend?
I am building an application with Django-Rest-Framework as my backend and React-Native as front-end. When a user registers an activation email is generated which is something of this sort http://192.168.0.109:8000/api/auth/register/account-confirm-email/MTU:1mmAOY:3c3emcDMtURa4euwcg3a-Iwb3YYh3pdmM4Dme8emwN0/ Which gives out the IP-address of my hosted server. How do I mask this IP address - http://192.168.0.109? -
Connect Android emulator to Django webserver filles when running locally
In Django under my settings.py I have the following set MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' But for some reason my images aren't rendering on my Android Emulator when I look at the request being set I see for the first post on the screen the image url is: pycharm console: >>> serializer.data[0]['images'] PyDev console: starting. OrderedDict([('uuid', '9df1b544-611c-4f31-a4eb-8c48cb183d45'), ('image_url', '/media/images/user_6badb4b8-33ba-4bb9-aa9a-2e3afb359960/9df1b544-611c-4f31-a4eb-8c48cb183d45.jpg'), ('created', '2021-11-03T04:51:51.830285Z')]) Then I run console.log on the React Native side and the url is: React Native Code to set URL: const getImageUrls = () => { console.log(url + images.image_url); return [ { uri: url + images.image_url, }, ]; }; log statement LOG http://10.0.2.2:8000/media/images/user_6badb4b8-33ba-4bb9-aa9a-2e3afb359960/9df1b544-611c-4f31-a4eb-8c48cb183d45.jpg url is just a constant I have on the React Native side. It gets set dynamically depending on what mobile OS is running the emulator if it's Android it'll set to http://10.0.2.2:8000 and if it's IOS it'll set to http://127.0.0.1:8000. Why isn't the image showing up? I checked <project folder>/media/images/user_6badb4b8-33ba-4bb9-aa9a-2e3afb359960/7afbaf6f-67ef-4879-bd61-026cc947933b.jpg and the file I'm trying to render is definitely there. Why is React Native not rendering the image URL? -
how to restrict a user from using application to just one tab, device or windows at a time?
This is how i am doing right now my middleware.py class MySessionMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if request.user.is_authenticated: user, _ = LoggedInUser.objects.get_or_create(user=request.user) print(user) if not request.session.session_key: request.session.save() prev_session_key = user.session_key if prev_session_key: if prev_session_key != request.session.session_key: return JsonResponse("you already have a active session kindly logout from that", status=400, safe=False) user.session_key = request.session.session_key user.save() return response my models.py class LoggedInUser(models.Model): user = models.OneToOneField(User, related_name='logged_in_user', on_delete =models.CASCADE, null=True, blank=True) session_key = models.CharField(max_length=32, null=True, blank=True) my signals.py @receiver(user_logged_in) def when_user_logs_in(sender, user, request, **kwargs): print('user_logs_signal is called') LoggedInUser.objects.get_or_create(user=kwargs.get('user')) @receiver(user_logged_out) def when_user_logs_out(sender, user, request, **kwargs): print('user logs out signal iscalled') LoggedInUser.objects.get_or_create(user=kwargs.get('user')).delete() my errors my signals are not firing , i am currently testing the application via postman and using token based authentication, they are not firing thats why i am creating object inside middlware While using postman LoggedInUser object session key and request.session session key always comes out to be same my doubts I know when a user signs up from different tab, window a new session key is generated but what are the other scenarios when a new session key is generated . If the issues that i am facing is because i am using postman … -
Overwriting default login template
I'm trying to overwrite the default login template, but I'm getting an error. My apologies. I'm very weak with class based views. views.py from django.contrib.auth.views import LoginView class CustomLoginView(LoginView): #to override the template_name used in LoginView template_name = 'website/login.html' urls.py url(r'^access/login/$', website_views.CustomLoginView, name='auth_login'), When I visit this url, I get the following error: __init__() takes 1 positional argument but 2 were given Traceback C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars -
How do I make a POST request using axios in react?
I am having issues with the axios post request. When I click on the Button, nothing happens. What is supposed to happen is that the data that I enter into the input fields is submitted to the API. However, no redirect or anything happens when I click the Button. I am not sure whether the onClick function in the Button is never being triggered or whether the issue lies with the call of axios and then the useNavigate function. I have tried several different ways of using these function but none worked. It might be a syntactic issue as I am a beginner with react. Any help would be appreciated! Full Code: import axios from 'axios'; import React, { useState } from 'react'; import { Container, Button } from 'react-bootstrap'; import { useNavigate } from 'react-router-dom'; const AddContact = () => { const [first_name, setFirstName] = useState("") const [last_name, setLastName] = useState("") const [mobile_number, setMobileNumber] = useState("") const [home_number, setHomeNumber] = useState("") const [work_number, setWorkNumber] = useState("") const [email_address, setEmailAddress] = useState("") const history = useNavigate(); const AddContactInfo = async () => { let formField = new FormData(); formField.append('first_name', first_name) formField.append('last_name', last_name) formField.append('mobile_number', mobile_number) formField.append('home_number', home_number) formField.append('work_number', work_number) formField.append('email_address', email_address) … -
Getting the 'request' within Class Based View
I'm attempting to subclass the LoginView so that I can change the template_name that is part of LoginView. I've simplified my template_file_name function for the purposes of this example. def template_file_name(request, template_name, page_title): return template_name class CustomLoginView(LoginView): template_name = template_file_name(self.request, 'login.html', "Login") I'm getting this error: NameError: name 'self' is not defined Thanks! -
No 'Access-Control-Allow-Origin' on AWS
I have a Django REST API sitting in AWS ECS, and a VueJS frontend sitting in AWS S3, distributed by AWS CloudFront, trying to reach the backend, using Axios, and I keep getting variations of this error: Access to XMLHttpRequest at 'https://api.example.com/api/v1/auth/login/' from origin 'https://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. I am using he Django app django-cors-headers and I have configured it in my settings.py file as, from corsheaders.defaults import default_headers ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # REST 'rest_framework', 'rest_framework.authtoken', # testing 'coverage', # auth 'dj_rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', # cors 'corsheaders', ... ] SITE_ID = 1 MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] CORS_ORIGIN_WHITELIST = ( 'http://localhost:8080', 'https://example.com', 'https://www.example.com', ) CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = list(default_headers) + ( 'X-CSRFTOKEN', ) CSRF_COOKIE_NAME = "csrftoken" CSRF_TRUSTED_ORIGINS = [ "crowd-scout.com", ] On the frontend side, I've configured Axios as, import axios from 'axios'; export const HTTP = axios.create({ baseURL: "https://api.example.com", withCredentials: true, xsrfHeaderName: "X-CSRFTOKEN", xsrfCookieName: "csrftoken", }) And I'm trying to post data to my Django REST API as, import {HTTP} from '@/common/http' function getToken (form) { … -
Django view not returning HttpResponse Object
Trying to pass a user form for registration, however the view is not returning the user_form object. view def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data['password']) new_user.save() return render(request, 'account/register.html', {'new_user':new_user}) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form', user_form}) template {% block title%}Create an Account{% endblock %} {%block content%} <h1>Create an Account</h1> <p>Please, sign up using the following form</p> <form method="post"> {{user_form.as_p}} {% csrf_token %} <p><input type="submit" value="Create my account"><p/> </form> {%endblock%} url path('register/',views.register, name='register') error The view account.views.register didn't return an HttpResponse object. It returned None instead. -
the _imagingft c module is not installed amazon linux elasticbeanstalk
I have my app installed on AWS ElasticBeanstalk and it recently started giving me the following error: The _imagingft C module is not installed Traceback: File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/opt/python/current/app/grn/views.py", line 256, in get a = ean.save(item['bar'], options=d) File "/opt/python/run/venv/local/lib/python3.6/site-packages/barcode/base.py", line 65, in save output = self.render(options) File "/opt/python/run/venv/local/lib/python3.6/site-packages/barcode/codex.py", line 257, in render return Barcode.render(self, options, text) File "/opt/python/run/venv/local/lib/python3.6/site-packages/barcode/base.py", line 105, in render raw = self.writer.render(code) File "/opt/python/run/venv/local/lib/python3.6/site-packages/barcode/writer.py", line 227, in render self._callbacks["paint_text"](xpos, ypos) File "/opt/python/run/venv/local/lib/python3.6/site-packages/barcode/writer.py", line 372, in _paint_text font = ImageFont.truetype(self.font_path, self.font_size * 2) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/PIL/ImageFont.py", line 855, in truetype return freetype(font) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/PIL/ImageFont.py", line 852, in freetype return FreeTypeFont(font, size, index, encoding, layout_engine) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/PIL/ImageFont.py", line 187, in __init__ if core.HAVE_RAQM: File "/opt/python/run/venv/local/lib64/python3.6/site-packages/PIL/ImageFont.py", line 44, in … -
How i solve this django project admin operational problem
When I go to project admin, and do some update on the user and save it, it said this, it always like this I have tried it uninstall django and install it again, create the virtualenv again and new project again, and the result is the same, here's the traceback: It said OperationalError at /admin/auth/user/1/change/ no such table: main.auth_user__old Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/auth/user/1/change/ Django Version: 2.0.7 Python Version: 3.9.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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'] Traceback: File "C:\Users\user\Dev\trydjango\lib\site-packages\django\db\backends\utils.py" in _execute 85. return self.cursor.execute(sql, params) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 303. return Database.Cursor.execute(self, query, params) The above exception (no such table: main.auth_user__old) was the direct cause of the following exception: File "C:\Users\user\Dev\trydjango\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\contrib\admin\options.py" in wrapper 575. return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\contrib\admin\sites.py" in inner 223. return view(request, *args, **kwargs) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\contrib\admin\options.py" in change_view 1557. return self.changeform_view(request, object_id, form_url, extra_context) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\utils\decorators.py" in _wrapper … -
Trouble in getting params pk or id in Django rest framework has_permission
I have trouble in getting the params pk in my url, resources/<int:pk> in the my django rest framework permission. def has_permission(self, request, view): #extract params pk here pass I tried request.POST.get('pk') but it returns nothing. -
Is it possible to return redirect and return render together in django?
I want to refresh the page after returning a render. I can use return redirect to the same page, but I am confused if I can use both return render and return redirect in the same view function. Is there any other way to reload the page other than redirect without affecting the return render? -
Redirect to Admin Panel(Superuser) Login Page from views.py and template in Django
I am trying to keep a link of Django's prebuilds admin pannel on my website. My Project's urls.py: urlpatterns = [ path('', include('diagnosis.urls')), path('admin/', admin.site.urls, name='admin'), ] In Template: <a href="{% url 'admin' %}" class="btn btn-sm btn-primary px-6">Explore Admin Pannel!</a> But it gives errors like: NoReverseMatch at / Reverse for 'admin' not found. 'admin' is not a valid view function or pattern name. How can I fix this? I also tried redirecting to admin in views.py like: if (condition): return redirect('admin') This approach also does not work. How can I redirect in admin pannel from views.py also? -
python3 Django What is the difference
What is the difference BASE_DIR = Path(file).resolve().parent.parent BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) -
How to avoid the user from opening applications in two different tabs in Django
I want to know how can i make the user avoid from opening application from two different tabs , if user opens a new tab without logging out from previous tab or windows i need to show a error i didnt find any solution in django, help is highly appreciated -
I want to update multiple fields at a time in django model form forms
I have tried by filtering with roll number in views.py so I want to update all the marks fields from the form.py module so can anyone suggest me the best way of updating all the marks fields at a time. def marks_view(request, roll_number): return render(request, 'marks_entry.html') modles.py class NurseryResult(models.Model): roll_number = models.PositiveIntegerField(primary_key=True) student_name = models.CharField(max_length=50, blank=False) academic_Year = models.CharField(blank=True, max_length=50) nepali = models.PositiveIntegerField( blank=True) nepali_gpa = models.FloatField( blank=True) nepali_grade = models.CharField( blank=True, max_length=50) english = models.PositiveIntegerField( blank=True) english_gpa = models.FloatField(blank=True) english_grade = models.CharField(blank=True, max_length=25) math = models.PositiveIntegerField(blank=True) math_gpa = models.FloatField(blank=True) math_grade = models.CharField(max_length=50, blank=True) science = models.PositiveIntegerField(blank=True) science_gpa = models.FloatField(blank=True) science_grade = models.CharField(max_length=10, blank=True) oral_nepali = models.PositiveIntegerField(blank=True) oral_nepali_gpa = models.FloatField(blank=True) oral_nepali_grade = models.CharField(max_length=50, blank=True) oral_math = models.PositiveIntegerField(blank=True) oral_math_gpa = models.FloatField(blank=True) oral_math_grade = models.CharField(max_length=50, blank=True) oral_english = models.PositiveIntegerField(blank=True) oral_english_gpa = models.FloatField(blank=True) oral_english_grade = models.CharField(max_length=50, blank=True) hygiene = models.PositiveIntegerField(blank=True) hygiene_gpa = models.FloatField(blank=True) hygiene_grade = models.CharField(max_length=50, blank=True) grade = models.CharField(max_length=10, blank=True) gpa = models.FloatField(blank=True) -
How do I set default image based on gender in django-rest-framework?
I know there are several similar questions here, but none of them seem to resolve my issue. I am using Django-Rest-Framework. I am creating the user-profile simultaneously with the creation of user using signals. As my question is pretty self explanatory, this is my code models.py from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from django.db import models from django.conf import settings from PIL import Image GENDER_SELECTION = ( ('Male', 'Male'), ('Female', 'Female'), ) class CustomUser(AbstractUser): username = models.CharField(max_length=100, blank=True, null=True) email = models.EmailField(_('email address'), unique=True) gender = models.CharField(max_length=20, choices=GENDER_SELECTION) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'gender'] def __str__(self): return self.email class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') profile_pic = models.ImageField(upload_to='profile/', default='default.png', blank=True) def __str__(self): return f'{self.user.first_name} Profile' def save(self, *args, **kwargs): super(UserProfile, self).save(*args, **kwargs) uploaded_image = Image.open(self.profile_pic.path) if uploaded_image.height > 300 or uploaded_image.width > 300: output_size = (300, 300) uploaded_image.thumbnail(output_size) uploaded_image.save(self.profile_pic.path) This is what I have tried In models.py # ... def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) if self.profile_pic == 'default.png': if CustomUser.gender == 'Male': self.profile_pic = 'user_default_m.png' return self.profile_pic else: self.profile_pic = 'user_default_f.png' return self.profile_pic else: uploaded_image = Image.open(self.profile_pic.path) if uploaded_image.height > 300 or uploaded_image.width > 300: output_size = (300, 300) uploaded_image.thumbnail(output_size) uploaded_image.save(self.profile_pic.path) -
has_object_permission not working for detail action decorator?
I have an private action decorator for a User View. I want the action to be accessible only for the User in question. # views.py class UserViewSet(viewsets.ModelViewSet): queryset = get_user_model().objects.all() serializer_class = UserSerializer @action(detail=True, permission_classes=[IsSelf]) def private(self, request, pk): user = get_object_or_404(get_user_model(), pk=pk) data = UserPrivateSerializer(user).data return Response(data, status=status=HTTP_200_OK) # permissions.py class IsSelf(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj == request.user However, it looks like anyone can go to my private action - even if I explicitly declare IsSelf to be False: class IsSelf(permissions.BasePermission): def has_object_permission(self, request, view, obj): # This has no effect return False What am I missing?