Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django, can I use context in redirect?
I am trying to use redirect with context but I get NoReverseMatch exception. Code snippet is as follows: return redirect(reverse('td:success', kwargs={ 'data': my_data })) However, when I use render, all goes well and I am able to access the context in the template. But I want redirect instead. enter image description here -
Reverse for 'showuser' with keyword arguments '{'bid': 1}' not found. 1 pattern(s) tried: ['showuser/(?P<broadcastid>[0-9]+)\\Z']
I am getting following error: Reverse for 'showuser' with keyword arguments '{'bid': 1}' not found. 1 pattern(s) tried: ['showuser/(?P[0-9]+)\Z'] Does anyone knows how to solve it? urls.py path('showuser/<int:broadcastid>', views.showuser, name="showuser") views.py def showuser(request, broadcastid): vrbrlstnm = BroadcastListSms.objects.get(id=broadcastid) showDepartment = AddContact.objects.values('dept_nm').distinct() if request.method == "GET": if request.GET.get('select') == "All": departmentData = AddContact.objects.all() else: departmentData = AddContact.objects.filter(dept_nm=request.GET.get('select')) return render(request, "showuser.html", {'adduser': vrbrlstnm, 'showDepartment': showDepartment, 'departmentData': departmentData}) return HttpResponseRedirect("showuser", {'showDepartment': showDepartment, 'departmentData': departmentData}) adduser.html <a href="{% url 'showuser' bid=adduser.id %}" class="btn btn-primary"> Add Existing User </a> Note: adduser.id is the foreign key value, from where we get broadcastid. I am stuck here from so many days. Not able to understand what to do now -
How to create authenticated by phone number django
i want to create authenticataion by phone number i don'i know to do it. I don't found any library for django, python. I have authentication by email and password: # models.py class User(AbstractUser): email = models.EmailField(_('email address'), blank=False,unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] How i can create authentication by phone number and verify code which send when user click the button ??? -
Django - Accessing static/media files from a remote url instead of local the one
I cannot find any answer to my question on the web so here it is with some context : I have a Django app running on a server and I would like to continue working on it locally with the "runserver" command. My problem concern the use of common static and media files. The media folder content changing frequently in production I have to download those media files from the server each time I want to dev locally and add those the MEDIA_ROOT path on my computer. The database is common to both dev and production environment since it is a MySQL host on my server. My question is simple, how can I tell Django in local mode to lookup static and media files on a remote url from my domain name instead of localhost ? Searching for media on : https://example.com/media/ instead of : https://127.0.0.1:8000/media/ Hoping this is possible without so much effort ! Thank you in advance for your help -
Refactoring: how to remove a model?
I have a model which is causing too much complexity, and so I want to do away with it and move to a simpler way of doing things. I don't immediately want to scrap the data in this database table, though. class PRSblock( models.Model): PRS = models.ForeignKey( 'jobs.PRS2', models.CASCADE, related_name='prs_blocks') # no other relational fields So, first, migrate the related name prs_blocks to obsolete_prs_blocks and then in the PRS model, add a @property prs_blocks that will assert that it is never called (to trap any bits of code which I failed to remove) Second, rename the model PRSblock to obsolete_PRSblock. IIRC Django makemigrations will ask whether I renamed it, and if I say yes, it will preserve the database table. Does this sound sensible or are there any gotchas I haven't though of? -
How can I add the following JSON to a new URL based on its "category": 2?
I have a JSON array in my server in Django rest framework, but I want to filter them by category , for example some of them have 'category':1 and some of them have 'category':2 like this: [ { "id": 667, "image": "https://ae0g", "description": "GRE", "price": "USD .11", "buy": "https://sn", "category": 1 }, { "image": "https://ae04.", "description": "10/13 ", "price": ".18", "buy": "https://", "category": 2 } ] How can I add the following JSON to a new URL based on its "category": 2? "image": "https://ae04.", "description": "10/13 ", "price": ".18", "buy": "https://", "category": 2 views: class productviewset(viewsets.ModelViewSet): queryset=product.objects.all() serializer_class = productSerializer pagination_class = None def create(self, request): serialized = productSerializer(data=request.data, many=True) if serialized.is_valid(): serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) @action (detail=False , methods=['post']) def delete(self,request): product.objects.all().delete() return Response('success') urls: router = routers.DefaultRouter() router.register(r'product', productviewset,basename='product') # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('api/', include(router.urls)), -
VariableDoesNotExist at
I encountered a problem in django this the problem enter image description here this is my model enter image description here and this is my views.py enter image description here someone could help me? -
Django Template inclusion tags, supress trailing newline
Firstly I know about {% spaceless %}. I don't want to remove all spaces. I just would like the inclusion tag to only render the template, and not add its own trailing '\n' at it's own discretion. E.g. say I have the template tag: from django import template register = template.Library() @register.inclusion_tag(f'myemail/button.html') def myemail_button(href, title, color, background_color): return { 'href': href, 'title': title, 'color': color, 'background_color': background_color, } And this is the inclusion tag's template (myemail/button.html): <table><tbody><tr> <td style="background-color:{{ background_color }}; border-radius:5px; border:solid 1px {{ background_color }}; color:{{ color }}; padding:0px;"> <a href="{{ href }}" style="background-color:{{ background_color }}; border-radius:5px; border:solid 1px {{ background_color }}; color:{{ color }}; display:inline-block; font-weight:bold; padding:12px; text-align:center; text-decoration:none;" target="_blank">&nbsp; {{ title }} &nbsp;</a> </td> </tr></tbody></table> Then when one renders this template (there is no blank line at the start nor end of the file: {% load myemail %}{% myemail_button href="https://example.com" title="CLICK ME!" color="#123456" background_color="#abcdef" %} {% myemail_button href="https://example.com" title="CLICK ME!" color="#123456" background_color="#abcdef" %} It renders as (note the space between the two adjacent <table> elements (this is the new line I would not like auto inserted): <table><tbody><tr> <td style="background-color:#abcdef; border-radius:5px; border:solid 1px #abcdef; color:#123456; padding:0px;"> <a href="https://example.com" style="background-color:#abcdef; border-radius:5px; border:solid 1px #abcdef; color:#123456; display:inline-block; font-weight:bold; padding:12px; … -
Date defaults to Django webserver start date rather than to the default method parameter
I've stumbled on something unexpected, it is probably something basic I'm misunderstanding either in Python or Django. I have a static method in my model class to return the date provided by the user or alternatively return today's date: @staticmethod # By default return today's date or the date provided def get_start_date(**kwargs): startDate = kwargs.get('startDate', datetime.date.today()) return startDate I decided to rewrite it such that the method has the startDate as a default parameter. However, instead of defaulting to today's date it defaults to the date when the Django webserver was first started. Why would this be the case? The method is executed, I've confirmed that the startDate was not provided in the call, even when a variable which I know for certain isn't used anywhere else in the code is entered in the argument, it still returns the date Django was first ran. def get_start_date(startDate=datetime.date.today(), notUsed=datetime.date.today(), **kwargs): print(startDate, notUsed, datetime.date.today()) return startDate >>> 2022-06-23 2022-06-23 2022-06-24 -
Oauth2 - password grant type not working after Django version upgrade to 3.2 LTS
After upgrading my Django app from version 2.2 to 3.2 LTS, the same token generation request that my app was using to generate access and refresh tokens with grant type - password is not working. This is the cURL request I'm using: curl --location --request POST '0.0.0.0:8000/o/token/' \ --header 'Content-Type: application/json' \ --data-raw '{ "grant_type":"password", "username":"xxxx", "password":"xxxx", "client_id":"xxxx", "client_secret":"xxxx" }' I have two docker containers of my app running the same code - one on Django 2.2 and another on Django 3.2. Both are connected to the same postgres db (in a separate container). This same request gives me access and refresh tokens in the Django 2.2 container but in the Django 3.2 container I get this error - { "error": "invalid_grant", "error_description": "Invalid credentials given." } I have checked the documentation of oauth2 toolkit and I'm not seeing any deprecation notes. I moved the django-oauth-toolkit version from 1.2.0 to 1.7.1. Please let me know what I'm missing. -
update data with href link in django and ajax
$("#feedlikes").on("click", function(e){ e.preventDefault(); $.ajax({ type: 'get', url:'{% url "feedlikes" %}', data:{}, success: function({ alert("Updated Successfully") }), }), }), those are my Ajax code help me to get them work. this is my view: def feedlikes(request, feed_id): feed_update= Feeds.objects.get(pk=feed_id) feed_update.likes = feed_update.likes +1 feed_update.save() -
Displaying python list of dictionaries on front-end using django [duplicate]
I have python list as list_dict= [{'_id': ObjectId('6299ba68beb94e0a32af47a8'), 'name': 'Pepperoni', 'size': 'small', 'price': 19, 'quantity': 10, 'date': '2021-03-13T08:14:30Z'}, {'_id': ObjectId('6299ba68beb94e0a32af47a9'), 'name': 'Pepperoni', 'size': 'medium', 'price': 20, 'quantity': 20, 'date': '2021-03-13T09:13:24Z'}, {'_id': ObjectId('6299ba68beb94e0a32af47aa'), 'name': 'Pepperoni', 'size': 'large', 'price': 21, 'quantity': 30, 'date': '2021-03-17T09:22:12Z'}, {'_id': ObjectId('6299ba68beb94e0a32af47ab'), 'name': 'Cheese', 'size': 'small', 'price': 12, 'quantity': 15, 'date': '2021-03-13T11:21:39.736Z'}, {'_id': ObjectId('6299ba68beb94e0a32af47ae'), 'name': 'Vegan', 'size': 'small', 'price': 17, 'quantity': 10, 'date': '2021-01-13T05:08:13Z'}] In template/home.html of my_project in django, I have executed following code: {%block content %} {% for element in list_dict %} <ul> <li>Name:{{element['name']}}</li> <li>Size:{{element['size']}}</li> <li>Price:{{element['price']}}</li> </ul> {% endfor %} {% endblock %} But when i run python manage.py runserver I get error as: Could not parse the remainder: '['name']' from 'element['name']' I'm a beginner in django, kindly looking to learn about my mistakes and fix this error. Thank you. -
Django Authenticate function always returns nine even after making required changes in the settings.py
I am trying to create a login system with Django python. Though the Authenticate function always returns none even after making certain changes in the settings.py as suggested in other StackOverflow answers. I have tried running this code in debug mode in visual studio code and found out the problem lies in the authenticate function only as it's always none and the code hence is never able to log in any user. Here is my code: views.py(login function) from django.http import HttpResponse from django.shortcuts import redirect, render from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib import messages # Create your views here. def home(request): return render(request, 'Home_Page.html') def signup(request): if request.user.is_anonymous: if request.method == 'POST': if User.objects.filter(username=request.POST.get('username').upper()).exists(): messages.error(request, 'The username already exists') elif User.objects.filter(email=request.POST.get('email').lower()).exists(): messages.error(request, 'The Email already exists') else: user = User.objects.create_user(username=request.POST.get('username').upper(), email=request.POST.get('email').lower(), password=request.POST.get( 'password'), first_name=request.POST.get('firstname'), last_name=request.POST.get('lastname')) user.save() return redirect('home') return render(request, 'Signup_Page.html') else: return redirect('/dashboard') def login(request): if request.user.is_anonymous: if request.method == 'POST': user = authenticate(username=request.POST.get( 'username'), password=request.POST.get('password')) if user is not None: login(request, user) return redirect('/dashboard') else: return render(request, 'Login_Page.html') else: return render(request, 'Login_Page.html') else: return redirect('/dashboard') def logout(request): if not request.user.is_anonymous: logout(request) return HttpResponse("Home Page") return redirect('/') Login_Page.html … -
Fetch TOP(N) with Group by Date range for Users using Django ORM
I am trying tio fetch TOP(N) results for every user within a date range. I know to fetch TOP(N) from any model one can use Window and Rank functions like. qs.annotate(rank=Window( expression=Rank(), order_by=F("id").asc(), partition_by=F('user'), ) ).values('id', 'status', 'rank') But I am wondering how to apply Group By for Every User within a Date range. Let me explain with a sample data what I want to achieve I have the following data , You can see from the Following image Alex has 3 entries (id=1,3,7) . But two of them have same dates (3,7) , so out of these two latest entries will be counted i.e., 7. So overall 2 results will returned for User Ales 1 & 7 or Results are returned based on date range filter . If sept 22 filter is applied then only 7 will be returned. Jon has 9 entries (id=6,10,12,15,16,17,18,20,21), For Oct 25 he have 7 entries but l;latest entry id=21 must be returned. So overall, Latest entry for every Used based on dare range must be returned. Date range can be used in filter() if Admin wants to see status counts on specific Dates. -
Fernet Encrypt_key and Decrypt_key both are same but still giving error
I have create an fernet file encryption and decryption using python-cryptography. I can encrypt file but when I decrypt the file with the same key i am getting error for invalid token. Code: ENCRYPTION & DECRYPTION def encrypt_file(blob_name): key = key_gen() fernet = Fernet(key) with open(os.path.join('./static/temp/', blob_name), 'rb') as file: original = file.read() encrypted = fernet.encrypt(original) with open(os.path.join('./static/temp/', blob_name), 'wb') as encrypted_file: encrypted_file.write(encrypted) def decrypt_file(blob_name): print(blob_name) with open('./static/temp/filekey.key', 'rb') as filekey: key = filekey.read() fernet = Fernet(key) with open('./static/temp/'+blob_name, 'rb') as enc_file: print(enc_file) encrypted = enc_file.read() print(encrypted) decrypted = fernet.decrypt(encrypted) print(decrypted) with open(os.path.join('./static/temp/', blob_name), 'wb') as dec_file: dec_file.write(decrypted) Folder Tree: project_folder -static -- temp --- blob_name app.py gcpdata.py Error: Traceback (most recent call last): File "\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 2077, in wsgi_app response = self.full_dispatch_request() File "\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1525, in full_dispatch_request rv = self.handle_user_exception(e) File "\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1523, in full_dispatch_request rv = self.dispatch_request() File "\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1509, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args) File "\PROJECT\app.py", line 47, in download decrypt_file('./static/temp/'+list_blobs(bucket_name)) File "\PROJECT\gcpdata.py", line 117, in decrypt_file decrypted_data = f.decrypt(encrypted_data) File "\AppData\Local\Programs\Python\Python39\lib\site-packages\cryptography\fernet.py", line 88, in decrypt return self._decrypt_data(data, timestamp, time_info) File "\AppData\Local\Programs\Python\Python39\lib\site-packages\cryptography\fernet.py", line 145, in _decrypt_data self._verify_signature(data) File "\AppData\Local\Programs\Python\Python39\lib\site-packages\cryptography\fernet.py", line 129, in _verify_signature raise InvalidToken cryptography.fernet.InvalidToken -
How to run Django Project on HTTPS locally?
Is there a way to run a Django Project on localhost on something like https://localhost/app-name/ on a Windows 10 machine? -
After downloading and opening an excel file it is showing me an error(Django, python)
Here is my view.py code : def downloadfile(request, filename=''): if filename != '': BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = 'SampleExcel.xls' filepath = BASE_DIR + "\SampleExcel\SampleExcel.xls" path = open(filepath, encoding='cp437') mime_type, _ = mimetypes.guess_type(filepath) response = HttpResponse(path, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response else: return HttpResponseRedirect("adduser", {}) File is downloaded properly, but not opening as you can see in below images. -
SQL query group by and join
I have following problem: N+1 queries in SerializerMethodField Queries in Django ORM - https://gist.github.com/dima-dmytruk23/0183014d76ad25f4e2a0ca87ec225a10 As far as I understand, it is unrealistic to implement this using Django ORM. There is an idea to write this in RAW SQL, but I also don’t understand how to make such a query ( -
Is the "with" template nest-able in Django 2.2, and 3.2? HOw do I do that and work with forloop.counter as well?
I am referring to https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#with for Django 2.2 and https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#with for 3.2 Can i use them this way? {% with thStyle="font-size: 1.4em;text-align: left;background-color: #A7C942;color: #fff;border: 1px solid #98bf21;padding: 5px 7px 4px 7px;" tdStyle="font-size: 1.2em;border: 1px solid #98bf21;padding: 3px 7px 2px 7px;" alttdStyle = "font-size: 1.2em;border: 1px solid #98bf21;padding: 3px 7px 2px 7px; background-color: #EAF2D3;" %} .... {% for key, value in some_list.items %} {% with style = tdStyle # when forloop.counter|divisible:2 else it's alttdStyle %} .... {% endwith %} {% endfor %} {% endwith %} My plan is taht i need to use different td style depending whether the counter is divisible by 2 or not. This is my logic. not confident if correct. -
How do I build a server for an Android app?
How do I go about connecting my app to a server? I've literally no idea I have an application which is connected to firebase for Google sign in. Now I need to make a server to facilitate connection between people (kinda like messaging) My question is where do I write the code for backend? I have a bit of experience with Django so I reckon I can use Django for building the server but how can I go about connecting it to my application? Sorry if I'm not making sense. Guidance is appreciated. Links would be helpful. -
How to implement refresh token in django-oauth-toolkit? I'm able to get access_token but the refresh token isn't coming with it
I'm using django-oauth-toolkit with djangorestframework where our partner user will register their application and get application credentials (client id and client secret) which then used to get access token that can be used further to get our server resources. Upto now I'm able to convert those form based application registration process and other apis through rest. But while I hit for access_token only access token with expire are coming as response. Refresh token also supposed to come along the access token but it's not. What I'm missing here... Below is the sample api response for access_token And the oauth2 settings -
Gunicorn --max-requests configuration: Would the periodic workers restart kill the tasks(process) running inside it?
I have been facing memory leaks in my Django application and for some reason, I am not able to get rid of them. Here I wanted to try with Gunicorn --max-requests config to restart the gunicorn workers periodically to release the memory. I had a few concerns here before taking it to production, Would this periodic restart kill any process running inside it? Or would it wait for the worker to be idle before restarting it? I was assuming the basic philosophy will be wait it to be idle before restarting it. but I did not find documents backing this up. Any insights on this will be helpful. -
Django / Django Rest Framework ModelViewSet: __init__() takes 1 positional argument but 2 were given
I'm trying to create a custom "list" under OptionViewSet but It's giving me an error. class OptionViewSet(viewsets.ModelViewSet): serializer_class = OptionSerializer queryset = Option.objects.all() def list(self, request): queryset = Option.objects.all() serializer = OptionSerializer(queryset, many=True) return Response(serializer.data) Error __init__() takes 1 positional argument but 2 were given This works fine: class OptionViewSet(viewsets.ModelViewSet): serializer_class = OptionSerializer queryset = Option.objects.all() urls.py path('api/shipping/', include((shipping_routes.urls, 'shipping'), namespace='shipping')), routes.py routes.register(r'option', OptionViewSet, basename='option') -
TypeError: 'module' object is not iterable under nginx+uwsgi+django+centos7 Never seen before
I have an annoying problem thest days.There are errors from uwsgi.log in the project I am creating: Traceback (most recent call last): File "/root/Envs/magicmall2/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner File "/root/Envs/magicmall2/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner Traceback (most recent call last): File "/root/Envs/magicmall2/lib/python3.6/site-packages/django/urls/resolvers.py", line 409, in url_patterns response = get_response(request) File "/root/Envs/magicmall2/lib/python3.6/site-packages/django/core/handlers/base.py", line 172, in _get_response Traceback (most recent call last): iter(patterns) File "/root/Envs/magicmall2/lib/python3.6/site-packages/django/urls/resolvers.py", line 409, in url_patterns TypeError: 'module' object is not iterable django.core.exceptions.ImproperlyConfigured: The included URLconf 'magic_mall.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. the project is running fine on my windows laptop.but couldn't work properly while i am deploying on server. uwsgi.ini nginx.conf -
Django app with MS Azure SAML SSO using MSAL
I have an application created using Django that uses MSAL library to authenticate with Azure AD. As I understand, MSAL uses OAuth and so far the authentication/authorization works great. Is there a way to implement authentication using SAML instead of OAuth. I came across pysaml2 library but doesn't have sufficient documentation to integrate with Azure AD. Can someone please share your thoughts.