Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In django-simple-jwt package, how can I conditionally validate a password against different signing algorithms & secret keys?
My use-case is that I have a legacy backend that has generated tokens using an insecure secret key. I have imported all the user data into a new backend using simple-jwt. The app owner does not want to force existing users to logout and login again to get a new token. The problem is when an existing user requests a token, their old password cannot be checked because the existing hash because it was created with the secret key from the old backend. So I would like DRF/simple-jwt to first try to validate against the default key/algorithm, and if that fails attempt against the old, insecure secret key/algorithm. Is this possible? Do I create a new serializer class based on TokenObtainPair and override validate? If so, how exactly would I do this? -
How can I safely debug my Django Website hosted on apache2 server?
I am trying to change my website which is hosted on a Linux machine with Ubuntu. I am able to access it using ssh username@serverIPadress command on my local machine. Now, when I change my code I get a 500 server error message, so I can't check where I am doing something wrong. Do I have to change Debug = True in my settings.py file and what do I need to fill in at ALLOWED HOSTS? Currently, I have ALLOWED HOSTS = {domainname, server IP}. So, is there a secure way to change my deployed Django Website locally on my own machine? Maybe, I am changing it too complicated, but I am not a webdeveloper. I can't get an answer when I read the documentation. Thank you in advance. -
django-allauth: include allauth email template in your custom profile template
How can I include allauth's email.html into a custom profile editing template? I've tried doing {% include 'account/email.html %} but the problem is that it doesn't show the form to add email address, and when I press make primary button it takes me to the original template. -
AttributeError at /product/7 'QuerySet' object has no attribute 'category'
So I get AttributeError at /product/7 'QuerySet' object has no attribute 'category' error whenever I visit the detail view page, It says there is no attribute category but I have formed a relationship with another model called category in models.py, I have tried using category.id but that does not work too views.py def detailview(request, id): book = get_object_or_404(Book, pk=id) if request.user.is_authenticated: oof = CartItem.objects.filter(user=request.user).values_list('book', flat=True) lmao = OrderItem.objects.filter(user=request.user).values_list('book', flat=True) hehe = CartItem.objects.filter(user=request.user) number = 0 for num in hehe: number += 1 fianlprice = 0 for item in hehe: fianlprice += item.book.price specific = Book.objects.filter(pk=id) matching_books = Book.objects.filter(category=specific.category).exclude(pk=id)[:3] reviews = Paginator(ProductReview.objects.filter(book=id), 5) review_page = request.GET.get('reviews') review_objects = reviews.get_page(review_page) one_two_star = ProductReview.objects.filter(book=id, rating=1).count() + ProductReview.objects.filter(book=id, rating=2).count() three_star = ProductReview.objects.filter(book=id, rating=3).count() four_star = ProductReview.objects.filter(book=id, rating=4).count() five_star = ProductReview.objects.filter(book=id, rating=5).count() checking = True if ProductReview.objects.filter(book=id, user=request.user).exists(): checking = False if checking == False: gotten_review = ProductReview.objects.get(user=request.user) params = {'book':book, 'price':fianlprice, 'cart':oof, 'order':lmao, 'number':number, 'matching_books':matching_books, 'reviews':review_objects, 'one_two_star':one_two_star, 'three_star':three_star, 'four_star':four_star, 'five_star':five_star, 'gotten_review':gotten_review, 'checking':checking} return render(request, 'main/detail.html', params) else: specific = Book.objects.filter(pk=id) matching_books = Book.objects.filter(category=specific.category).exclude(pk=id)[:3] reviews = Paginator(ProductReview.objects.filter(book=id), 5) review_page = request.GET.get('reviews') review_objects = reviews.get_page(review_page) one_two_star = ProductReview.objects.filter(book=id, rating=1).count() + ProductReview.objects.filter(book=id, rating=2).count() three_star = ProductReview.objects.filter(book=id, rating=3).count() four_star = ProductReview.objects.filter(book=id, rating=4).count() five_star = ProductReview.objects.filter(book=id, rating=5).count() params = … -
how can i import all choices in a ChoiceField in django from the views.py file?
i am trying to import a list of account numbers in django from a model called Accounts in views.py and then trying to pass them to the MoneyTransfer form in form.py but id doesn't work correctly why is that? forms.py code views.py code -
How can I migrate AWS RDS database through eb cli (django postgres)?
I have a django project deployed with elastic beanstalk CLI. I added a postgres database (AWS RDS), the connection is runnning. My database is still empty. How can I run migration commands or "python manage.py createsuperuser" inside of eb shell? When I open eb ssh <env> and try ls, nothing is shown. Stepping one directory back with cd .. and again ls shows me ec2-user, healthd and webapp. I have not the permissions to enter these folders. Isnt it possible, to run python commands inside of eb ssh? I did also try container commands, .ebextensions/db-migrate.config: container_commands: 01_makemigrations: command: "python manage.py makemigrations" leader_only: true 02_migrate: command: "python manage.py migrate --first main initial && python manage.py migrate" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: <app>.settings After commiting and deploying again with eb deploy, I get this error: eb deploy Creating application version archive "app-xxxx". Uploading: [##################################################] 100% Done... 2021-02-22 12:57:12 INFO Environment update is starting. 2021-02-22 12:58:05 INFO Deploying new version to instance(s). 2021-02-22 12:58:21 INFO Instance deployment successfully generated a 'Procfile'. 2021-02-22 12:58:23 ERROR Instance deployment failed. For details, see 'eb-engine.log'. 2021-02-22 12:58:24 ERROR [Instance: i-xxxx] Command failed on instance. Return code: 1 Output: Engine execution has encountered an error.. 2021-02-22 12:58:24 INFO … -
Why is this Django query annotation with float division so slow?
I have a query with subqueries and annotated with derived calculations: base_query = PlayerReport.objects.filter( # ... some filter conditions ) # Create a sum on the base query, to join later points = base_query.filter(pk=OuterRef('pk')).annotate( points=Sum('player_match__score') ) prices = PlayerPrice.objects.filter( player_report=OuterRef('pk') ).order_by('-date') # The final_query to evaluate final_query = base_query.annotate( # Sum of total points for the player points=Subquery( points.values('points') output_field=FloatField() ) # Latest player price price=Subquery( price.values('price')[:1] output_field=FloatField() ) # This causes a big performance hit price_per_point = _division_exp('points', 'price') # _division_exp is used for other derived calcs # these do not cause noticeable performance problems derived_field2 = _division_exp('field1', 'field2') derived_field3 = _division_exp('field3', 'field4') ) The _division_exp is a convenience helper method that helps us create an expression that guards from zero division. def _division_exp(num_key, denom_key): return Case( When(**{denom_key: 0, 'then': 0}), default=ExpressionWrapper( F(num_key) / F(denom_key), output_field=FloatField() ) ) There are many uses of this division helper, but only the price_per_point causes any sort of problem. Observed query performance on my local machine is: without price_per_point: ~9s with price_per_point: ~16s I've repeated this many times, and I'm sure I've singled it out as what's causing the problem. I've also tried pasting raw queries in a postgres console and the same … -
Error while try to make widget to the form in django
I got error when I try to add widjet to the form The error **File "C:\Users\lib\site-packages\django\forms\fields.py", line 558, in init super().init(kwargs) TypeError: init() got an unexpected keyword argument 'attrs' The model class Video(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) video = models.FileField(upload_to='post-videos') title = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) video_poster = models.ImageField(max_length=255, upload_to='post-videos') The views def VideosUploadView(request, *args, **kwargs): all_videos = Video.objects.all() V_form = Video_form() video_added = False if not request.user.is_active: # any error you want return redirect('login') try: account = Account.objects.get(username=request.user.username) except: # any error you want return HttpResponse('User does not exits.') if 'submit_v_form' in request.POST: print(request.POST) V_form = Video_form(request.POST, request.FILES) if V_form.is_valid(): instance = V_form.save(commit=False) instance.author = account instance.save() V_form = Video_form() video_added = True contex = { 'all_videos': all_videos, 'account': account, 'V_form': V_form, 'video_added': video_added, } return render(request, "video/upload_videos.html", contex) The form class Video_form(forms.ModelForm): class Meta: model = Video fields = ('title', 'description', 'video', 'video_poster') widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'description': forms.TextInput(attrs={'class': 'form-control'}), 'video': forms.FileField(widget=forms.FileInput(attrs={'class': 'form-control'})), 'video_poster': forms.ImageField(attrs={'class': 'form-control'}), } -
ValueError: Cannot assign "<Airport: Name:Viru ....>": "Route.origin" must be a "Airport" instance
I a creating a Django app where my models (for now) include Airport, Airline and Route. Where a route is a model which has only three ForeignKey fields: Route.airline should be an Airline instance while Route.destination and Route.origin should be Airport instances. Previously, I have filled my database with Airports and Airlines and now trying to run following migration but got a ValueError: from django.db import migrations from flights.aviation import list_routes from flights.models import Airline, Airport #this func returns list of dicts that include IATA and ICAO etc routes = list_routes() def add_routes(apps, schema_editor): # We can't import the model directly as it may be a newer # version than this migration expects. We use the historical version. Route = apps.get_model('flights', 'Route') for route in routes: try: origin=Airport.objects.get(IATA=f"{route['dep_iata']}") except Airport.DoesNotExist: try: origin=Airport.objects.get(ICAO=f"{route['dep_icao']}") except Airport.DoesNotExist: continue try: destination=Airport.objects.get(IATA=f"{route['arr_iata']}") except Airport.DoesNotExist: try: destination=Airport.objects.get(ICAO=f"{route['arr_icao']}") except Airport.DoesNotExist: continue try: airline=Airline.objects.get(IATA=f"{route['airline_iata']}") except Airline.DoesNotExist: try: airline=Airline.objects.get(ICAO=f"{route['airline_icao']}") except Airline.DoesNotExist: continue new = Route() new.origin = origin new.destination = destination new.airline = airline new.save() I was not expecting ValueError: Cannot assign "<Airport: Name:Viru ....>": "Route.origin" must be a "Airport" instance. because Airport.objects.get returns a single object that is an Airport. And error text is also not very explanatory. -
Django (PySerial): SerialException | [Errno 2] could not open port | [Errno 2] No such file or directory in Production
I have a function in Django that reads data from a scale terminal. The function works perfectly on my computer in Dev mode when I have the scale connected to my computer USB port. I can actually get the weight on the scale connected on my computer. However, when I host the same code in the production server (running Ubuntu 18.04), I get the following error when I try to access the same function from a client machine with the scale connected via USB port: SerialException at /receiving_app/scale_reader/ [Errno 2] could not open port /dev/cu.usbserial-14440: [Errno 2] No such file or directory: '/dev/cu.usbserial-14440' Port '/dev/cu.usbserial-14440' is the one on my computer that works if I am testing the code locally. But when I put the same code in production and I try to access the same function whilst connecting the scale on the same port, that's when I get the error. Below is the function snippet of code: def scale_reader(request): com_port = request.session['com_port'] if sys.platform == "win32": com_port = 'COM'+com_port elif sys.platform == "win64": com_port ='COM'+com_port else: com_port = com_port ser = serial.Serial(port=com_port, baudrate=9600, timeout=2) if not (ser.isOpen()): try: ser.isOpen() messages.info(request, f"Serial port is open on {com_port}") except: messages.error(request, "Error … -
OAuth: Securing a Django-rest API for server-to-server requests
I am creating an API using the Django-rest-framework. The API will only be communicating with other servers and needs to use the OAuth Client Credentials Authorization Flow to authorize requests. I have tried looking through the The Django-OAuth-Toolkit and others for guidance but they all seem to be centered around client-server use cases. How can use OAuth to authorize my Django-rest API when communicating with other servers? Any links to helpful resources and documentation will be much appreciated thanks. -
Django templates "include" tag with jQuery
I'm trying to lessen the repetition of appending the same div. I am using ajax and I want to pass a context to another file after every successful posts but it always results to TemplateSyntaxError. Is it possible to do something like this in jQuery or am I just doing it wrong? Thanks in advance! $.ajax({ url: "{% url 'namespace:name' %}", data: { item: "123" }, method: "POST", success: (response) => { let data = JSON.parse(response); $('#container').append(`{% include "partials/repeating_item.html" with response=${data} %}`); } }); -
Sending an array as data with APIClient on Django?
I'm designing a backend with Django Rest Framework. I have this endpoint that expects to receive with each HTTP request, an array of numbers in the data of the request. This works just fine when the frontend communicates with the backend, the problem is that I can't test it. I'm currently using the APIClient class that comes with the framework for my integration tests, but if I try to write inside a test something like: client.post('/my-endpoint/', data=[1,2,3]) I get the error: AttributeError: 'list' object has no attribute 'items' If I try passing the array as a positional argument instead of as 'data' I get the same error. How can I pass an array as data with APIClient? -
Django Python Create function that generate random code file and verify file from url
I want to create function for my django website project. how to works for me? First Generate a .txt random name file and give output to user and user can download it and upload on its server and after enter file url then verify in our database. -
How can I make the multi-select function in django admin
I am using the ManyToManyField in Django models and would like to change the interphase to something better rather than the default interphase. This is the default interphase, how can I make it like a multiple select items. -
Frontend and backend in one single docker container. Which IP address to use?
I have a docker container running a frontend (react) on port 3000 and a backend (django) on port 8000. From inside the container I can run wget localhost:8000/ and I get back what the server has to give me back. This also works if I forward port 8000 and I call wget from outside the container. But what about the frontend? Since it resides in the same container of the backend, I suppose it resides in the same localhost, so it should be able to retrieve the information from the backend using wget localhost:8000/ But this is not what happens (I get ERR_CONNECTION_REFUSED) Is it because when I run the frontend, the request comes actually from the browser on my local machine, which lives outside the container (and also outside the server)? Or am I getting something wrong and wget localhost:8000/ should work also from my browser? -
ModuleNoFound Error ,while using num2words
I successfully installed num2words with pip install num2words in my django project. when I import it by as follows from num2words import num2words and use it as num2words(amount) I am getting error from num2words import num2words ModuleNotFoundError: No module named 'num2words' -
Django admin model automatically deletes
I hosted my django website on heroku becuase it was only option for me due to some reasons, now I have to push files to it when I do any changes, In admin, I have a model named contact for contacting in my website, First time, I pushed it to the heroku master, It was pushed with no data inside it, now whenever someone contacts me and data is added, It stays there for sometime and then it automatically changes to how much data it came with in starting, Please help me and tell me the fixes ! Whenever I have to push changes I do it with this command git status git add (only the file I changed file) git commit -m "make it better" git push heroku master -
How to set notification system in Django?
I am trying to create a notification system with Django. I have an approval process in my project. A user approves a document according to his/her role. For example manager sent a document to the regional manager and wait for the approval. When the manager sends the document it goes to the regional manager's pending approvals list. I created these tables. What I want to is When the user's pending approval is found, write it in the notification icon above. How can I do it? There is a picture for understanding clearly. views.py def approval(request): current_user = request.user rank_priority = RankPriority.objects.filter(rank = current_user.rank) priority = rank_priority[0].priority pend_list = ApprovalProcess.objects.filter(status = priority ) submit_list = ApprovalProcess.objects.filter(user_id = current_user) context = { 'pend_list': pend_list, 'submit_list': submit_list } return render(request, 'approvals.html', context) approvals.html <div class="content"> <div class="page-inner"> <div class="page-header"> <h4 class="page-title">Approvals</h4> </div> <div class="row"> <div class="col-md"> <div class="card"> <div class="card-body"> <ul class="nav nav-pills nav-secondary" id="pills-tab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="pills-home-tab" data-toggle="pill" href="#pills-home" role="tab" aria-controls="pills-home" aria-selected="true">Pending Approvals</a> </li> <li class="nav-item"> <a class="nav-link" id="pills-profile-tab" data-toggle="pill" href="#pills-profile" role="tab" aria-controls="pills-profile" aria-selected="false">Submitted Approvals</a> </li> </ul> <div class="tab-content mt-2 mb-3" id="pills-tabContent"> <div class="tab-pane fade show active" id="pills-home" role="tabpanel" aria-labelledby="pills-home-tab"> <div class="card"> <div class="card-title">Pending Approvals</div> <div class="card-body"> <table … -
Django turning Async, is it enough to replace the complete Async framewoks
We use another Complete Async Python framework, FastAPI, and it works well in serving various use cases. We have strong inclination to use Django, which certainly has lot of simple integrations and quick development, especially when it is already on its way to turn ASGI and seamlessly transfers context between WSGI and ASGI. However as of now in v 3.1 only Async Views are introduced, which needs threads to communicate between Sync and Async, metnioned here SyncToAsync. Now my primary questions are related to the perfromance of 100 concurrent DB IO requests to Django Asgi vs Fast API Asgi: Will they work in a similar way internally with not much differnce in the perfromance ? Do we need to be specially careful while calling inbuilt integrations in Django, which are not yet Async or the simple decorator works ? Does the debugging of the FastAPI ASGI same as mixed Async Sync in case of Django ? Following is my understanding, but need extra view to confirm my understanding: There will substantial difference between pure Async and sync to Async perfromance, since Django cannot first provision 100 threads in one go, that's an OS resource and even if it does then … -
How do I copy automatic to the clipboard using Python.....?
i have problem in my code problem is: copy automatic to the clipboard using Python not working?please help me. -
Change setted model field in admin panel
Here is my model: class Dummy(models.Model): field1 = models.CharField(max_length=50, blank=True) field2 = models.CharField(max_length=50, blank=True) monthly_limit = models.IntegerField(choices=STEPS_FOR_MONTHLY_USER_LIMIT, default=STEPS_FOR_MONTHLY_USER_LIMIT[8][1]) Choices in my setting are some numbers (10, 20, etc) Here is my admin registration of this model: from models import Dummy from django.contrib import admin admin.site.register(Dummy) In admin panel logically when i go to Dummy model in gives to fill up field 1, filed1 and monthly_limit with choice filed (10, 20, etc.). Is there way to eliminate this choices for monthly_limit filed in admin panel. Because i want the admin to be able to put whatever positive integer he wants, without any restrictions ? -
I need a way to remove some strings in a link
I am working on an application whereby I am inserting url from the database into the anchor tag, which works well, but the issue is that there is a translation in the application whereby there is /en/ or //ar in the link which i would like to remove. templates.html {% for x in my_announcement %} <div class="card container mt-4 mb-5"> <h5 class="card-header">From: the dean</h5> <div class="card-body"> <a href="media/{{x.Attachment}}"><button class="btn btn-outline-info btn-sm">View file</button></a> </div> </div> {% endfor %} The link URL is http://localhost:8000/en/media/announcement/charts-sparklines.html but i would like to remove the /en/ or /ar/ in it. I want the final URL format to be http://localhost:8000/media/announcement/charts-sparklines.html -
Saving Pandas DataFrames to a SQL Database in Django
I am deploying a simulation model written in Python using Django. The input of the simulation model is a multi-sheet Excel file. Currently the simulation model runs locally by reading each sheet and saving the contents of each sheet to a Pandas DataFrame, which are then used as inputs. I have a web app built in Django and want to link it to the simulation model such that a user can upload the multi-tab Excel file via the web app. In the back-end I want the DataFrames created from each Excel sheet to be written to a SQL Database. Every time a new Excel file is uploaded, the new DataFrames must also be saved. As such a user can choose via the web app which input Excel file to run the simulation on. Is it possible to write the DataFrames to the SQL database directly or do they have to be saved as Django Models? And if so, which would be the best option? -
Django returns an array instead of a dictionary (rest-api-framework
I send a post request with data (using requests.post('url', data=data) ): data = { 'token':1234, 'data':{ 'name':'test', 'etc':True, } } When processing reguest.POST in django i get: <QueryDict: {'token':[1234], 'data':['name', 'etc']} > What could be the reason?