Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamic inline CSS styling in Django template
I am new to Django and am trying to figure out how to use dynamic CSS that is only active for the current category a user is on. I have a side nav with some categories and whichever category the user is on should be active with the use of a class. This is currently how I have things: {% for category in categories %} <li><a href="{% url 'category' category.id %}" {% if category.id in request.path %} class="uk-text-bold" {% endif %} >{{ category.name }}</a></li> {% endif %} This is obviously not correct and doesn't work so I imagine there is a proper way to do something like this and I'm just having a hard time understanding or finding that out. Any help is appreciated! Thanks. -
How can I package a Django app with chocolatey?
I'd like to package a Django + SQLite + JS-Frontend app with chocolatey. Are there specifics to consider which are not obvious from the chocolatey docs? -
how to pass parameter from view to form #typedChoiceField #django
i'm new in django and I want to pass list_choices from view to forms Forms.py taille = forms.TypedChoiceField(choices=q) def __init__(self,*args,**kwargs): /* I don't now what I will do */``` **View.py** ``` tailles= Taille.objects.filter(valable=True) list= [(i.taille_name, str(i.taille_name)) for i in tailles] form = CartTailleForm(q=list)``` -
Optimum uwsgi configuration
I have a Django project configured with uwsgi and Nginx. The issue is that I am getting lot of 502 Bad gateway. The nginx error log says (104: Connection reset by peer) while reading response header from upstream. Looks like uwsgi is not able to give response for some of the requests. Below is my uwsgi configuration. Could the issue be due to the bad uwsgi configuration ? I have an ec2 t3.medium instance it has two vCPUs. These 502 gateways increase when the site load increases. Sometimes the processor is 100%, that is when the we get more of this error. I am thinking of upgrading the server to t3.xlarge which has 4 vCPUs. But how to make sure the issue is with the server performance ? Please check the uwsgi configuration and see if there is any issue with the configuration. [uwsgi] master = true socket = /tmp/uwsgi.sock chmod-socket = 666 chdir = <dir_path> wsgi-file = <wsgi.py path> processes = 16 threads = 8 cpu-affinity = 1 max-worker-lifetime = 3600 max-requests = 1000 reload-on-rss = 2048 worker-reload-mercy = 60 virtualenv = <ven_path> vacuum = true enable-threads = true daemonize= <log_path> stats= <stats_path> buffer-size = 65535 -
django sending AJAx POST request using classical javascript into server with csrf_token, how to?
I have this part of code: document.querySelector('#form_pizza_order').onsubmit = () => { // make an ajax request to save the pizza order in the server const request = new XMLHttpRequest(); request.open('POST', '/order_pizza'); // Callback function for when request completes request.onload = () => { const data = JSON.parse(request.responseText); if (data.success) { // show in cart new order show_in_cart(data); } else { alert('failed to save pizza order in server'); } } const data = new FormData(); let username = localStorage.getItem('username'); data.append('username', username); //Send request request.send(data); return false; }; that when used the server returns 403 forbidden response because of csrf_token not sent. how do I add the crsf_token header properly with the javascript above, without using jquery. just javascript. thanks. -
Solving a slow query with a Foreignkey that has isnull=False and order_by in a Django ListView
I have a Django ListView that allows to paginate through 'active' People. The (simplified) models: class Person(models.Model): name = models.CharField() # ... active_schedule = models.ForeignKey('Schedule', related_name='+', null=True, on_delete=models.SET_NULL) class Schedule(models.Model): field = models.PositiveIntegerField(default=0) # ... person = models.ForeignKey(Person, related_name='schedules', on_delete=models.CASCADE) The Person table contains almost 700.000 rows and the Schedule table contains just over 2.000.000 rows (on average every Person has 2-3 Schedule records, although many have none and a lot have more). For an 'active' Person, the active_schedule ForeignKey is set, of which there are about 5.000 at any time. The ListView is supposed to show all active Person's, sorted by field on Schedule (and some other conditions, that don't seem to matter for this case). The query then becomes: Person.objects .filter(active_schedule__isnull=False) .select_related('active_schedule') .order_by('active_schedule__field') Specifically the order_by on the related field makes this query terribly slow (that is: it takes about a second, which is too slow for a web app). I was hoping the filter condition would select the 5000 records, which then become relatively easily sortable. But when I run explain on this query, it shows that the (Postgres) database is messing with many more rows: Gather Merge (cost=224316.51..290280.48 rows=565366 width=227) Workers Planned: 2 -> Sort (cost=223316.49..224023.19 … -
Django: problem with format when using ajax query (string/Json)
I try to send data with ajax but format is string and I need JSon (or formated data) Data to be send are displayed in an htlm table. I loop in all my row to collect all data to be send using ajax. But I have error when I try to make a JSON object when using JSON.Parse(new_parameters). If use new_parameters in my ajax query, I get False in my ajax view... If I "stringify" new_parameters to use it in my ajax query, I get data in my ajax view but in string format... That's mean the way I construct new_parameters is not the good way... var parameters = {}; var current_parameters = []; var new_parameters = []; // Collect data from html data when user click on "Modify settings" button $(document).on('click', '#modifier', function(event) { event.preventDefault(); $('#table_parametrage tr').each(function() { var parameter = {}; $(this).find('td div').each (function() { parameter[$(this).attr("col_name")] = $(this).eq(0).html(); }); new_parameters.push(parameter); }); new_parameters.shift(); // requête ajax > start // parameters = JSON.parse(new_parameters, null, 2); console.log(new_parameters); function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does … -
How to create multilink django model?
if you help I will be very grateful to you! In general, I decided to consolidate the knowledge of django by creating my own project and chose that I was implementing a multi-link service such as 'taplink' and so on, there were a lot of them. Just started and was immediately confused. Essence of the question: I need to display in the template all the links that the user selected and decided to add. Everything would be fine, but each link has its own unique css classes and unique href attributes. First I decided to create a model: class Links(models.Model): # messengers whatsapp = models.CharField(max_length=50, blank=True) telegram = models.CharField(max_length=50, blank=True) viber = models.CharField(max_length=50, blank=True) fbmessenger = models.CharField(max_length=50, blank=True) skype = models.CharField(max_length=50, blank=True) but realized that this is wrong. Then created other models, for example: class InstagramModel(models.Model): #title = models.CharField(max_length=100) help_text = "Введите ваш логин (без @)" login = models.CharField(max_length=100) choose = models.BooleanField(default=False) style = models.TextField(default='fab fa-instagram instagram') url = models.URLField(default='https://www.instagram.com/') class WhatsappModel(models.Model): #title = models.CharField(max_length=100) help_text = "Введите ваш номер телефона начиная с цифры 7 или 8 (без +7)" login = models.CharField(max_length=100) choose = models.BooleanField(default=False) style = models.TextField(default='fab fa-whatsapp whatsapp') url = models.URLField(default='https://wa.me/') here is view file def card_links (request): … -
python built in server not loading css file
Why does not it work in Django? There is error in the browser like that. its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. In file html there is : <link rel="stylesheet" href="{% static 'nowy.css' %}"> In settings.py it looks like: STATIC_URL = '/static/' Dirs are: app > static > nowy.css I can't find where is the mistake. -
Django , C# User Authentication,PostgreSQL
I am new in Django Web Development and i am in a process of learning. So i have some questions. I have build a simple register / login system in Django that is connected to a PostgreSQL local database.And all work fine registration/login function, now i want to develop a log in c# desktop application where i will use the PostgreSQL Database that django is using for saving the registered users. So since the password are encrypted i cant just do "Select user from user_auth where password='test' and email='test@test.com'". So is there any library for c# that i can use to encrypted the password and send the request, or i need to take another approach .... to learn Django REST and do all this with HTTP requests. -
Transport Endpoint is not connected - apache hosted django app
I just deployed my first Django application on my apache web server and I ran into follwing problem: I configured my django app that you can login with your ad credentials. If I run the server via development web server (python manage.py runserver) it works just fine. But if my apache is hosting the app, it says Caught LDAPError while authenticating adaccount: SERVER_DOWN({'desc': "Can't contact LDAP server", 'errno': 107, 'info': 'Transport endpoint is not connected'},) I know it must the something with the apache. I tried 3 settings KeepAlive On, MaxKeepAliveRequests and KeepAliveTimout but no success. Any Idea? Here is my Settings.py import os import ldap os.environ.setdefault("DJANGO_SETTINGS_MODULE", __file__) import django #django.setup() from django_auth_ldap.config import LDAPSearch AUTH_LDAP_SERVER_URI = 'ldap://dnsOfLDAP:3268' AUTH_LDAP_BIND_DN = "serviceaccount" AUTH_LDAP_BIND_PASSWORD = "some***" AUTH_LDAP_USER_SEARCH = LDAPSearch( "searchScope", ldap.SCOPE_SUBTREE, "sAMAccountName=%(user)s" ) AUTH_LDAP_USER_ATTR_MAP = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "UserPrincipalName", } from django_auth_ldap.config import ActiveDirectoryGroupType AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "searchScope", ldap.SCOPE_SUBTREE, "(objectCategory=Group)" ) AUTH_LDAP_GROUP_TYPE = ActiveDirectoryGroupType(name_attr="cn") AUTH_LDAP_USER_FLAGS_BY_GROUP = { #"is_active": "activeGroup", "is_staff": "staffGroup", } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 1 # 1 hour cache #ohne apache auth backend AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', 'django.contrib.auth.backends.RemoteUserBackend', ] #mit apache auth backend # AUTHENTICATION_BACKENDS = [ # 'django.contrib.auth.backends.RemoteUserBackend', # … -
Django, how to display thousand's point with IntegerField
I utilize in my views.py the following code: Materiale.objects.values_list('conto__nome', 'data__year','data__month').annotate(totale=ExpressionWrapper(Sum(F('quantita') * F('prezzo')), output_field=IntegerField())).values_list('conto__nome', 'data__year', 'data__month', 'totale')) Or rather the ExpressionWrapperwith output_fiedl = IntegerField(). But in my templates I view, ad example, the value 1000, instead 1.000. How can obtain this result? -
Conditional Statement not working in Django template
I am trying to offer a download option if the file exits but it always shows Not Avaialable even if the file exists. I have made a dictionary in views.py which saves True for that index if the file exists. I have also generated logs and the path generated at os.path.join is correct and dictionary has True for those values. I think the problem is me using 2 dot operator while accessing the dictionary in template. Template {% for upload in upload_list %} <tr> <td>{{ upload.upload_report_date|date:"M-Y" }}</td> <td>{{ upload.upload_at|date:"d-M-Y" }}</td> <td>{{ upload.upload_at|date:"h:i A" }}</td> <td>{{ upload.upload_by }}</td> <td>{% if upload.upload_errors %} Errors {% else %} Successful {% endif %}</td> {%if file_list.upload.upload_report_date %} <td><a href="{%static 'media/reports/finance'%}/sap-daily-{{ upload.upload_report_date|date:"Y-m" }}.csv" download >Download</a></td> <td><a href="{%static 'media/reports/finance'%}/sap-monthly-{{ upload.upload_report_date|date:"Y-m" }}.csv" download >Download</a></td> <td><a href="{%static 'media/reports/finance'%}/quantum-monthly-{{ upload.upload_report_date|date:"Y-m" }}.csv" download >Download</a></td> <td><a href="{%static 'media/reports/finance'%}/daily-ignored-vendors-{{ upload.upload_report_date|date:"Y-m" }}.csv" download >Download</a></td> {% else %} <td>Not Available</td> <td>Not Available</td> <td>Not Available</td> <td>Not Available</td> {% endif %} </tr> {% endfor %} Views.py upload_list = SAPActivityUpload.objects.all().order_by('-upload_at') file_list={} for upload in upload_list: try: if os.path.exists(os.path.join(settings.MEDIA_ROOT,'reports/finance/sap-daily-%s.csv' % (upload.upload_report_date).strftime("%Y-%m"))): file_list[upload.upload_report_date]=True except: pass -
when django user creates new user send mail
I am able to send the mail when Django-Admin user creates new user but this(send mail) function also trigger when i am register the user from front-end side. I want this should not call when front-end user register. Help me for this. -
Set Content-Type with Django, gunicorn and nginx
I've deployed a Django app with gunicorn and nginx as they normally recommend. After deploying, the static js and css did not load into the browser. On firefox console I get an error saying: The resource from “http://my.url/static/global/css/template.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff) -
How to get full path of selected file on change of <input type=‘file’> using django
compress.html <form action="/compress" method="POST" enctype="multipart/form-data"> {% csrf_token %} <label for="pdf">Select pdf :</label> <input type="file" name="pdf1" id ="pdf1" accept="pdf/*" /> <br> <button type="submit" class="btn btn-dark mt-2" value="click"> submit </button> <script type="text/javascript"> function getFilePath(){ $('input[type=file]').change(function () { var filePath=$('#fileUpload').val(); }); } </script> views.py def mergepdf(request): from pylovepdf.ilovepdf import ILovePdf ilovepdf = ILovePdf('my_secrete_key', verify_ssl=True) task = ilovepdf.new_task('compress') task.request.FILES['full_path']# here i want full path of selected file task.set_output_folder('/Downloads/download_pdffile') task.execute() task.download() task.delete_current_task() The filePath var contains the only name of selected file, not the full path. I searched it on the net, but it seems that for security reasons browsers (FF, chrome) just give the name of the file. Is there any other way to get the full path of the selected file? -
Do I have to recreate tables as models for an existing database?
I'm just starting with Python and Django and have an existing database. I'd like to create views to edit the fields in this database, do I have to create models to match these tables or is there a way to start editing after connecting the database and a view? -
Django UserCreationForm raise Validation Error when email already exist
Hi there I am new to Django. I have got a UserRegisterForm inherited from UserCreationForm. Everything works fine class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ["username", "email", "password1", "password2"] Now I want the to show a sign 'email already exist' near by the email input box if the email's already in the database. I have tried: class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ["username", "email", "password1", "password2"] def clean_email(self): username = self.cleaned_data.get("username") if User.objects.filter(username=username).exists(): raise forms.ValidationError("Username is not unique") return username def clean_username(self): email = self.cleaned_data.get("email") if User.objects.filter(email=email).exists(): raise forms.ValidationError("Email is not unique") return email It didn't work. I will be so glad if anyone can help. -
Django Rest Framework fields source validation naming issues
How to ensure DRF serializer attribute or validated_data parameter for validate and create method does not change to model attribute name when field name are declare in different name using source argument class TestSerializer(serializers.HyperlinkedModelSerializer): new_name = HyperlinkedRelatedField( source='old_name', view_name='viewset-detail', queryset=SomeModel.objects.all(), ) # override validate method def validate(self, attrs): attrs['old_name'] # this is valid attrs['new_name'] # invalid # override create method # problem same for create here def create(self, validated_data): attrs['old_name'] # this is valid attrs['new_name'] # invalid Just want to know is this part of DRF design(any reason) or I did this wrongly, is kind of confuse other team members when this happened -
Pagination stopped working on Django application
I am new to Django and I just picked up a book "Django 2 by example". I followed all the code in the tutorial bu something broke the pagination along the line and I just can't figure what it is. I get an output of "Page of ." instead of "Page 1 of 1. at the base of my blog. Find some of my code below:. P.S: Kindly ignore the indentation in the code. Thank you. Views.py from django.shortcuts import render, get_object_or_404 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.views.generic import ListView from django.core.mail import send_mail from django.db.models import Count from taggit.models import Tag from .models import Post, Comment from .forms import EmailPostForm, CommentForm def post_list(request, tag_slug=None): object_list = Post.published.all() tag = None` if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) paginator = Paginator(object_list, 3) # 3 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts = paginator.page(paginator.num_pages) return render(request, 'blog/post/list.html', {'page': page, 'posts': posts, 'tag' : tag}) list.html {% extends "blog/base.html" %} {% block title … -
Continuously parse CSV files which are updated by another process in PHP
I'm working on project in which csv file is updated continuously with python program. I'm creating a dynamic webpage in PHP which shows updated csv values in HTML table. I got logic for reading csv file in PHP but don't know how to read the updated values continuously and display them in HTML table in which updated values overwrites the previous values -
Django and pure Python
I want to create a web app with Django and integration of Selenium and Python-Docker API. Where inside the Django project is the correct place to put the Selenium scripts so users will be able the run it by a puse of a button? I've seen some thred saying inside a 'view', but is is a lot of logic that I've sprated into multipale .py files. -
Django Admin - filter inline options by 3rd Model?
Use-case: There are 3 Models: User Division Office The relations are: An Office is always connected to one Division. A User can be a member of various Divisions, and work for various offices. I want to create an inline for my User admin page, under the Office field. However I would like to populate the inline options with Offices that belong only to Divisions that the user is part of. Code: class User(models.Model): username = models.CharField(max_length=100) class Division(models.Model): name = models.CharField(max_length=100) users = models.ManyToManyField(User) class Office(models.Model): name = models.CharField(max_length=100) division = models.ForeignKey(Division, on_delete=models.CASCADE, null=True, blank=True) class OfficeAdminForm(forms.ModelForm): # I assume I should change it here, but I don't know how to filter accordingly. office = forms.ModelChoiceField(queryset=Office.objects.all(), empty_label="(Nothing)") class OfficeInline(admin.TabularInline): model = Office form = OfficeAdminForm class UserAdmin(admin.ModelAdmin): inlines = [OfficeInline] admin.site.register(Item, ItemAdmin) admin.site.register(Category) -
Django - Excel Calculate the total of method value
I created a data model that user upload excel file and calculate the row and column class Data(models.Model): """ Model of Data""" user = models.ForeignKey(User, on_delete=models.CASCADE) document = models.FileField(upload_to="documents/%Y/%m/%d") uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.document) def amount(self): wb = xlrd.open_workbook(self.document.name) worksheet = wb.sheet_by_index(0) row_count = worksheet.nrows print(row_count) column_count = worksheet.ncols print(column_count) total_col_row = row_count * column_count # print payments payments = total_col_row * 9 return payments how to get the total amount if user enter for example a 3 files? -
Filtering django model using date
I need to filter some data from models using the date. I see some posts that speaks about ranges but I just want to see for example the rows of my table from the 22/04/2020, in other words, just one day. Reading the documentation, I understood that I have to do the following, import datetime prueba = DevData.objects.order_by('-data_timestamp').filter(data_timestamp=datetime.date(2020, 4, 22)) prueba = loads(serializers.serialize('json', prueba)) for p in prueba: print(p) But appears the following warning: RuntimeWarning: DateTimeField DevData.data_timestamp received a naive datetime (2020-04-22 00:00:00) while time zone support is active. And the list appears empty. I think the problem is that is just filtering using 2020-04-22 00:00:00 and not all the day. How can I fix this? Between two dates is working but just one day I don't know how to do it. import datetime start_date = datetime.date(2020, 4, 22) end_date = datetime.date(2020, 4, 23) prueba = DevData.objects.order_by('-data_timestamp').filter(data_timestamp__range= (start_date,end_date)) PD: I have info rows in this day. Thank you very much.