Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to convert ajax code into vue.js axiox method in django
If user click on like button web page not refresh and count of the likes also updated without refreshing so, In first I have written in ajax then I want to convert it into vue.js after converting into vue.js its not working. Can any one please help me to achieve this. Here I have written vue.js axios method. That I have accessed in html template html template <div id = "deals-vikreya"> <a class="likebutton" style=" {% if request.session.email %}pointer-events: auto; {% else %}pointer-events: none;{% endif %}" id="like-{{i.id}}" href="#" data-catid="{{ i.id }}"> <i class="fa fa-thumbs-o-up" id="like-icon-{{i.id}}" aria-hidden="true" style="color: gray"></i> </a> <span id="cm_count{{i.id}}"> ({{ c_count }}) </span> </div> vue.js axiox <script> new Vue({ el: '#deals-vikreya', data() { return {}; methods: { $('.likebutton').click(function(){ var catid; catid = $(this).attr("data-catid"); console.log(catid); axios( { method : "POST", url: "{% url 'post_comment_like' + catid %}", //django path name data:{ post_id: catid }, success: function( data ) { console.log("like saved"); console.log(data.comment_count); document.getElementById("cm_count"+catid).innerHTML ="(" + data.comment_count + ")"; $( '#like-'+ catid ).attr("href", "/post_comment_like_remove/" + catid); $( '#like-icon-'+ catid ).css("color", "#DB0038"); } }) }); }, }) </script> -
ValueError: Missing staticfiles manifest entry for 'css/homepage.css' heroku
i am trying to deploy my django app on heroku and i am unable to collect static files. i tried many things including whitenoise but it still shows error ValueError: Missing staticfiles manifest entry for 'css/homepage.css' and there is internal server error due to this my settings: please help THANK you -
Django filter check if small range is in a bigger range
I want to check a simple logic, for example if 15 - 25 is inside 1 - 100. I tried gte, lte and range but no luck. It does not match what I need. Here is my sample code: if obj.max_number == 0: objRange.append(Q(number_min__gte=obj.min_number) and Q(number_max__gte=obj.min_number)) elif obj.min_number == 0: objRange.append(Q(number_min__lte=obj.max_number) and Q(number_max__lte=obj.max_number)) else: objRange.append(Q(number_min__range=(obj.min_number, obj.max_number))) objRange.append(Q(number_max__range=(obj.min_number, obj.max_number))) Note, I only need the else part since if and elif is a working condition -
I have to display 'location' with respective to the 'latitude' and 'longitude'. Got the desired location printed in the console but not getting saved
I tried many approaches including SerializerMethodField and didn't work. I want to print the location in the result with respect to the latitude and longitude from the models. Models.py class CustomerProfile(models.Model): location = models.PointField(default=Point(0,0),geography=True) latitude = models.DecimalField(blank=True,max_digits=9,decimal_places=6,default=None,null=True) longitude = models.DecimalField(blank=True,max_digits=9,decimal_places=6,default=None,null=True) Serializer.py class CustomerSerializer(serializers.ModelSerializer): class Meta: model = CustomerProfile fields = "__all__" Views.py from django.contrib.gis.geos import GEOSGeometry class CustomerView(APIView): def get(self, request, format=None): query = CustomerProfile.objects.all() serializer = CustomerSerializer(query, many=True) return Response(serializer.data) def post(self, request,data,format=None): serializer = CustomerSerializer(data=request.data) if serializer.is_valid(): lat=getattr(data,"latitude") lon= getattr(data,"longitude") lat_1 = float(str(lat)) lon_1 = float(str(lon)) print(lon_1) if lat_1 and lon_1: location = Point((lat_1, lon_1), srid=4326) print(location) if location: loc=getattr(data,"location") print(loc) loc=location Serializer.save() return Response({"message":"Customer Profile Updated Successfully","data":serializer.data}, status=200) return Response({"message":"Customer registration failed!!","data":serializer.data}, status=400) -
Excel file cannot be auto download by browser
My server is based on Django, below is the response for my download request. ... stream_file = BytesIO() pivot_df.reset_index() pivot_df.to_excel(stream_file) stream_file.seek(0) response = StreamingHttpResponse(stream_file) response['Content-Type'] = 'application/octet-stream;' response['Content-Disposition'] = 'attachment; filename="{}.xlsx"'.format('account_data') return response The size of response is about 33.13MB, after a period of time my browser doesn't response anything. It showed Failed to load reponse data. Request URL: https: xxxxxx Request Method: POST Status Code: 200 OK Remote Address: xxxxxx Referrer Policy: strict-origin-when-cross-origin But if I try this request with Postman, I can get right file data. Why cannot I get excel file download from browser. Thanks. I'm using Chrome 90.0.4430.93 -
Changes are not being reflected in template even after cache expiry( TIMEOUT-180 ) in django?
Using filebased cahche in django, and set 3-minutes of timeout , But even after cache expiry, Page is being loading wiht the same content in template and not with the new data middleware in settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] using filebasedbackend for cache CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': 'cahcefiles', } } -
Using User module of the Django where it is saving the data
I am using User module to save the data for the registration from django.contrib.auth.models import User ## forms.py class NewUserForm(UserCreationForm): email = forms.EmailField(required = True) class Meta: model = User fields = ('username', 'email', 'password1', 'password2') ## views.py def register_request(request): if request.method == 'POST': form = forms.NewUserForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') and this is working but I want to in which table Django is saving the data...