Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form : how to get data in a ManyToMany field?
My objective is to implement the same kind of features than in admin panel with a many to many relationship. Everything seem to work all right, but when I submit my form, I get some strange results: I'm probably missing something but I cannot fogure out what goes wrong. For now, when I add lines, everything is OK. Problems occur when I try to remove lines from the group. I'm taking about users, I have a first list of 'all users' and the second one will make a group. When I had a user, then remove another one, the form cannot be validated; the list is empty, the removed user "disappear" (it is not in the group list nor among "all users". If I remove one user, then add a new one, the only user in my form after validation is the one I added, all other ones are removed. I hope I'm clear, many thanks in advance for your advise. Here are the related code blocks. Models: class UserComp(models.Model): """ Link between users and companies Used to restrict display to companie(s) the users belong to """ user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Utilisateur") company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name="Société") phone_regex = RegexValidator(regex=r'^0[0-9]([ … -
nginx docker container as reverse proxy for services running in docker containers
I have nginx running in a docker container which I want to use as reverse proxy for services running in docker containers. ATM I have two services, django and owncloud. Both services works when accessing them directory e.g. localhost:4000 and localhost:5000. When I'm accessing localhost/owncloud I get 502 Bad Gateway Nginx log: 2020-04-27T13:21:54.852082794Z 2020/04/27 13:21:54 [error] 6#6: *2 connect() failed (111: Connection refused) while connecting to upstream, client: 172.18.0.1, server: , request: "GET /owncloud/ HTTP/1.1", upstream: "http://172.18.0.4:4000/", host: "localhost" When I'm accessing localhost/django I get page not found from Django, which is fine, but I if I try to access localhost/django/admin I get page not found from Nginx. Nginx log: 2020-04-27T13:29:11.173933857Z 2020/04/27 13:29:11 [error] 6#6: *4 "/etc/nginx/html/sv/admin/index.html" is not found (2: No such file or directory), client: 172.18.0.1, server: , request: "GET /sv/admin/ HTTP/1.1", host: "localhost" I'm new to Nginx and have messed around with the nginx.conf a lot with no success. Here are the relevant files: /docker-compose.yml version: '3' networks: nginx-net: /nginx/docker-compose.yml version: '3' services: internal-nginx: build: context: ./nginx restart: unless-stopped image: web-nginx container_name: nginx ports: - "80:80" - "443:443" networks: - nginx-net depends_on: - internal-django - internal-owncloud /nginx/Dockerfile FROM nginx COPY nginx.conf /etc/nginx/nginx.conf COPY nginx.conf /etc/nginx/nginx-raw.conf RUN rm … -
How to create Django models from oracle table-synonyms using inspectdb command
I am using Oracle legacy database from which I am creating models using inspectdb command(inspectdb table_name) for existing tables. But this command is only working for tables and views not for table-synonym. Please correct me if I am wrong: There is no way to specify schema with table name as : [schema].[table_name] in Django framework. So, I found a solution on the given link How to access tables from a different schema in oracle 11g using django? I create private table-synonym in oracle db and use inspectdb [synonyme_name] command but unable to inspect the synonym. This command working fine for table and view but not for synonym. inspectdb WASTE2 error-screenshot -
How to display a spatial field on a map?
I have a spatial field in my Django model. I want to display this field on a map. How to do it? It works just fine in Django Admin with Django built-in OSMWidget and OpenLayers. If I try to access the spatial field in my template it is of this format: SRID=4326;GEOMETRYCOLLECTION (POLYGON ((54.57842969715517 23.34800720214843, 54.53144199643833 23.29547882080078, 54.52964902093564 23.38096618652343, 54.57444978782305 23.40499877929688, 54.57842969715517 23.34800720214843))) -
when I using celery with multiple processing , the notify signal can't be received by waiting thread
when I using celery with multiple processing , the notify signal can't be received by waiting thread. but when I run the code with script, it works normally. Whether the problem is caused by celery poor support for multithreading? Please give me a hint if you can resolve the problem, thank you! # tasks.py @shared_task(bind=True) def long_time_def(self, *args, **kwargs): tp = ThreadPool(5) tp.set_tasks(pv.check_position_effective, list(args)) res = tp.final_results() while len(res) < len(args): print(res) return 'finished' # ../public/tools.py class ThreadPool: def __init__(self, max_thread_num=5): self.over = False self.results = [] self.func = None self.args_list = None self.task_num = 0 self.max_thread_num = max_thread_num self.pool = ThreadPoolExecutor(max_workers=max_thread_num) self.cond = threading.Condition() def set_tasks(self, func, args_list): self.task_num = len(args_list) self.args_list = args_list self.func = func def get_result(self, future): self.results.append(future.result()) if len(self.args_list): args = self.args_list.pop() task = self.pool.submit(self.func, *args) task.add_done_callback(self.get_result) else: print("result:%s"%self.results) while self.task_num != len(self.results): print(self.results) time.sleep(1) print('\n', 'finish') self.cond.acquire() ############ this place ############ self.cond.notify() ############ this place ############ self.cond.release() return def _start_tasks(self): for i in range(self.max_thread_num): if len(self.args_list): args = self.args_list.pop() task = self.pool.submit(self.func, *args) task.add_done_callback(self.get_result) else: break def final_results(self): self._start_tasks() if self.task_num == len(self.results): return self.results else: # print("main locked") # self.cond.acquire() ############ this place ############ print("main waiting") self.cond.wait() ############ this place ############ # print("main … -
Django application page not showing when deploying to pythonanywhere.com
My application works perfect when run locally on my mac os, but when it is deployed to pythonanywhere (and also on my partners windows os laptop) one of the pages just shows the html code instead of the actual page as shown below: I dont know what the problem is as it runs locally fine. Here is my html page: ''' {% extends "base2.html" %} {% load static %} {% block content %} <header class="masthead"> <div class="overlay"></div> <div class="container my-4"> <div class="border border-light p-3 mb-4"> <div class="text-center"> <a href="/logbook/home/"><img src="{% static 'img/maplogbook1.png' %}" class="rounded mx-auto d-block" alt=""></a> </div> </div> </div> </header> <header class="masthead"> <div class="overlay"></div> <div class="container my-4"> <div class="border border-light p-3 mb-4"> <div class="text-center"> <a href="/logbook/create/" class="btn btn-lg btn-warning">New Post - Driving Instructor &rarr;</a> <a href="/logbook/learner/" class="btn btn-lg btn-dark text-warning">New Post - Learner Driver &rarr;</a> </div> </div> </div> </header> <div class="container"> <div class="row justify-content-center"> <div class="col-md-8 mt-3"> {% for post in posts %} <div class="card mb-4"> <div class="card-body"> <div class="container p-3 my-3 bg-dark text-white"> <h2 class="card-title text-dark "> <a href="% url "logbook:detail" slug=post.slug %}" class="btn btn-lg btn-warning">New Post - Driving Instructor &rarr;</a>. </h2> <h2 class="card-title text-dark "><a href="{% url "logbook:detail" slug=post.slug %}">{{ post.title }}</a></h2> </div> <p class="card-text text-muted h6">{{ … -
Django 2.0.5 - Signature of method 'ContentCreateUpdateView.dispatch()' does not match signature of base method in class 'View'
I am learning Django and I am following a book project Django 2 by example. In one of there project "building an elearning site", the have the following code: class ContentCreateUpdateView(TemplateResponseMixin, View): module = None model = None obj = None template_name = 'courses/manage/content/form.html' def get_model(self, model_name): if model_name in ['text', 'video', 'image', 'file']: return apps.get_model(app_label='courses', model_name=model_name) return None def get_form(self, model, *args, **kwargs): Form = modelform_factory(model, exclude=['owner', 'order', 'created', 'updated']) return Form(*args, **kwargs) def dispatch(self, request, module_id, model_name, id=None): self.module = get_object_or_404(Module, id=module_id, course__owner=request.user) self.model = self.get_model(model_name) if id: self.obj = get_object_or_404(self.model, id=id, owner=request.user) return super(ContentCreateUpdateView, self).dispatch(request, module_id, model_name, id) def get(self, request, module_id, model_name, id=None): form = self.get_form(self.model, instance=self.obj) return self.render_to_response({ 'form':form, 'object': self.obj }) def post(self, request, module_id, model_name, id=None): form = self.get_form(self.model, instance=self.obj, data=request.POST, files=request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.owner = request.user obj.save() if not id: Content.objects.create(module=self.module, item=obj) return redirect('module_content_list', self.module.id) return self.render_to_response({'form': form, 'object': self.obj }) But I am getting an error message from PyCharm (my IDE) on: def dispatch(self, request, module_id, model_name, id=None): And the error is: Signature of method 'ContentCreateUpdateView.dispatch()' does not match signature of base method in class 'View' less... (Ctrl+F1) This inspection detects inconsistencies in overriding method signatures. Is there … -
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.