Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django Formset Order on Template Render after Errors
I have a formset that adds new forms by javascript in diferent order in the page. someones in the bigining and others in the end. But when i save, the errors are shows in order of form-n form-n+1, etc. no in the order that i put in the hiddenfield form-N-ORDER. how i cant show in template ordered forms by the form-N-ORDER? because in the view, i cant use: for form in formset.ordered_forms: but ordered_forms not work in template. -
Pycharm unresolved references with Django
This is my 5th day learning Django. I've got a Django project working in a virtual environment using Pycharm. The problem I have is, Pycharm can't reference certain imports when they are actually working in Django without any issues. I've selected the right interpretor for the project but Pycharm cannot connect the imports with the .py files in the Django project. The selected interpretor does have Django for the virtual environment but it still doesn't work. Below are the screenshots: import works in Django but Pycharm cannot resolve reference with the correct interpretor -
Page not found (404) on django router
I have the below router router.register(r'get-customers/<int:number>', GetCustomersViewSet, basename='get-customers') when i visit http://127.0.0.1:9090/get-customers/20 I am getting the above error i am not sure what can be the problem. But when i change the router to router.register(r'get-customers', GetCustomersViewSet, basename='get-customers') and visit http://127.0.0.1:9090/get-customers It works perfectly -
django- createview with url parameter redirects to the same view without parameter in url and shows error
I have created a view with a generic view createview, to this view I pass a parameter by url, I have a form, but after clicking on the submit button it is redirected to the same url without parameter and shows error, I have tried to see if the form is invalid using "form_invalid" but it doesn't go there, it doesn't go to "form_valid" either and the "get_success_url" doesn't work, I don't know what's wrong. enter image description here url.py app_name = 'gestionAsignacion' urlpatterns = [ path('asignacionContact/<int:pk>',AsignacionCreateView.as_view(), name='asignacion_contact'), path('detalle/asignacion/<int:pk>',descargarAsignacion.as_view(), name='descargar_asignacion'), path('asignacionGeneral/',asignacionGeneral.as_view(), name='asignacion_general'), ] view.py class AsignacionCreateView(CreateView): model=AsignacionContact form_class=AsignacionForm template_name='gestionAsignacion/asignacion_contact.html' # success_url = reverse_lazy('gestionAsignacion:asignacion_general') def get_initial(self): # call super if needed return {'idasignacion_general': self.kwargs['pk']} def form_valid(self, form): print('hola form_valid') isvalid = super().form_valid(form) return isvalid def form_invalid(self, form): print ("form is invalid") return super().form_invalid(form) def get_success_url(self): return HttpResponseRedirect(reverse('gestionAsignacion:asignacion_general')) def get_context_data(self, **kwargs): # Llame primero a la implementación base para obtener un contexto context = super().get_context_data(**kwargs) # Agregar un QuerySet de todos los libros context['asig_general'] = AsignacionGeneral.objects.get(id=self.kwargs['pk']) context['object_list'] = AsignacionContact.objects.filter(idasignacion_general=self.kwargs['pk']) return context model.py class AsignacionContact(models.Model): id = models.IntegerField(primary_key=True) idasignacion_general = models.ForeignKey('AsignacionGeneral', models.DO_NOTHING, db_column='idasignacion_general') nombre_asignacion = models.CharField(max_length=100, blank=True, null=True) fecha_inicio = models.DateField(blank=True, null=True) fecha_fin = models.DateField(blank=True, null=True) observacion = models.CharField(max_length=255, blank=True, null=True) def __str__(self): … -
Django AWS S3 EB Max file upload
Hope everyone is well. When I upload a file greater than FILE_UPLOAD_MAX_MEMORY_SIZE I don't get any error it just gives me "This site can’t be reached". I have post conditions to check if the file is above this size and return an error message if it is, works in local using S3 but does not work on EB. Does anyone know why this is a problem on EB and not in local? If you need any further information please let me know. if 'document_file' in request.FILES: megabytes = 2621440 file = request.FILES['document_file'] if file.size > megabytes: raise Exception(f"{file.name}, cannot upload as the file is greater than 2.5mb") Thanks in advance, Thomas -
How do you display model attribute in a table within am html file?
I have a project and a task model and I want to make a table in a detail html that displays the tasks in the project. I've tried doing <table> <tr> <th>Name</th> <th>Assignee</th> <th>Start Date</th> <th>Due Date</th> <th>Is compeleted</th> </tr> <tr> <td>{{ task.name }} </td> <td>{{ task.assignee }}</td> <td>{{ task.start_date }}</td> <td>{{ task.due_date }}</td> <td>{{ task.is_completed }}</d> </tr> </table> but it just shows the table headers and not its content here is my task model from django.db import models from django.conf import settings from django.urls import reverse # Create your models here. class Task(models.Model): name = models.CharField(max_length=200) start_date = models.DateTimeField() due_date = models.DateTimeField() is_completed = models.BooleanField(default=False) project = models.ForeignKey( "projects.Project", related_name="tasks", on_delete=models.CASCADE, ) assignee = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, related_name="tasks", on_delete=models.SET_NULL, ) def __str__(self): return self.name def get_absolute_url(self): return reverse("show_my_tasks") -
where puting ForeignKey in django?
one of the questions that came to my mind is that in a many-to-one relationship in Django, where should the foreign key be located? I mean, it should be in many or in part one? For example, we have two classes, post and comment: in this case, where should the ForeignKey be located in the comment or post class? post model : class post(models.model): created_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ManyToManyField("PostCategory", blank=True) caption = models.CharField(max_length=2000) comment model : class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE) text = models.TextField() Now here is the comment field where the foreign key should be defined? -
'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name When using PasswordResetConfirmView
I learned tutorial Django was 3.0.0 and I am with 4.0.1 now. I try to use that module but it not working . I can see the below alert when I am trying to reset my password. Error : Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. My urls.py is given below from django.conf.urls import url from django.urls import path, reverse_lazy from Core import views from django.contrib.auth.views import PasswordChangeView, PasswordResetView, PasswordChangeDoneView, PasswordResetConfirmView from .forms import MyChangePasswordForm,MyPasswordResetForm app_name ='Core' urlpatterns = [ path('',views.home, name='home'), path('signup/',views.SignupView.as_view(),name='signup'), path('login/',views.LoginView.as_view(),name='login'), path('logout/', views.LogoutView.as_view(), name='logout'), path('change-password/', PasswordChangeView.as_view(template_name ='Core/change-password.html',form_class=MyChangePasswordForm, success_url = reverse_lazy('Core:password_change_done')), name='change-password'), path('password-change-done/', PasswordChangeDoneView.as_view(template_name ='Core/password_change_done.html'), name='password_change_done'), path('reset-password/',PasswordResetView.as_view(template_name = 'Core/password-reset.html',form_class=MyPasswordResetForm),name='reset-password'), path('password-reset-confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(success_url=reverse_lazy('Core:password_reset_confirm')),name='password_reset_confirm'), -
Send additional data to form initialisation
So I'm creating a form object using request.POST data, but want to initialise additional fields using other values. This is what i tried, it isn't working: #forms.py class InputForm3(forms.Form): url = forms.URLField(required=True) db = forms.CharField(required=False) wks = forms.CharField(required=True, initial="Sheet1") table = forms.CharField(required=False, initial="test_table") def __init__(self, wks, *args, **kwargs): self.wks=wks super().__init__(*args, **kwargs) self.cleaned_data = None def clean(self): self.cleaned_data = super().clean() print("FORM3 cleaned_data : ", self.cleaned_data) #views.py form3=InputForm3(wks="Sheet1", data= request.POST) if form3.is_valid: #remaining code #output FORM3 cleaned_data : {'url': 'https://randomurl.com', 'db': 'testdb', 'table': ''} the fields 'url' and 'db' are present directly in request.POST, HOW DO I INITIALISE THE OTHER FIELDS PLEASE HELP! -
How to configure my media url in settings.py using AWS S3
This is currently my configuration for static and media files. This works fine locally, however now, I'm trying to host them using S3. STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') This is also my initial S3 configuration: AWS_ACCESS_KEY_ID = '*******' AWS_SECRET_ACCESS_KEY = '*************' AWS_STORAGE_BUCKET_NAME = '*******' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Note: I'm also currently hosting my website on heroku. -
Django-Rest-Framework: Endpoint Using a Related Field ID in the URL
I have a MarketHistoryListing model that looks like the following: class MarketHistoryListing(auto_prefetch.Model): player_profile = auto_prefetch.ForeignKey(PlayerProfile, on_delete=models.SET_NULL, null=True) sales_minute = models.DecimalField( max_digits=1000, decimal_places=2, null=True) I'd like to setup an endpoint where I can get all of the MarketHistoryListing objects that below to a specific player_profile. Something like /api/market-history/<player_profile._id> I setup what I think is the correct way to do the view - but i'm not 100% sure. class MarketHistoryListingView(viewsets.ModelViewSet): serializer_class = MarketHistoryListingSerializer queryset = MarketHistoryListing.objects.all() pagination_class = LargeResultsSetPagination def get_queryset(self): return MarketHistoryListing.objects.filter(player_profile=self.kwargs['user_inventory_pk']) However, I really don't know how to do the URL. I'm assuming it will be something similar tot he following, but i'm not sure how to pass int he dynamic player profile ID. market_history_router = routers.NestedSimpleRouter( router, r'market-hitory', lookup='user_inventory' ) market_history_router.register( <player_id>, views.MarketHistoryListingView, basename=<player_id> ) Appreciate any help!