Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How i can change password on Django
i wanna change django password without using the default view , i passed the PasswordChangeForm to the view but i didnt know how to post it class UpdateUserView(UpdateView): model = User template_name = 'test.html' form_class = UserUpdateForm success_url = '/' def get_context_data(self, *args, **kwargs): data = super().get_context_data(**kwargs) data['PasswordChangeForm'] = PasswordChangeForm(self.request.user) return data def post(self, request, *args, **kwargs): change_pw = User(password=request.POST.get('id_new_password1')) change_pw.save() def get_object(self): return self.request.user -
Django Model method test
I have model like this: class Users(models.Model): pin = models.CharField(max_length=16, unique=True) name = models.CharField(max_length=64) surname = models.CharField(max_length=64, blank=True, null=True) patronymic = models.CharField(max_length=64, blank=True, null=True) def get_full_name(self): name = self.name surname = self.surname if self.surname is None: surname = '' if self.name is None: name = '' return str(name) + ' ' + str(surname) I want to write a test case for get_full_name method. Currently I wrote something like this: class TestUsersModel(TestCase): def setUp(self): self.data1 = Users.objects.create(name='Bob', pin='1') self.data2 = Users.objects.create(surname='Alex', pin='2') def test_users_model_entry(self): data = self.data1 self.assertTrue(isinstance(data, Users)) def test_users_full_name_only_name(self): data = self.data1.get_full_name() self.assertEquals(data,'Bob ') def test_users_full_name_only_surname(self): data = self.data2.get_full_name() self.assertEquals(data,' Alex') but when I check with coverage it says me that I have to write test case for this: What I am missing here? -
Have to display data, from django using form and optional value
I am trying to display data from my models to HTML page by using form and field optional(value). Bat noting is displaying to my HTML page and the filter is not working: This is my modles.py file: from django.contrib.auth.models import User from django.db import models class TaskCategory(models.Model): category_title = models.CharField(max_length=50) def __str__(self): return self.category_title class Post(models.Model): task_title = models.CharField(max_length=250) task_discription = models.CharField(max_length=250) task_category = models.ForeignKey(TaskCategory, on_delete=models.CASCADE) recommended_tools = models.CharField(max_length=250) budget = models.CharField(max_length=250) def __str__(self): return self.task_title + ' | ' + self.task_discription + ' | ' + str(self.task_category) + ' | ' + self.recommended_tools + ' | ' + self.budget urls.py file: from django.urls import path from .views import PostPageView urlpatterns = [ path('PostPage/', PostPageView, name ='post_page'), ] view.py file: from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView,DetailView from .models import Post, TaskCategory from django.shortcuts import render, get_object_or_404 def is_valid_queryparam(param): return param != '' and param is not None def PostPageView(request): post = Post.objects.all() category = TaskCategory.objects.all() category = request.GET.get('category') if is_valid_queryparam(category) and category != 'Choose...': post = post.filter(category_title=category) context = { 'post': Post.objects.all(), 'category': TaskCategory.objects.all() } return render(request, "post_page.html", context) -
Access to users update and delete views in allauth is accessible to other users
Just followed through all the allauth documentation setting up a site with user registration. Subclassed it to extend the fields. All working fine except that I can signup with a new account and delete/update any other account just by changing the url to supply their user id instead the logged in user. I must be missing a setting that I can't find documented anywhere - I'm really surprised this is the default behaviour. I've added a slug field to the user model with a random alphanumeric and changed the views to use this - mostly because I hate using pk's in urls, particularly in a situation that potentially exposes user accounts like this. This mitigates the risk at least but it's still open. Any allauth developers out there know what solution to this would be? -
Django After LDAP Authentication leads to {"detail":"Authentication credentials were not provided."}
I know that issue around '"detail": "Authentication credentials were not provided.' was in a similar way already posted several times. However, the answers I found o far did help me. I have a Django app that I would like to deploy. In this App I have several Rest-APIs defined such as class MyViewSet(ReadOnlyModelViewSet): ... permission_classes = (permissions.IsAuthenticated,) AS Authentification Backend I use "django_python3_ldap.auth.LDAPBackend" with the following setting in the setting.py file AUTHENTICATION_BACKENDS = ( 'django_python3_ldap.auth.LDAPBackend', ) LDAP_AUTH_URL = "ldaps://XXX.XXX.XXX.XXX:XXX" LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory_principal" # The LDAP search base for looking up users. LDAP_AUTH_SEARCH_BASE = "ou=XXX,dc=XXX,dc=XXX" # LDAP Credtials LDAP_AUTH_CONNECTION_USERNAME = XXX LDAP_AUTH_CONNECTION_PASSWORD = XXX # Adapt filter def custom_format_search_filters(ldap_fields): search_filters = [("(&(objectClass=user)(sAMAccountName=" + '{user}' + "))").format(user=user_id)] return search_filters LDAP_AUTH_FORMAT_SEARCH_FILTERS = custom_format_search_filters On my locale windows machine, everything works well. After successful authentication, I can trigger the events that raise the rest-get call. I then deployed the project on an EC2 Amazon Linux 2 AMI machine. Here I added to the nginx setting the following code: server { # URL that is communicating with the client listen XXX.XXX.XXX.XXX:9000; server_name XXX.XXX.XXX.XXX; # Locatio for the logs access_log /data/webapp_project/logs/nginx-access.log; error_log /data/webapp_project/logs/nginx-error.log; # Gunicorn IP+Proxy location / { proxy_pass http://127.0.0.1:8001; proxy_set_header Host $http_host; } location … -
how to find the distance between 1 user and other users in django rest framework
i am making an app which tracks the users location when they login, when they search for other users in their area i want to be able to calculate the distance between the users location and other users and only display users who are in a certain mile radius which the user can choose . I would like to put it in a class based list api view as a filter but i don't know how to do it. I have probably not explained it in the best way so please let me know if you don't understand my question -
No 'Access-Control-Allow-Origin' header is present on the requested resource Occurs only when send video as request data Django + React
I am using django for backend/rest api and React for frontend. Both are on different servers. My Django Settings: CORS_ALLOWED_ORIGINS = [ "http://localhost:8000", "http://localhost:3000", "http://127.0.0.1:3000", "https://example.com" ] CORS_ORIGIN_WHITELIST = ( "http://localhost:8000", "http://localhost:3000", "http://127.0.0.1:3000", "https://example.com" ) On example.com / React Frontend, when I send a request to the API, it gives me status code 200, unless expected errors. But when I send video as request data to the API, it is giving me the following error Access to XMLHttpRequest at 'https://backdoor.example.com/api/content/post/' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. This error only occurs if I try to send video as request data if the video is null it gives me no error -
Wrong links inside django app behind nginx reverse proxy
I am having this issue where i want to deploy my django app following way. Imagine some intranet virtual machine with some nginx configuration where all requests to https://something.smth/django/ will be forwarded to docker container where i have another nginx and django app. Home page is fine and django app normaly loads but when i click on some link django will set url to https://something.smth/some-link/ instead of https://something.smth/django/some-link/. I have seen lot of questions here but none of them solved my problem. I have very little knowledge about nginx and I would be very grateful if you could help me. Thank you! Here is my nginx configuration inside docker container (i dont have control over nginx in VM) upstream app { server web:8000; } server { listen 80; if ($http_x_forwarded_proto = 'http'){ return 301 https://$host$request_uri; } client_max_body_size 5000M; location / { proxy_pass http://app; proxy_read_timeout 10h; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header SCRIPT_NAME /ecg; } location /static/ { alias /usr/src/app/static/; } location /media/ { alias /usr/src/app/media/; } } and docker-compose if that helps version: '3.7' services: web: build: ./app command: daphne -b 0.0.0.0 -p 8000 django.asgi:application volumes: … -
TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method Django
How to solve this error : TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method'? I want to return cart length in json. def add_cart(request, product_id): cart = Cart(request) product = Product.objects.get(id=id) produit = serializers.serialize('json', [produit]) form = CartProductForm(request.POST) if request.method == 'POST' and request.is_ajax(): if form.is_valid(): cd = form.cleaned_data cart.add(product=product, qty=cd['qty'], update_qty=cd['update_qt'] ) card = serializers.serialize('json', cart) return JsonResponse({'status': 'success', 'cart_length': card}) Error: Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\decorators\http.py", line 40, in inner return func(request, *args, **kwargs) File "C:\Users\HP\Desktop\sama-marche\cart\views.py", line 26, in ajouter_cart produit = Produit.objects.get(id=id) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 399, in get clone = self.filter(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 892, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 910, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\query.py", line 1290, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\query.py", line 1315, in _add_q child_clause, needed_inner = self.build_filter( File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\query.py", line 1251, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\query.py", line 1116, in build_lookup … -
How to access request.user with AbstractUser class
I am trying to create an order object and assign the order's customer field (which is a foreign key for User) to the current user. Even though it passes the if statement and it can authenticate the request.user, it assigns customer as a blank value. When I print customer it prints a blank line, however when I print customer.id, it prints the ID of the customer. This happens in all views in the project so its a global issue I belive this has something to do with the fact that my user class is inheriting from AbstractUser utils.py def cartData(request): if request.user.is_authenticated: print('This will print') customer = request.user print(customer) print(customer.id) order, created = Order.objects.get_or_create(customer=customer, complete=False) models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): author = models.BooleanField(default=False) settings.py AUTH_USER_MODEL = 'main.User' I feel like this may be an easy one but I can't figure it out! Thanks. -
How to implement as new Django application whose data are based on MS Access?
I need to implement a new version from scratch of an old software (the new version will be web based). The data is already available in a MS Access database. The company wants to use the new application while the old one is still on production. The technology I chose to develop the new version is Django. The issue is the database technology. I want to use postresql. Is there a way to easily implement the new version while being based on MS Access + postgresql in parallel? I cannot modify the old software to adapt its backend to postgres and Django does not seem to provide support for MS Access on Linux. Is there an alternative way here? -
Will .save() data from Api directly to db be faster than sending it from a Django form?
I am pulling a lot of data from an API to my django template and I keep getting a 504 timeout error so it never finishes. I can cut the data I am calling in half and it prints just fine. Will I get any error if I pull the data from the api and save it to my db straight from my view?? -
How to return an HTML file in Django that is NOT a template?
I have a particular HTML file that I want to show in Django. This file is generated externally and will not use Django template syntax. In fact, it includes some syntax that confuses the Django template generator (like {{ #something }}) and makes it return an error. What is the best way to return this particular HTML page in a way that does not trigger the template syntax to be used? I use this now, and it works, but is this the recommended way? Any drawbacks? def annual_report(request): from django.http import HttpResponse html_content = open("templates/reports/annualreport.html") return HttpResponse(html_content) -
Listing only specific values in OneToOneField Django
I have two models. The first one is a tools/models.py and the second one is projects/models.py. The tools model has a OneToOneField which refer to my projects model. But I don't want to show the project's name if the project status IS 'DONE' So how can I set a condition before adding the models.OneToOneField ? Thanks.. -
how do i send an email to verify someones email address in DRF
hello i have tried a tutorial on how to send an email verification https://www.youtube.com/watch?v=BXg-b20Xusw but when i create a user it doesn't send an email for verification here is my code views.py class UserCREATEView(generics.ListCreateAPIView): queryset = Users.objects.all() serializer_class = UserSerializer permission_classes = [permissions.AllowAny] authentication_classes = [] def create_user(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() user = Users.objects.get(email=serializer.data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relative_link = reverse('email-verify') absurl = 'http://' + current_site + relative_link + "?token=" + str(token) email_body = "Hello " + Users.username + ' use the link below to verify your email. \n' + absurl data = {'email_body': email_body, 'to_email': user.email, 'email_subject': 'Verify Account'} Util.send_email(data) return Response(serializer.data, status=201) else: return Response(serializer.errors, status=400) class Verifyemail(generics.GenericAPIView): def get(self): pass utils.py class Util: @staticmethod def send_email(data): email=EmailMessage(subject=data['email_subject,'], body=data['email_body,'], to=[data['to_email']]) email.send() .env export EMAIL_HOST_USER={myemail} export EMAIL_HOST_PASSWORD={my password} settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS=True EMAIL_HOST='smtp.gmail.com' EMAIL_PORT=587 EMAIL_HOST_USER= os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD= os.environ.get('EMAIL_HOST_PASSWORD') is there anything i am missing? -
Issue with Custom Authentication Background and Custom Login Form
I am working on a django app where I have to authenticate users from active directory. I can do it with following code in CustomAuthenticationBackend: def authenticate(self, request, **kwargs): username = kwargs['username'] password = kwargs['password'] # type = kwargs['userType'] adConnect,message = self.is_valid_ad(username, password) if adConnect: request.session['pss'] = password try: userExist = User.objects.get(username__iexact=username) if userExist.check_password(password) is True: return userExist else: pass except User.DoesNotExist: # raise ValidationError(username+" is not allowed to access this application.") return self.createNewUserFromAD(adConnect, username, password) else: pass and in settings.py AUTHENTICATION_BACKENDS = ( 'dcw_app.CustomBackendAuth.CustomBackendAuth', 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) and in urls: path('login/', auth_views.LoginView.as_view(template_name='dcw_app/login.html'), name='login'), Problem comes when I need to add an extra field in login form. Authentication does not happen and on submit form is just reloaded. Custom form is like this in forms.py: class UserLoginForm(AuthenticationForm): errors = { 'required': 'Admin Must enter at least one role.', } def __init__(self, *args, **kwargs): super(UserLoginForm, self).__init__(*args, **kwargs) userType = forms.ChoiceField(error_messages=errors,required=True, label=pgettext("field label","Role"),widget=forms.Select(attrs={'class': 'form-control', 'placeholder': '', 'id': 'userType'}), choices=UserModal.USER_ROLES,) and in urls.py path('login/', auth_views.LoginView.as_view(template_name='dcw_app/login.html',authentication_form=UserLoginForm), name='login'), -
How to get years separated by centuries and decade like YY-YY?
I have a project in django and I want to get a year like 1985 separated in two scrolldowns one going from 00 to 20 and another going from 00 to 99, I tried using selectDate widgets, and also tried modifying some datepickers without success -
Unable to load custom JS file in Django admin home
I am trying to add Custom css and js in my django admin. But CSS is working but js is not working. I have checked my code. I don't think there is any error in my code. my admin.py from django.contrib import admin from .models import Blog # Register your models here. class BlogAdmin(admin.ModelAdmin): class Media: css = { "all": ('css/main.css',) } JS = ('js/blog.js',) admin.site.register(Blog, BlogAdmin) my blog.js console.log("This is blog.js"); let sc = document.createElement('script') sc.setAttribute('src', 'https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js') document.head.appendChild(sc); document.addEventListener("DOMContentLoaded", function (event) { console.log("This is blog.js"); let sc = document.createElement('script') sc.setAttribute('src', 'https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js') document.head.appendChild(sc); sc.onload = ()=>{ tinymce.init({ selector: '#id_content' }); } }); In the first line of js I have written a code console.log("This is blog.js");. But while inspecting the page I didn't see "This is blog.js" in console. It means my js is not loading in Django admin. Please look into this issue. Thanks in advance. -
Insomnia - CSRF cookie not set
I am trying to use insomnia for POST requests for testing my API in a Django application. I am getting this CSRF token error. I saw this post here Django CSRF Failed: CSRF token missing or incorrect which tells me that I need to set my CSRF Token in my headers but I get this new error in return under Live Preview "No cookies in store for URL". Does anyone know a workaround to this problem? -
Mocking external API in Django
I am trying to mock external api in Django but not sure how to do it properly. Basically, it must mock the json data from external API and then create a new object if all values are valid. The program fetches the geolocation data based on given IP address and saves the object in database if response data includes all required fields. So, how I can mock this process to test a new object creation? services.py import os import requests from .exceptions import ExternalApiException def get_location(ip): url = f'http://api.ipstack.com/{ip}' params = {'access_key': os.environ.get('ACCESS_KEY')} try: res = requests.get(url, params=params) data = res.json() return { 'ip':data['ip'], 'country_name':data['country_name'], 'region_code':data['region_code'], 'city':data['city'], 'latitude':data['latitude'], 'longitude':data['longitude'], 'zip_code':data['zip'] } except requests.exceptions.ConnectionError: raise ExternalApiException('Connection error occured during the fetch process') except requests.exceptions.Timeout: raise ExternalApiException("Connection timeout. Please check your internet connection and try again later") except requests.exceptions.TooManyRedirects: raise ExternalApiException("Too many redirects") except requests.exceptions.RequestException: raise SystemExit(e) tests.py #I am lost in this part @patch('geolocation.services.get_location') def test_create_basic_geolocation(self, mock_request): """Test creating geolocation data""" payload = { 'ip': '', } res = self.client.post(LOCATIONS_URL, payload) self.assertTrue(res.data['ip']) Thanks for any help. -
X-Accel_Redirect returns an empty file when using application port
Dears, When I use X-Accel_Redirect, nginx returns an empty file (when using application port), but when I use the port which nginx listens to, it returns it. I need to return the file on the port the application is running on. I really appreciate your help! -
Use non model django fields in django filter
I have a variable 'cptCodeTBX' which is not present as fields in django models. I need to apply filter on 'cptCodeTBX' variable. Something roughly equivalent to select * from cpt where cpt.code like cptCodeTBX or cptCodeTBX is != '' In dot net entity framework we could do it by b = cptContext.CPTs.AsNoTracking().Where( a => (String.IsNullOrEmpty(cptCodeTBX) || a.Code.StartsWith(cptCodeTBX)) -
django's sql for terminal functions
I know that in order to see the generated SQL statement for queries I could use the .query function (e.g. str(Model.objects.all().query), or same with filter, etc.) I want to see the generated SQL statements for terminal functions used on query sets (e.g. Model.objects.count(), Model.objects.update(...), etc.). As the function is called it's executed without giving out an object like QuerySet to have the query on. So is there a way to see the generated SQL statement for these kind of operations without executing them and looking back at logs, etc.? -
how to create custom scheduler in celery without the help of django celery beats
First to create an app second to create a custom scheduler to work with celery third to integrate to celery -
Internal Server Error. Unable to get access to server's content - apache2
to be short I have encountered a problem that blocked the HTTP/TCP access to port 80 error.jpg below are my errors logs and other related conf errors_logs: [Mon Feb 15 01:56:43.361342 2021] [wsgi:error] [pid 73449:tid 139984461121088] [remote 203.145.94.145:41526] RuntimeError: populate() isn't reentrant [Mon Feb 15 01:56:43.844935 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] mod_wsgi (pid=73449): Failed to exec Python script file '/home/user/project/project/wsgi.py'. [Mon Feb 15 01:56:43.844969 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] mod_wsgi (pid=73449): Exception occurred processing WSGI script '/home/user/project/project/wsgi.py'. [Mon Feb 15 01:56:43.845066 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] Traceback (most recent call last): [Mon Feb 15 01:56:43.845093 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] File "/home/user/project/project/wsgi.py", line 16, in <module> [Mon Feb 15 01:56:43.845097 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] application = get_wsgi_application() [Mon Feb 15 01:56:43.845103 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] File "/home/user/project/venv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Mon Feb 15 01:56:43.845106 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] django.setup(set_prefix=False) [Mon Feb 15 01:56:43.845111 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] File "/home/user/project/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup [Mon Feb 15 01:56:43.845114 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] apps.populate(settings.INSTALLED_APPS) [Mon Feb 15 01:56:43.845119 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] File "/home/user/project/venv/lib/python3.8/site-packages/django/apps/registry.py", line …