Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Enabled CORS White listing for Cross Origin Requests, Now I do not get CORS Error but my API Code gets Executed
I have enabled Cross Origin Requests by using the following approach: 1.Add corsheaders to INSTALLED_APPS INSTALLED_APPS = [ ... 'corsheaders', ... ] 2.Add CorsMiddleware to MIDDLEWARE LIST MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] 3.Define list of whitelisted Origins from which Request is allowed. CORS_ORIGIN_WHITELIST=['abc.com', 'xyz.com'] By enabling this Cross Origin Request I am not getting CORS Error in Browser for WhiteListed Origins but When I can access my APIs from Origin which mentioned in WhiteListed Origins, it gives me CORS Error in browser but My API Code gets executed means Django is calling my API before checking whether the request is from WhiteListed Origin or not. I want to Block such Cross Origin Request before my API get Called. How can we do it? Note: I have also tried Whitelisting using Signals, but I gets same Result as Whitelisting by CORS_ORIGIN_WHITELIST -
Linking Django with PysimpleGUI
I am really new to both of them. I have created a app with PysimpleGUI that gets the webcam input. So I need to link it to a website that uses Django, so that the webcam input is displayed on a webpage. What I need to know is whether it is possible to connect the two components together and/or are there any alternatives ? -
Python Django: Insert dynamic form records to db
It is a Medical Lab Software solution. A user makes lab investigation request that is unique to a patient’s encounter, I.e., a patient can have 1 or more request per encounter. This uniqueness is denoted by the encounter_id. The challenge now is the ability to send the results back to the requester. I am able to display all requests per encounter_id on a template but unable to return the result since each result is tied to a particular investigation. This is largely because I have a limited knowledge on JS. My current approach can only submit one record, usually the last record Here’s the URL that displays the result template: https://smart-care.herokuapp.com/labs/lab_results/1/ Here’s the django template: <div class="container"> <form id="myForm" method="POST" action="">{% csrf_token %} {% for request in lab_request %} {{ request.test }}: <input type="text" class="result" id="{{ request.test.id }}" name="test_id"> <br> {% endfor %} <br><br> <button>Send Result</button> </form> </div> Here’s my view: def lab_results_view(request, enc_id): lab_request = LabRequest.objects.filter(encounter_id=enc_id, done=False, decline=False) # Get values from tempalte if request.POST.get('test_id'): entered_result = LabRequest() entered_result.result = request.POST.get('test_id') new_result = entered_result.result print("Just = ",new_result) template = "labs/lab_results.html" context = {"lab_request":lab_request} return render(request, template, context) The models: class LabRequest(models.Model): encounter = models.ForeignKey(PatientEncounter, on_delete=models.CASCADE, blank=True, null=True) patient = … -
Why Django admin search field taking too much time to response?
It's my first time to handle project with large data. I have 16millions of data. When i query in django shell it give me result in few seconds. But on django admin site when i register my model and apply search field . It takes too much time to query. I tried django debug toolbar and here is the result it's showing me Django debug toolbar result models.py: class TrademarkAvailability(models.Model): serial_number = models.IntegerField(unique=True) filing_date = models.IntegerField(null=True) status_code = models.IntegerField(null=True) status_date = models.IntegerField(null=True) mark_identification = models.CharField( max_length=5000, null=True, blank=True, db_index=True) mark_drawing_code = models.CharField( max_length=5000, null=True, blank=True) attorney_name = models.CharField(max_length=5000, null=True, blank=True) current_location = models.CharField(max_length=5000, null=True, blank=True) employee_name = models.CharField(max_length=5000, null=True, blank=True) correspondent = models.JSONField() classifications = models.JSONField(null=True) case_file_owners = models.JSONField(null=True) transaction_date = models.JSONField(null=True) registration_number = models.JSONField(null=True) case_file_statements = models.JSONField(null=True) case_file_event_statements = models.JSONField(null=True) admin.py @admin.register(TrademarkAvailability) class TrademarkAdmin(admin.ModelAdmin): list_display = ("mark_identification",) search_fields = ["=mark_identification"] paginator = LargeTablePaginator show_full_result_count = False -
Django and keyclok AUTHENTICATION BACKEND error
In my djando application i create my own middleware for authentication using keycloak, I create my class as: class KeycloakMiddleware(MiddlewareMixin): def __init__(self, get_response): """ :param get_response: """ self.keycloak_authorization_config = settings.KEYCLOAK_CONFIG.get('KEYCLOAK_AUTHORIZATION_CONFIG', None) self.default_access = settings.KEYCLOAK_CONFIG.get('KEYCLOAK_DEFAULT_ACCESS', "DENY") self.method_validate_token = settings.KEYCLOAK_CONFIG.get('KEYCLOAK_METHOD_VALIDATE_TOKEN', "INTROSPECT") # Create Keycloak instance self.keycloak = KeycloakService.connect_authentication_client() # Read policies if self.keycloak_authorization_config: self.keycloak.load_authorization_config(self.keycloak_authorization_config) # Django self.get_response = get_response .... and in my django settings.py i do: MIDDLEWARE = [ ... 'myapp_backend.utils.keycloak_middleware.KeycloakMiddleware', ... and AUTHENTICATION_BACKENDS = ( 'myapp_backend.utils.keycloak_middleware.KeycloakMiddleware', ) but when i run my /admin app i get: TypeError at /admin/login/ init() missing 1 required positional argument: 'get_response' If i try to leave AUTHENTICATION_BACKEND params blank i get an error because no AUTHENTICATION_BACKEND was defined. How can i pass the get_response argument from my django settings to my middleware for authentication? So many thanks in advance Manuel -
Django query looping
I have been trying to work out a more efficient way of doing below. Does one exist? The issue is i have to do this loop 100 times (in my test case but more in real life), and there are about 100 items in each loop, which makes it really quite slow. There must be a way to compare query results something like array.filter in JS. But i cant seem to find it for Django. for choice in question.answer_choices.all(): amount = 0 for ans in q_answers: if choice in ans.answers.all(): amount += 1 It is basically getting the choice of answers and counting how many match to give me a result for each choice from a set of answer choices. q_answers is just an array of answers that were given by user for 'question'. -
adding image in pdf using Django pisa: standard {% static 'path/to/image' %} do not working
I try to implement pdf output using pisa following this tutorial: https://www.codingforentrepreneurs.com/blog/html-template-to-pdf-in-django/ and it works except for images that are not displayed I understand the problem deal with relative/absolute path between pisa and Django system but do not manage to resolve. I read the solution in the xhtml2pdf document using link_callback method but it dosen work and have no error If I pass the absolute url of images in context to my html template it works : <img class="logo" src="{{ url }}" alt="logo alima"> -
Django 3, model textField returns byte string while saved a string
I have updated my Django version from Django 2.1.4 to Django 3.2.3 Now I am facing a weird behavior of my apps. I am saving string data in my textFiled of the model, but when I retrieve data from model it returns byte string which is not serializable in JSON. I have verified saved data in DB is string type. For now, I have overridden Django model method from_db and checking the data type and changing it. But I think this is not a good solution. using AWS MySQL aurora db, Django 3.2.3 and python 3.6 Your suggestions will be appreciated. -
Django 3 run server error ImproparlyConfigured on django 3
I installed the newest version of Django and when I did the runserver command it showed a really long error. I searched the internet for it but most of the sollutions I found were either not working or outdated. The error: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS _MODULE or call settings.configure() before accessing settings. Please help me as I have been stuck on this for a really long time. Thanks -
How can I group two same products to show them as one in django?
*Now as u see in the database table. In this table, we have two oranges but have different prices because pack size. From this table, I want to get data in this way that on my project product view list oranges shows only once and if we go to the product detail we have a combo box where we can display the different size of pack from the table like oranges. Oranges should we shown once from this table to the product list by grouping them and after going to oranges details we can see both the oranges packaging in a combo box. * -
hamburger icon not opening
my hamburger icon is currently not opening, i figure that is a problem with my javascript, any other tips and tricks when coming to javascript are very much welcome, i am a beginner so your assistance would be very much appreciated java.js $('.open-overlay').click(function() { var overlay_navigation = $('.overlay-navigation'), nav_item_1 = $('nav li:nth-of-type(1)'), nav_item_2 = $('nav li:nth-of-type(2)'), nav_item_3 = $('nav li:nth-of-type(3)'), nav_item_4 = $('nav li:nth-of-type(4)'), nav_item_5 = $('nav li:nth-of-type(5)'), top_bar = $('.bar-top'), middle_bar = $('.bar-middle'), bottom_bar = $('.bar-bottom'); overlay_navigation.toggleClass('overlay-active'); if (overlay_navigation.hasClass('overlay-active')) { top_bar.removeClass('animate-out-top-bar').addClass('animate-top-bar'); middle_bar.removeClass('animate-out-middle-bar').addClass('animate-middle-bar'); bottom_bar.removeClass('animate-out-bottom-bar').addClass('animate-bottom-bar'); overlay_navigation.removeClass('overlay-slide-up').addClass('overlay-slide-down') nav_item_1.removeClass('slide-in-nav-item-reverse').addClass('slide-in-nav-item'); nav_item_2.removeClass('slide-in-nav-item-delay-1-reverse').addClass('slide-in-nav-item-delay-1'); nav_item_3.removeClass('slide-in-nav-item-delay-2-reverse').addClass('slide-in-nav-item-delay-2'); nav_item_4.removeClass('slide-in-nav-item-delay-3-reverse').addClass('slide-in-nav-item-delay-3'); nav_item_5.removeClass('slide-in-nav-item-delay-4-reverse').addClass('slide-in-nav-item-delay-4'); } else { top_bar.removeClass('animate-top-bar').addClass('animate-out-top-bar'); middle_bar.removeClass('animate-middle-bar').addClass('animate-out-middle-bar'); bottom_bar.removeClass('animate-bottom-bar').addClass('animate-out-bottom-bar'); overlay_navigation.removeClass('overlay-slide-down').addClass('overlay-slide-up') nav_item_1.removeClass('slide-in-nav-item').addClass('slide-in-nav-item-reverse'); nav_item_2.removeClass('slide-in-nav-item-delay-1').addClass('slide-in-nav-item-delay-1-reverse'); nav_item_3.removeClass('slide-in-nav-item-delay-2').addClass('slide-in-nav-item-delay-2-reverse'); nav_item_4.removeClass('slide-in-nav-item-delay-3').addClass('slide-in-nav-item-delay-3-reverse'); nav_item_5.removeClass('slide-in-nav-item-delay-4').addClass('slide-in-nav-item-delay-4-reverse'); } }) my html <div class="overlay-navigation"> <nav role="navigation"> <ul> <li><a href="#" data-content="The beginning">Home</a></li> <li><a href="#" data-content="Curious?">About</a></li> <li><a href="#" data-content="I got game">Skills</a></li> <li><a href="#" data-content="Only the finest">Works</a></li> <li><a href="#" data-content="Don't hesitate">Contact</a></li> </ul> </nav> <section class="home"> <div class="open-overlay"> <span class="bar-top"></span> <span class="bar-middle"></span> <span class="bar-bottom"></span> </div> </section> -
i wanted to send a json response through url so that i can retrieve it from url in android app and display it in list but my code produces wrong json
this is how i got when i try to print it [{"model": "api.product", "pk": 1, "fields": {"productname": "keyboard", "productdesc": "keyboard is made by sony", "amount": 200.0, "available": 20, "image": "pics/Send.png"}}] but i wanted it in a correct way so that i can retrieve it form the application my django views.py: from django.http import HttpResponse from django.core import serializers as core_serializers from rest_framework import serializers from .models import users,product from django.views.decorators.csrf import csrf_exempt @csrf_exempt def viewproduct(self): obj=core_serializers.serialize('json',product.objects.all()) return HttpResponse(obj,content_type='application/json') models.py from django.db import models class users(models.Model): username=models.CharField(max_length=100) password= models.TextField() email=models.EmailField() class product(models.Model): productid=models.AutoField(primary_key=True) productname=models.CharField(max_length=255) productdesc=models.CharField(max_length=255) amount=models.FloatField(max_length=25) available=models.IntegerField() image=models.ImageField(upload_to='pics') -
Django: How to edit old model to have PK serializable
I have a model in Django with a custom Primary Key that I want to be serializable. When I created the model it automatically added serialize=False to the original migration. How can I now edit/change to have the primary key serializable? Thanks -
How to pass csrf token in Nuxt.js/auth to django backend?
I'm trying to find a solution for 3 days now and I didn't find anything related to my problem. I have a Nuxt.js frontend that uses the auth module to get a JWT token from a DRF backend. After login, the server prints out this: Forbidden (CSRF cookie not set.): /api/accounts/login/ [04/Jun/2021 10:36:44] "POST /api/accounts/login/ HTTP/1.1" 403 2870 In the network tab, I can see this in the request headers when I try to log in: X-CSRFToken: csrftoken, which means that the csrf token is not passed properly. Right? In my nuxt.config.js file, I have these settings: axios: { baseURL: 'http://localhost:8000', headers: { "X-CSRFToken": "csrftoken", }, xsrfCookieName: "csrftoken", xsrfHeaderName: "X-CSRFToken", }, // authentication module configuration auth: { strategies: { local: { endpoints: { login: { url: '/api/accounts/login/', method: 'post', propertyName: 'access', altProperty: 'refresh' }, logout: {}, user: false } } }, redirect: { login: '/login', }, }, router: { middleware: ['auth'] }, Here is my login script: export default { data() { return { user: { username: "", password: "", }, }; }, methods: { async login() { try { await this.$auth.loginWith("local", { data: this.user, }); console.log("VALID"); } catch (err) { console.log("INVALID"); } }, }, }; How can I pass … -
The best way to PDF generation with next.js - each page has its own template
I'm working on an application which generates multi-page, each page has its own template how to do this with Next.js, but any starting points would be appreciated. backEnd: Django frontEnd: next.js Thanks -
Django-Celery No Periodic Outputs
I am trying to use Celery to create periodic tasks in my application. However, I cannot see the outputs of the periodic task that I wrote. The backend is on a Windows-based redis-server. The server is up and running. project/celery.py import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nttracker.settings') app = Celery app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.update( result_expires=3600, ) @app.task def add(x, y): z = x + y print(z) app.conf.beat_schedule = { 'add-every-30-seconds': { 'task': 'tasks.add', 'schedule': 30.0, 'args': (16, 16) }, } if __name__ == '__main__': app.start() project/tests.py from __future__ import absolute_import import django django.setup() from .celery import app @app.task def add(x, y): return x + y @app.task def mul(x, y): return x * y @app.task def xsum(numbers): return sum(numbers) However, when I ran celery -A project worker --pool=solo -l INFO, I get: -------------- celery@LAPTOP-A0OM125L v5.0.5 (singularity) --- ***** ----- -- ******* ---- Windows-10-10.0.19041-SP0 2021-06-04 16:45:29 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: nttracker:0x22698b76340 - ** ---------- .> transport: redis://127.0.0.1:6379// - ** ---------- .> results: - *** --- * --- .> concurrency: 12 (solo) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- … -
Python requests_html throwing error There is no current event loop in thread 'ThreadPoolExecutor-0_0'
I am trying to run a JS script using python requests_html module for a given url but was getting few errors. Can some please help me out? Code :- from requests_html import HTMLSession def rrr(request): session = HTMLSession() url = 'https://careers.microsoft.com/' response = session.get(url) script = """ () => { return { ans: window.location.href, } } """ ans = response.html.render(script=script) return JsonResponse(ans, safe=False) Error :- File "/home/mahesh/anaconda3/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/home/mahesh/anaconda3/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/home/mahesh/anaconda3/lib/python3.7/site-packages/rest_framework/decorators.py", line 50, in handler return func(*args, **kwargs) File "/home/mahesh/Documents/dojo/dojo/dojo/tenants/api.py", line 242, in rrr ans = response.html.render(script=script) File "/home/mahesh/anaconda3/lib/python3.7/site-packages/requests_html.py", line 586, in render self.browser = self.session.browser # Automatically create a event loop and browser File "/home/mahesh/anaconda3/lib/python3.7/site-packages/requests_html.py", line 727, in browser self.loop = asyncio.get_event_loop() File "/home/mahesh/anaconda3/lib/python3.7/asyncio/events.py", line 644, in get_event_loop % threading.current_thread().name) RuntimeError: There is no current event loop in thread 'ThreadPoolExecutor-0_0'. When ran in terminal, it worked fine as follows -
python serve mp4 files securely
I am building video serving service on python (django framework). The main requirement is that users should not be able to see mp4 direct link. I was thinking about generating .ts files with subprocess using ffmpeg like this: import subprocess infile = 'video.ts' outfile = 'video.mp4' subprocess.run(['ffmpeg', '-i', infile, outfile]) but as I guess it will take a lot of resources (in a RAM) if multiple users try to watch videos can you suggest any native(in python) or third party solution(maybe there are some API services)? thanks in advance -
Unable to Authenticate login page in Django when created a new database using Models.py
I have created a new table using models.py and this table stores data to my models.py table which I created. Now when I am going to my login page its not able to authenticate the details from that table and always gives invalid credentials. My app name which I created is User and the table name which is stored in SQLite is User_register Login.html <div class="wrapper gradient"> <div class="container"> <div class="row centered-form"> <div class="col-xs-12 col-sm-8 col-md-4 col-sm-offset-2 col-md-offset-4"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"><center><b>Login To Web App!!</b></center> </h3> </div> <div class="panel-body"> <form role="form" method="POST"> {% csrf_token %} <div class="form-group"> <input type="text" name="email" id="email" class="form-control input-sm" placeholder="Username"> </div> <div class="form-group"> <input type="password" name="password" id="password" class="form-control input-sm" placeholder="Password"> </div> <div class="form-group"> {% for message in messages %} <p style="color:black;">{{message}}</p> {% endfor %} </div> <input type="submit" value="Login" class="btn btn-info btn-block"> </form> </div> </div> </div> </div> </div> </div> Models.py class Register(models.Model): first_name = models.CharField(max_length=90) last_name = models.CharField(max_length=90) email = models.EmailField(max_length=90) password = models.CharField(max_length=90) Views.py def login(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user = auth.authenticate(email=email, password=password) if user is not None: auth.login(request, user) return render(request,'index.html') else: messages.info(request, 'Invalid credentials') return render(request,'login.html') else: return render(request, 'login.html') -
Custom Django admin: unable to assign users to a group because of field rendering
I'm currently working on a Django app on which I have created a custom admin section (i know of the existing default admin section, but could not use it). The "admin" of the website should be able to CRUD users and assign them to a group (either "admin" or "manager" group). I'm having difficulties upon CRUD users on assigning them to either group, because the rendering of the group field. I have to highlight the group I want to put the user in, but upon saving the user is not assigned to the group chosen. I'm guessing I will have to put this field in some sort of widget but I'm unable to find the solution. Hereunder the code forms.py class AdminUserCreateForm(UserCreationForm): """UserCreateForm custom made class""" class Meta: """ Meta definitioon of UserCreateForm""" model = User fields = [ 'username', 'last_name', 'first_name', 'password1', 'password2', 'email', 'is_staff', 'is_active', 'is_superuser', 'groups', ] views.py (just a create use view here for example) @group_required('Administrator') def admin_create_user(request): if request.method == "POST": admin_user_create_form = AdminUserCreateForm(request.POST) if admin_user_create_form.is_valid(): admin_user_create_form.save() if request.user.groups.filter(name__in=['Administrator']).exists(): return redirect('admin_home') else: return redirect('manager_home') else: admin_user_create_form = AdminUserCreateForm() context = { 'admin_user_create_form': admin_user_create_form, } return render(request,'admin_create_user.html', context) template <!-- template admin_create_user.html --> {% extends 'base.html' … -
"mod_wsgi-express module-config" command not working in windows command Prompt?
"MOD_WSGI_APACHE_ROOTDIR=C:\xampp\Apache" in windows environment variable but Not work mod_wsgi-express module-config command .I got this error [mod_wsgi-express module-config][1] -
Django ValueError in form
I am trying to submit a form by pulling post data from form fields and plugging it into my view. I have the following model class ExerciseEdl(models.Model): unit = models.ForeignKey(Units, models.CASCADE) exercise = models.ForeignKey(Exercises, models.CASCADE) equipment = models.ForeignKey(Equipment, models.CASCADE) quantity = models.IntegerField() location = models.ForeignKey(Locations, models.SET('Unassigned'), db_column='location') And the following view def add_edl_item(request, unit_pk, ex_pk, *args, **kwargs): ex_instance = Exercises.objects.get(pk=ex_pk) unit_instance = Units.objects.get(pk=unit_pk) if request.method == "POST": print(request.POST) ExerciseEdl.objects.update_or_create( unit=unit_instance, exercise=ex_instance, equipment=request.POST.get('equipment'), quantity=request.POST.get('quantity'), location=request.POST.get('location') ) messages.success( request, f'{unit_instance.unit_name} EDL for {ex_instance.exercise} successfully updated') return redirect('exercise-equipment', ex_pk=ex_pk, unit_pk=unit_pk) else: messages.error( request, f'Failed to update the {unit_instance.unit_name} EDL for {ex_instance.exercise}.') And I am using data from this form to input the equipment, quantity, and location fields. <form action="{% url 'add-edl-item' ex_pk=ex_instance.id unit_pk=unit_instance.id %}" method="post"> {% csrf_token %} <label for="equipment">Equipment</label> <select class="form-control" id="id_equipment" name="equipment"> {% for equip in equip_list %} <option value="{{equip.id}}">{{equip.tamcn}} - {{equip.nomen}}</option> {% endfor %} </select> <div class="mb-3"> <label for="quantity" class="form-label">Quantity</label> <input id= "id_quantity" type="number" class="form-control" name="quantity"> </div> <div class="mb-3"> <label for="location">Location</label> <select class="form-control" id="id_location" name="location" value=""> {% for loc in locations %} <option value="{{loc.id}}">{{loc.location}}</option> {% endfor %} </select> </div> <input class="btn btn-primary" type="submit" value="Submit"> </form> The quantity is fine, it's just an integer, the other two fields however, give the … -
Attach created object to another existing objects with M2M relatonship
I have a little question, I have two models, Account and Services. Account can be attached to one or several services (Many2Many relationship). Services are pre-existing in the DB. How can I attach the account I create by doing POST to these services by passing a list with their id's? When I try it now, I receive the answer "These id's are already existing" -
Finding Selected Value of Widget in Django Forms
Im new to django framework ..and im having a situation when a browser back button is pressed, the form is rendered in the context of GET method without any query dict specified. However i could see the value for select widget (named as state in the below code) holding the last set value I would like to know how we can find what value the widget is holding in the forms class # in forms.py class MyCustomForm(forms.Form): items = [('', 'Select Your Choice'), ('1', 'NAME'), ('2', 'AGE') ...] item = forms.CharField(required=True, initial='', widget=forms.Select(attrs={'class': 'form-control'}, choices=items)) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if 'item' not in self.data: # WHEN BACK IS PRESSED I see we are landing here in the context of GET method. # And the field 'item' is holding valid value from previous selection # Lets assume i selected AGE, and that is being shown properly in the page after going back # i would like to know how to read that selected value here # in views.py @never_cache def index(request): if request.method == 'GET': form = MyCustomForm() return render(request, 'mypage.html', {"form": form}) -
How to convert a pandas plot into an image
I am working on an app which will be able to show a graph of the company's performance in stocks, I wanted to turn the pandas plot of that company into an image without saving it. Can someone tell me what to do? from fastquant import get_pse_data import matplotlib.pyplot as plt import pandas as pd df = get_pse_data(symbol, '2019-01-01', '2020-01-01') ma30 = df.close.rolling(30).mean() close_ma30 = pd.concat([df.close, ma30], axis=1).dropna() I want to create a python function that will allow me to return it as an image for a django code. Thank you for the help!