Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djan-go run sslserver
I have this code for CMD to run the website with ssl py manage.py runsslserver 127.0.0.1:8384 but today I decided to use waitress-serve, this is the code I use in CMD to run the website without SSL waitress-serve --listen=*:8384 tracker.wsgi:application Now, I don't know how to run the website with SSL using waitress-serve code. Please help. -
Redirect link with token to the correct page
i am implementing email verification on my website, i am sending a link/"token" to the user, how do i make it so that the link redirects to success/failed page, here is how am sending the link (i am using React on the front end if that matters) views.py @api_view(['POST']) def sendmail(request): FRONTEND_URL='http://127.0.0.1:8000' token = get_random_string(length=32) verify_link = FRONTEND_URL + '/email-verify/' + token subject, from_email, to = 'Verify Your Email', 'my@email', request.data['to'] html_content = render_to_string('verify_email.html', {'verify_link':verify_link, 'base_url': FRONTEND_URL}) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return JsonResponse({"message": "email sent"},status=HTTP_200_OK) -
How Use Django to maintain cross domain session?
Trying to build a service similar to fast.co where user session/token/credentials are maintained within the browser when user login to fast.co and is shared between other partner websites for single-click payments. I am using Django with javascript, jquery. How to share session details of the user of abc.com with xyz.com or cde.com etc., What are the possible ways to do it and please provide any code snippet if available? -
Prefilter queries in django for a session
Currently I have an unique UUID tied to all models, including a one to one relation with the user model. For filtering data based on this UUID, I save the UUID as a session variable for the logged in user and then in the views, data = Model.objects.filter(unique_num=request.session.get('unique_num')) Is it possible to prefilter these queries. For example, if the user logs in, I should just be able to data = Model.objects.filter() and it should show only related data. -
How can I create a timeline with equal spacing between elements whilst maintaining full width of container?
Issue Description I have created a timeline within a kanban item. The timeline design is exactly what I want but I have an issue with spacing between the timeline elements. I require the timeline to cover the full width of the container with first and last positioned at the very start and end of container but with equal distances between each element. So instead of : O---O--O--O---O and more like: O--O--O--O--O But still maintain full width of the container. JSFiddle: https://jsfiddle.net/cn9m0wfz/5/ CSS .kanban-booking-item .mini-timeline-item { padding:0; display: flex; position: relative; } .kanban-booking-item .mini-timeline-item .item-container { background-color:rgb(209, 209, 209); height:15px; width: 15px; border-radius:10px; display: flex; justify-content: center; } .kanban-booking-item .mini-timeline-item .item { background-color:rgb(255, 255, 255); height:9px; width: 9px; border-radius:5px; margin:3px; } .kanban-booking-item .mini-timeline-item .pipe { background-color: #d1d1d1; height:3px; width: 100%; border-radius:5px; margin:3px; position:absolute; top:3px; } .kanban-booking-item .mini-timeline-item .pipe.pipe-left { left: -16px; } .kanban-booking-item .mini-timeline-item .pipe.pipe-right { right: -16px; } .kanban-booking-item .mini-timeline-item .pipe.pipe-centre-right { right: -9px; width: 50%; } .kanban-booking-item .mini-timeline-item .pipe.pipe-centre-left { left: -9px; width: 50%; } HTML <div class="kanban-booking-item" style="padding: 0px 40px 8px 10px"> <div class="content row" style="padding: 0 15px;"> <div class="mini-timeline-item col" style="justify-content:flex-start;"> <div class="item-container"> <div class="item"> </div> </div> <div class="pipe pipe-right"> </div> </div> <div class="mini-timeline-item col" style="justify-content:center;"> <div … -
Django Form Media creating Exception Value: Missing staticfiles manifest entry for 'lead_management/admin/extra.css'
I have the following within a Form I am using class Media: css = { 'all' : ('lead_management/admin/extra.css',) } I have recently upgraded from Py3.6, Django 2.1.10 to Py3.8, Django 3.1.7. It used to work and it continues to work in development (DEBUG=True). It also works locally with DEBUG=False. But when running in production I am now getting Exception Value: Missing staticfiles manifest entry for 'lead_management/admin/extra.css' This is running on an EC2 instance with the staticfiles in S3. Dev is the same and it was the case prior to upgrade. Why am I getting this error? -
Django Rest Framework URL pattern with json object
I have an Angular/DRF application. What I want is to send an object to my backend to process it: var data = {'url': url, 'name': name} return this.http.get("http://127.0.0.1:8000/api/record/json=" + encodeURIComponent(JSON.stringify(data))) Because my data as URL in it, I URI encode it to escape the "/" Then in DRF this my urls.py: path('record/<str:music_details>', record_views.Record.as_view(), name='record'), And my views.py: class Record(View): def get(self, request): json_string = request.query_params['json'] data = json.loads(json_string) print(data) I have nothing printing in my console, I assume my url path is wrong, how should I fix it? -
Django admin login with either username or email or phone number
I have set USERNAME_FIELD="email" in my customer user model. I have created custom backend authentication class.enter image description here I am only able to login with the phone number. For other two it's showing the error: invalid literal for int() with base 10 -
returns single value while using for loop in django
I am trying to return 2 tables data in one request using for loop. When I print the result its showing correctly but while return first table result only showing. I have tried with yield its not working for Response. I have used return both inside and outside of the loop but not achived. Request please give your suggestion. table_name = "table1,table2" table_multiple = list(table_name.split(",")) con = psycopg2.connect(user=username, host=host, database=db_name, password=password) for tablenames in table_multiple: t_data = pd.read_sql_query(f"select * from {tablenames}", con) table_json = t_data.to_json(orient="records") tableDatum = json.loads(table_json) print(tableDatum) return Response('tableDatum' : tableDatum) -
How can select and load form?
I want to select option 1 and load a form with inputs HTML: <select id="orden" class="form-control" name="orden"> <option disabled selected>Selecciona una opci&oacute;n</option> <option value="1">{{ results.1.op_ser_codigo }}{{ results.1.op_num_codigo }} / ({{ results.1.data_ini }} - {{ results.1.data_fim }})</option> <option value="2">{{ results.2.op_ser_codigo }}{{ results.2.op_num_codigo }} / ({{ results.2.data_ini }} - {{ results.2.data_fim }})</option> <option value="3">{{ results.3.op_ser_codigo }}{{ results.3.op_num_codigo }} / ({{ results.3.data_ini }} - {{ results.3.data_fim }})</option> <option value="4">{{ results.4.op_ser_codigo }}{{ results.4.op_num_codigo }} / ({{ results.4.data_ini }} - {{ results.4.data_fim }})</option> <option value="5">{{ results.5.op_ser_codigo }}{{ results.5.op_num_codigo }} / ({{ results.5.data_ini }} - {{ results.5.data_fim }})</option> <option value="6">{{ results.6.op_ser_codigo }}{{ results.6.op_num_codigo }} / ({{ results.6.data_ini }} - {{ results.6.data_fim }})</option> </select> I want to fill this: (If on select option i select 1 on this inputs fill value 1) <b><p class="black">OP: </b>{{ results.1.op_ser_codigo }}{{results.1.op_num_codigo}} </p> <b><p class="black">Fecha Inicio: </b>{{ results.1.data_ini }} </p> <b><p class="black">Fecha Final: </b> {{ results.1.data_fim }} </p> -
sending a javascript symbol through django json objects does not show
In Django (2.2) I am trying to send a json response like this: return JsonResponse(data, safe=False) In the data object there is this value "unit": "\u33A5" (cubic meters) when I am trying to print this value on my html page using javascript, I get this exact literal instead of the cubic meters symbol. I cannot paste javascript code because this symbol is supposed to be displayed as a y-axis label to an echarts graph, but this what I do: yAxis: { type: 'value', name: data.unit, nameLocation: 'middle', }, If I hardcode this "\u33A5" instead of data.unit in the options the cubic meters symbol appears. my question is how am I supposed to serialize or print correctly javascript symbol codes using the django JSON's response? -
How to enable horizontal scrolling in Django Admin list view?
I really like the Django Admin list view. I would like to show ~30 fields of one table in the list, however my issue is that horizontal scroll bar is not visible in the list view even though data overflows right border. How can I enable scrolling? -
With Django EmailMessage, why headers keys and values sometimes display and sometimes don't?
I am utilizing Email Message from django.core.mail. I am trying to include headers in messages that I want to send. But in some cases, the first header line does not appear in my message. Why ? Example with an issue In the following case, I have an issue : views.py from django.shortcuts import render, redirect from django.core.mail import send_mail, EmailMessage from django.contrib import messages from django import forms from . forms import ContactMessageForm def contact_form(request): form = ContactMessageForm(request.POST or None) context = {'form':form} if request.method == 'POST': if form.is_valid(): contact_form = form.save() contact_form = ContactMessageForm() first_name = form.cleaned_data["first_name"] last_name = form.cleaned_data["last_name"] email = form.cleaned_data["email"] order_number = form.cleaned_data["order_number"] subject = form.cleaned_data["subject"] cc = form.cleaned_data["cc"] message = form.cleaned_data["message"] full_name = first_name + " " + last_name objet = "" if order_number == None: objet = subject else: objet = subject + ' / ' + order_number email_msg = EmailMessage( '[TITLE] : ' + objet, message, 'foo@foo.fr', ['foo@foo.fr'], reply_to = [email], headers = { "Exp ": 'header 1 value', "Prenom et Nom ": full_name, "Objet du message ": str(subject), "Testing header 4 key": 'header 4 value', }, ) email_msg.send() if cc == True: msg = ''' Bonjour, Nous avons bien reçu votre email. … -
starting container process caused "exec: \"./boot.sh\": permission denied": unknown
There is a back.Dockerfile. FROM python:3.9 WORKDIR /src COPY . ./ RUN apt-get update -y RUN pip install --upgrade pip && pip install --no-cache-dir -r requirements.txt RUN chmod +x boot.sh ENTRYPOINT ["boot.sh"] There is a boot.sh in which I do migrations for Django and then start the service. #!/bin/sh while true; do python /src/manage.py migrate if [[ "$?" == "0" ]]; then break fi echo Upgrade command failed, retrying in 5 secs... sleep 5 done exec python /src/manage.py runserver 0.0.0.0:8000 There is a docker-compose. version: "3" services: backend: build: context: . dockerfile: deploy/back.Dockerfile volumes: - .:/src ports: - 8888:8000 depends_on: - db db: image: mysql:8.0.24 ports: - '3307:3306' environment: MYSQL_DATABASE: ${MYSQL_NAME} MYSQL_USER: ${MYSQL_USER} MYSQL_PASSWORD: ${MYSQL_PASS} MYSQL_ROOT_PASSWORD: ${MYSQL_NAME} volumes: - /var/lib/vennepriser-db:/var/lib/mysql When I run sudo docker-compose up, I get the error Tried also such options ENTRYPOINT ["./boot.sh"] ENTRYPOINT ["/src/boot.sh"] How can I fix it? -
How can I deploy with apache my django app using a virtualenv?
I deployed my django app on my apache server. Now, I would like to use a virtualenv on my apache server. How can I do that ? I thought to that : virtualenv myenv source myenv/bin/activate But it works only for my terminal not my django app... How can I do that ? Thank you very much ! -
Ajax is not sending multiselect data to Django views
I am quite new to Django so bare with me. I have a multiselct list in my webpage and I need to send the selected items to my views in order to make use of them. To do so, I used ajax but when it doesn't seem to work for some reason. This is the script: $("#var_button").click(function(e) { var deleted = []; $.each($("#my-select option:selected"), function(){ deleted.push($(this).val()); }); alert("You have deleted - " + deleted); e.preventDefault(); $.ajax({ type: "post", url: "/description/upload-csv/" , data: { 'deleted' : deleted } }); // End ajax method }); I checked with alert if maybe the variable deleted is empty but it return the selected values so the problem is in my ajax query. This is the part where I retrieve the data in my views.py if request.method == 'POST': del_var = request.POST.getlist("deleted[]") my_class.del_var = del_var I changed the data type to text but it doesn't do anything -
Why does django-q throw exception with arrow time
I'm trying to create a Django-q schedule and following the documents to use arrow for the next run I get the following error with the schedule: schedule( func='test.tasks.test_task', name='test_task_nightly', schedule_type=Schedule.DAILY, next_run=arrow.utcnow().replace(hour=23, minute=30), q_options={'timeout': 10800, 'max_attempts': 1}, ) Traceback (most recent call last): File "/usr/lib/python3.8/code.py", line 90, in runcode exec(code, self.locals) File "<console>", line 1, in <module> schedule( File "/home/user/PycharmProjects/app/venv/lib/python3.8/site-packages/django_q/tasks.py", line 122, in schedule s.full_clean() File "/home/user/PycharmProjects/app/venv/lib/python3.8/site-packages/django/db/models/base.py", line 1209, in full_clean self.clean_fields(exclude=exclude) File "/home/user/PycharmProjects/app/venv/lib/python3.8/site-packages/django/db/models/base.py", line 1251, in clean_fields setattr(self, f.attname, f.clean(raw_value, self)) File "/home/user/PycharmProjects/app/venv/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 650, in clean value = self.to_python(value) File "/home/user/PycharmProjects/app/venv/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1318, in to_python parsed = parse_datetime(value) File "/home/user/PycharmProjects/app/venv/lib/python3.8/site-packages/django/utils/dateparse.py", line 107, in parse_datetime match = datetime_re.match(value) TypeError: expected string or bytes-like object Not sure why it's not accepting the time format similar to the example given in the django-q documentation page. -
Replacing an old table with a new one in the Django database using csv file?
Hi I am working on a Django Project and added the functionality of importing a csv file to the Django database using the following code View.py However if I make changes to the csv file and add it to the database it just adds everything and I have the data basically twice in the table. I would like to know if there is any option to just replace the old data in the table with the changed data, instead of just adding it to the table. I use the standard sqlite3 database csv file This is my models.pyModel.py -
HTML Tags problem in Amazon Buyer-Seller Messages
So I am trying to send emails on behalf of the seller to the buyer (Buyer-Seller messages) via the SES email service and it's working good. The problem is I can't send HTML formatted email. it looks good when I sent it to my email but it will display tags if I do it for the buyer and check that in the amazon messages it will display HTML tags check link. Dear valued customer <br /> <br /> Thank you for placing an order with us. Please check the attached invoice for your order ID# XXXXX for Volutz USB C Cable 2M Long USB Type C Cable Nylon Braided Durable Charger for Samsung Galaxy S10 S9 S8 A40 A50 A70, Huawei P30 P20, Google Pixel, OnePlus, Nintendo Switch and other USB-C Devices, . <br /> Should you encounter any issues with your order please reply to this email and tell us about how we can make it right. <br /> We aim to reply to any inquiry within 24h on normal working days. <br /> <br /> Have a wonderful day,<br /> XXXXXX I am using Django DRF and SES to send those emails. Do I have to encode something … -
Translate a Django app in Arabic and also make forms LTR to RTL
I have translated a Django app in multiple languages and everything works fine. But when I switch it to Arabic language I want to make all forms LTR to RTL. How can I achieve this in Django? -
In Django I have written the html to edit a form this during retrieving the values from database by value={{ i.full_name}} it shows only first name
enter image description hereenter image description here This is my edit.html code and during retrieving the values from database and showing in this html form it shows only first name when I am writing value={{ i.full_name}} why not the full name during filling up form I have included the full name I think there is some mistake after white space it cant read the characters anymore <section class="site-section"> <div class="container"> <div class="row"> <div class="col-lg-12 mb-5"> <h2 class="mb-4 text-center">Update Candidate Details</h2> <form method="POST" action="/update/ {{i.id}}/" enctype="multipart/form-data" class="p-4 border rounded" onsubmit="myFunction()" > {% csrf_token %} {% comment %} <input type="hidden" name="csrfmiddlewaretoken" value="UabxqpD8HGPOu1ZSFnIHAPbMtRgWBAnVHEs8bLDx0HnxN6uhG3LyYvZShvcx1ekn"> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="full_name">Full Name :</label> <input type="text" class="form-control" value ={{ i.full_name}} name="full_name" id="id_full_name" placeholder="Enter First Name"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="recruiter_name">Recruiter Name :</label> <input type="text" class="form-control" value ={{ i.recruiter_name }} name="recruiter_name" id="id_recruiter_name" placeholder="Enter Recruiter Name"> </div> </div> {% comment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="id_last_name">Last Name :</label> <input type="text" class="form-control" name="last_name" id="id_last_name" placeholder="Enter Last Name"> </div> </div> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="email">Email :</label> <input type="email" class="form-control" value ={{i.email }} name="email" … -
Python Web Application - With or without a framework? [closed]
My end-of-studies project for engineering is to make a web application with python allowing the instantaneous tracking of outstandings in an aeronautical room manufacturing material. this application allows to see in real time the status and location of the parts in production. analyse the data and provides a dashbord of the late parts. So I want to use python as a programming language. the problem that I am a beginner in this field and I would like to ask you some information to help me: Do I need a python framework? If so, is django the best for my project? What suggestions do you have in this scenario? -
How to make conditional refresh django
I am making a website and I have 3 buttons. Button named "byHour" is a normal button but how do I make so that the other 2 button will not refresh the page when clicking them. <form method="POST" > {% csrf_token %} <center> <input list="name" name="enterName" placeholder="enter name..." style="margin-bottom: 10px;"> <datalist id="name"> {% for empName in empName %} <option value="{{empName.employee}}"> {% endfor %} </datalist> <div id="date" style="display: none;"> <input type="date" name="firstDate" value="firstDate" style="margin-right: 10px;"> <input type="date" name="secondDate" value="secondDate"> </div> <p class="p2" style="margin-top: 10px; font-size: 15px;">Filter by: </p> <div class = "pad3"> <button type="submit" name="byHour" value="byHour" class="button1" id="example2" onclick="closeFunction()" style="width: fit-content; margin-right: 50px; font-size: 12px;">Total Hours</button> <button type="submit" name="byDate" value="byDate" class="button1" id="example2" onclick="closeFunction()" style="width: fit-content; margin-right: 50px; font-size: 12px;">Date</button> <button type="submit" name="specificDate" value="specificDate" class="button1" id="example2" onclick="myFunction()" style="width: fit-content; font-size: 12px;">Date Range</button> </div> </center> </form> <script> function myFunction() { var x = document.getElementById("date"); if (x.style.display == "none") { x.style.display = "block"; } else{ x.style.display = "none" } } function closeFunction() { var x = document.getElementById("date"); x.style.display = "none" } </script> -
Type Error with Django Rest Framework SimpleJWT
I have set up django restframework with jwt, following some instructions that was working previously, however now whenever I go to try and obtain a token using the path I defined in my 'accounts' app, it works until I enter in credentials and make a POST request. Django throws me an error saying "TypeError at /accounts/api/token/ Expected a string value". This hardly makes sense to me because I am simple entering my password which is a string into the password field. If I enter in wrong credentials, it gives back a correct response saying there isn't such a user. which means it is set up correctly? please help I have been stuck for so long. This is what is returned with CORRECT credentials. This is what is returned with INCORRECT credentials -
Invalid HTTP_HOST header: The domain name provided is not valid according to RFC 1034/1035
Our Django server is often having this error: Invalid HTTP_HOST header: u'/home/appname/run/gunicorn.sock:'. The domain name provided is not valid according to RFC 1034/1035. I think this happens when the host is a real IP rather than a domain name. If you're thinking why such a host is making it to the Django app, it's because we're actually actually any host: ALLOWED_HOSTS = ['.appname.org', '*'] And we want to keep it this way because we're allowing clients to point their own domains to our proxy. We have a DomainNameMiddleware which checks the host name against our database and if not found, the request is rejected. However, it seems the "Invalid HTTP_HOST header" error happens before our domain name middleware runs, so the error is raised when our middleware would've handled it silently. How can I have this error fail silently?