Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django app architecture: multithreading or correct processing of background tasks
Wrote a django application to control the launch of queries in the background. According to server events, for example, post_save tasks are created or updated for execution in the background (apsheduler background tasks). While developing on the local machine, everything was fine - django provided the functionality of simultaneously connecting and fulfilling long tasks for different clients without freezes. However, when moving to production, the server using the gunicorn encountered such a problem that a request is being made from one client, while others are waiting. Set up several workers (2 * CPU) +1), but another problem appeared: When django is started with several workers, then each instance of django (worker) starts its background task (which needs to be done only once). And instead of just one, as many tasks are run as there are workers. Performance of tasks is critical for my application, and simultaneous execution of requests from different clients so far is in second place. Therefore set the parameter number of workers: 1. But I understand that this is a compromise, and that I’m doing something wrong. How correct is this task should be architecturally solved? The problem, it seems to me, is complicated by the fact … -
Is it necessary to specify default=django.utils.timezone.now while creating automatic primary key field for Django model
I created model Class Team(models.Model): team = models.IntegerField(primary_key = True) name = models.CharField(max_length = 30) After it i saved some objects from this model and decided to change manually created primary key field to auto primary key field. I changed previously created model to Class Team(models.Model): team = models.IntegerField(null=True) name = models.CharField(max_length = 30) After it i run python manage.py makemigrations Django promted that i need specify default=django.utils.timezone.now here is my question what reason to specify this field with django.utils.timezone.now Why i can create primary key field without specifying it? What if i delete default=django.utils.timezone.now from migrations file and will migrate it ? -
How to setup SSH connection with Django
I want to setup SSH connection with Django. Run shell commands and display results on the User Interface. -
Python click project, "Django is not available on the PYTHONPATH " error
I am having a click project which don't use/need Django anywhere but while running prospector as part of static analysis throws this strange error Command prospector -I __init__.py --strictness veryhigh --max-line-length 120 src/ Error Line: 1 pylint: django-not-available / Django is not available on the PYTHONPATH There was no reference of django anywhere in the project/code . I am fairly new to python, Am i missing something obivious here ? python-version : 3.7 pip list apipkg 1.5 asn1crypto 1.2.0 astroid 2.3.2 atomicwrites 1.3.0 attrs 19.3.0 auger-python 0.1.35 bitmath 1.3.3.1 boto3 1.10.14 botocore 1.13.14 bravado 9.2.0 bravado-core 4.9.1 certifi 2019.9.11 cffi 1.13.2 chardet 3.0.4 click 6.7 colorama 0.4.1 coloredlogs 10.0 coverage 4.5.4 cryptography 2.3.1 deb-pkg-tools 4.5 docutils 0.15.2 dodgy 0.1.9 entrypoints 0.3 execnet 1.7.1 executor 21.3 fasteners 0.15 filelock 3.0.12 flake8 3.7.9 flake8-polyfill 1.0.2 funcsigs 1.0.2 future 0.18.2 humanfriendly 4.18 hvac 0.7.1 idna 2.5 importlib-metadata 0.23 isort 4.3.21 jmespath 0.9.4 jsonpointer 2.0 jsonschema 3.1.1 lazy-object-proxy 1.4.3 mando 0.6.4 mccabe 0.6.1 mock 3.0.5 monotonic 1.5 more-itertools 7.2.0 murl 0.5.1 packaging 19.2 pep8 1.7.1 pep8-naming 0.4.1 pip 19.3.1 pluggy 0.13.0 property-manager 2.3.1 prospector 1.1.7 py 1.8.0 pycodestyle 2.5.0 pycparser 2.19 pydocstyle 4.0.1 pyflakes 2.1.1 pylint 2.4.3 pylint-celery 0.3 pylint-django 2.0.10 pylint-flask 0.6 pylint-plugin-utils … -
Django allauth login / signup/ or any links is not showing the template
I'm using Django all-auth for authentication, after the setup, I'm trying "http://127.0.0.1:8000/accounts/login/" link to test the login but the template is not rendering. The whole page is blank and the HTML is showing my 'base.html's extended version. I'm not sure where is the problem. I'm using virtual env as well. Though I believe something wrong with the template rendering. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainapp', # Thrid party apps 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] SITE_ID = 1 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('mainapp.urls')), ] NOTE: this is not the first time I'm using Django all-auth and I've not such kind of problem before. -
Django ValidationError CSV-Upload
I am trying to upload a CSV file into my Django model. Although the upload of the data works fine (all the rows get copied into the database), at the end Django returns a ValidationError ["'' value must be a decimal number."] error message. From the local vars section of the error message I kind of get the reason - when the iteration reaches the end of the rows contianing data, there is obviously no decimal number. So django throws an error. However, I do not understand why as there is always a last row after which there is no more data. experimneted a bit to try to find the problem: I think that worked is so copy the whole data from the original CSV into a new SCV - suddenly everything works fine and no error message appears. I would love to accomplish this with the original CSV file and no error message! Would appreciate any help. My CSV files are CSV UTF-8 and they are saved in Excel models.py from django.db import models class Testdata3(models.Model): key = models.CharField(max_length=100, primary_key=True) assetclass = models.CharField(max_length=25) value = models.DecimalField(max_digits=25,decimal_places=10) performance = models.DecimalField(max_digits=25,decimal_places=10) def __str__(self): return self.key views.py from django.shortcuts import render from … -
Filter by ForeignKey using django model
I have two models Users and Attributes, each user has multiple attributes class User(models.Model): userid = models.CharField(max_length=200, primary_key=True) name = models.CharField(max_length=200) email = models.CharField(max_length=200) def __str__(self): return self.userid class Attribute(models.Model): userid = models.ForeignKey(User,on_delete=models.CASCADE) rolechoice = (('admin','admin'),('visitor','visitor'),('customer','customer'),('user','user')) type = models.CharField(max_length=15,choices = rolechoice) value = models.CharField(max_length=200) def __str__(self): return str(self.value) I can do filters by name, id, email in my users page, but to do a filter by the role that exist in the class Attribute i didn't know how. This is my view : def users_search(request): user_list = User.objects.all() user_filter = UserFilter(request.GET, queryset=user_list) return render(request, 'cocadmin/users_stream.html', {'filter': user_filter}) And this my filter.py class UserFilter(django_filters.FilterSet): userid = django_filters.CharFilter(lookup_expr='icontains') name = django_filters.CharFilter(lookup_expr='icontains') email = django_filters.CharFilter(lookup_expr='icontains') attributes = django_filters.ModelChoiceFilter(queryset=Attribute.objects.all()) class Meta: model = User fields = ['userid','name','email','attributes'] thank you for the Help :) -
How to show a variable only on when user session available
Hello I have a variable...... How can I show a variable only on when user session available... window.inline_endpoint = "{% url 'request_access' %}"; -
Using Django's Messages Framework with a React
I"m gradually moving the UI to React. many server notifications are implemented using django.contrib.messages. Is there a way for me to keep consuming those message in React (it's CookieStorage) -
Best method for reliable high volume data stream: websockets with Django Channels?
Our company built an endpoint a while back which exposes a POST endpoint to which one other company pushes A LOT of data. At peak moments there are 200+ requests per second. I would like to make this more efficient, so to avoid the usual https overhead for every request I thought of using websockets. I've got some experience with websockets for simple websites, but so far not with continuous high volume data streams. Our setup is based on a Python/Django stack. I could go with something different than Django, but it would be easier to keep the current setup. So I was wondering about a couple things. First of them reliability. As far as I understand websockets are based on a "at most once" or "at least once" deliverability. In this comment I read that Django Channels are of the "at most once" type. That means that packets could well be missed. My question is; how can I take this into account? What are the things that influence websocket reliability? And in what order of magnitude should I think? I need to discuss our acceptance for missed records, but should I think in 0.1%, 0.01% or 0.0001%? And a … -
loading static files in django application
I have a django application and trying to load the front end from by django project. My index.html is: <link rel="icon" type="image/x-icon" href="favicon.ico"> {% load static %} <link rel="stylesheet" href="{% static "styles.38614f36c93ac671679e.css" %}"></head> <body> <app-root></app-root> {% load static %} <script type="text/javascript" src="{% static "runtime.a66f828dca56eeb90e02.js" %}"></script><script type="text/javascript" src="{% static "polyfills.f3fc5ca24d1323624670.js" %}"></script><script type="text/javascript" src="{% static "scripts.5bde77e84291ce59c080.js" %}"></script><script type="text/javascript" src="{% static "main.e7b9143f2f482d6d3cc7.js" %}"></script></body> </html> and in settings.py of project file i have added static file settings: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') my project structure is: apt.yml DCMS_API/ infra/ manage.py* odbc-cfg/ requirements.txt static/ templates/ Authorize/ facility/ manifest.yml Procfile runtime.txt when i uploaded the code on cloud foundry and tried to run the application it says ERR Not Found: /static/runtime.a66f828dca56eeb90e02.js ERR Not Found: /static/styles.38614f36c93ac671679e.css ERR Not Found: /static/polyfills.f3fc5ca24d1323624670.js ERR Not Found: /static/scripts.5bde77e84291ce59c080.js ERR Not Found: /static/main.e7b9143f2f482d6d3cc7.js What am i missing? -
Exchange on programming techniques and boiler plates
I do my programming like probably a large number of us, mostly alone. I would like to have the chance to exchange and show some of my programming boiler plates mainly in Django and ask if there are ways to improve my programming, ways if I can be for example to be more DRY or simply a better programmer. I would be open to also help others if I can. So the basic difference, I am not asking to fix a bug in my program, but just to reach a community where we can exchange on our good and bad practices. Does Stackoverflow currently offer this? Have a nice day. Guy -
Form not resetting upon submission?
I have a page with a form that once it gets submitted, the form loads again for the next person. I switched from class based views to function based due to a problem I was having to render modals and I noticed that now, since I'm not redirecting to the form again, it does not clear the data that was entered previously. How can I clear the form upon submission? views.py def enter_exit_area(request): form = WarehouseForm(request.POST or None) enter_without_exit = None exit_without_enter = None if form.is_valid(): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in request.POST: # Some rules to open modals/submit message = 'You have entered %(area)s' % {'area': area} if station is not None: message += ': %(station)s' % {'station': station} messages.success(request, message) elif 'leave_area' in request.POST: # more Rules message = 'You have exited %(area)s' % {'area': area} if station is not None: message += ': %(station)s' % {'station': station} messages.success(request, message) return render(request, "operations/enter_exit_area.html", { 'form': form, 'enter_without_exit': enter_without_exit, 'exit_without_enter': exit_without_enter, }) forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}), } fields = ('employee_number', 'work_area', 'station_number', 'edited_timestamp') enter_exit_area.html {% extends "base.html" %} {% load core_tags %} … -
same url pattern with differnet views and names
My code is below template looks like this <td><button><a href="{% url 'testschema' allschema.schema_name %}"> Test</a></button></td> <td><button><a href="{% url 'deleteschema' allschema.schema_name %}"> Delete</a></button></td> url patterns urlpatterns = [ path('<int:id>/', views.confighome, name='config'), path('<str:schmid>/', views.deleteschema, name='deleteschema'), path('te<str:schmid>/', views.testschema, name='testschema') ] views.py def deleteschema(request,schmid): some code return redirect('/configuration/'+str(request.session["project_id"])) def testschema(request,schmid): some code return redirect('/configuration/'+str(request.session["project_id"])) Whenever I click on the Testbutton its actually calling the delete function Any idea why this happening Since I used named url parameters Thanks in advance -
Modal not submitting data (stuck on submit "loading")
I have a form that keeps track of enter/leave times and, whenever there is a time discrepancy, it prompts the user for an estimate of a time. Currently the main parts of the form work, and the modal shows, but when you try to submit the "edited timestamp" the modal just gets stuck on loading and nothing happens until you refresh the page, and even when you do, nothing has been submitted to the database for the edited timestamp. What could be causing this to get stuck? views.py def enter_exit_area(request): form = WarehouseForm(request.POST or None) enter_without_exit = None exit_without_enter = None if form.is_valid(): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in request.POST: new_entry = form.save() EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now()) # If employee has an entry without an exit and attempts to enter a new area, mark as an exception 'N' enters_without_exits = EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num) & Q(time_out__isnull=True) & Q(time_exceptions="")).exclude(pk=new_entry.pk).order_by("-time_in") if len(enters_without_exits) > 0: enter_without_exit = enters_without_exits[0] enters_without_exits.update(time_exceptions='N') message = 'You have entered %(area)s' % {'area': area} if station is not None: message += ': %(station)s' % {'station': station} messages.success(request, message) return render(request, "operations/enter_exit_area.html", { 'form': form, 'enter_without_exit': enter_without_exit, }) class UpdateTimestampModal(CreateUpdateModalView): … -
uwsgi memory consumption increases gradually but the consumed memroy not freed
I am running a project with django + nginx + uwsgi and my uwsgi.ini file confiuration is as follows: socket = /tmp/uwsgi.sock chmod-socket = 666 socket-timeout = 60 enable-threads = true threads = 500 disable-logging=True with the above configuration also added harakiri = 60 but unable to free memory then tried addition of max-request = 100 and max-worker-lifetime = 30 but memory was not freed after this tried configuring process=4 and threads =2 but also unable to free memory usage. while analysing my api calls I found three bulk api which increased memroy usage continuously and optimized the code. Eventhough after code optimizing and adding some parameters to uwsgi.ini file unabke to free memory. Please help me out to fix this issue. -
why does this code return true only for the super user
this code in theory should stop user without the mentioned permission. could it be a caching issue as i have found posts on github with this issue but from a different version of django from django.shortcuts import render from django.http import HttpResponse from .models import chem # Create your views here. def console(request): if request.user.has_perm('bio_lab.can_view_chem'): print('works') istekler = chem.objects.all() return render(request,'console.html',locals()) else: print('error') ''' -
Executing django's 'custom management command' in VSCode errors 'Unknown command'
I am using Django 1.3.5 and Python 2.7.14. I have a 'custom management command' called 'csvimport' in my django app. However when I try to run the command from 'VSCode Terminal' by typing in python source\manage.py csvimport 'db\eds.csv' it throws error saying Unknown command: 'csvimport'. Find below code of my 'django custom management command'. I tried all sorts of options to run it but no luck. Any hint would really help me a lot. I have been googling and trying different ways to run the command :-( -
I keep getting a 500 Internal server error
I have been trying to push my Django project to the web for the first time, but I keep getting the Internal server error, I have tried solutions from around the site but they haven't been able to help me. My apache error log is: [Mon Nov 18 12:49:31.996083 2019] [wsgi:error] [pid 2673:tid 140041613797120] [remote 101.165.248.136:53820] Traceback (most recent call last): [Mon Nov 18 12:49:31.996155 2019] [wsgi:error] [pid 2673:tid 140041613797120] [remote 101.165.248.136:53820] File "/home/ib/personal_project/log_it/wsgi.py", line 16, in <module> [Mon Nov 18 12:49:31.996159 2019] [wsgi:error] [pid 2673:tid 140041613797120] [remote 101.165.248.136:53820] application = get_wsgi_application() [Mon Nov 18 12:49:31.996165 2019] [wsgi:error] [pid 2673:tid 140041613797120] [remote 101.165.248.136:53820] File "/home/ib/personal_project/venv/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Mon Nov 18 12:49:31.996168 2019] [wsgi:error] [pid 2673:tid 140041613797120] [remote 101.165.248.136:53820] django.setup(set_prefix=False) [Mon Nov 18 12:49:31.996173 2019] [wsgi:error] [pid 2673:tid 140041613797120] [remote 101.165.248.136:53820] File "/home/ib/personal_project/venv/lib/python3.7/site-packages/django/__init__.py", line 19, in setup [Mon Nov 18 12:49:31.996176 2019] [wsgi:error] [pid 2673:tid 140041613797120] [remote 101.165.248.136:53820] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Mon Nov 18 12:49:31.996181 2019] [wsgi:error] [pid 2673:tid 140041613797120] [remote 101.165.248.136:53820] File "/home/ib/personal_project/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__ [Mon Nov 18 12:49:31.996183 2019] [wsgi:error] [pid 2673:tid 140041613797120] [remote 101.165.248.136:53820] self._setup(name) [Mon Nov 18 12:49:31.996188 2019] [wsgi:error] [pid 2673:tid 140041613797120] [remote 101.165.248.136:53820] File "/home/ib/personal_project/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 66, in _setup [Mon Nov 18 … -
django url _reverse _ not a valid view function or pattern name
the redirect url is "liveinterviewList/2" and, ofcourse, I declare that url in url.py more over, when I type that url in browser manualy, it works well. what's the matter? more question. at this case, I write the user_id on the url. I think, it is not good way to make url pattern. but I don't know how I deliver the user_id variable without url pattern. please give me a hint. -
Rendering a text field based on data entered without refreshing the page
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page. For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number". I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered. My page currently loads, but when I check the network using F12, there is never a call to the function/url that searches for the name to display it on the page. I'm not sure where I might be missing the part that connects these two areas of the code, but I … -
Django: join two table on foreign key to third table?
I have three models class A(Model): ... class B(Model): id = IntegerField() a = ForeignKey(A) class C(Model): id = IntegerField() a = ForeignKey(A) I want get the pairs of (B.id, C.id), for which B.a==C.a. How do I make that join using the django orm? -
how can I generate dyanamic charts with highcharts.js or charts.js in django?
I have a Django app where users might want to monitor their entries where they see how many entries they added this month and throughout the whole year. basically I made a DateTime field in every model and would use that to make the queries but the problem is making the template how can I make it more dynamic so I don't have to change it every year and how should I make the queries of the dates? i would use something like this -
Django debugger hangs in settings.py - Runs fine
I can't debug custom_commands in django anymore. I try it with PyCharm (tried it with VSCode as well) using the template for Django Server and entering my custom command. If I hit run on this configuration it is running fine. If I try to debug it hangs after printing the graylog configuration. I could debug it from the settings.py until it is in venv/lib/python3.6/importlib/__init__.py in the function import_module where it tries to execute the command _bootstrap._gcd_import(name[level:], package, level) and from that on it hangs. Unfortunately I can't share the repository. The same thing happens with other custom commands as well. Any ideas for that problem? -
send a contact form to mail id and PostgreSQL database using Django
I would like to send a contactform to an emailid as well as save it to postgresql database.The following code helps me to send it to the mail id but can't save it in the database. can anyone please help me to solve this one which would be very much appreciated urls.py from django.contrib import admin from django.urls import path from.import views urlpatterns = [ path('email/', views.email, name='email'), path('success/', views.success, name='success') ] models.py from django.db import models from django.forms import ModelForm class Comment(models.Model): what_about = models.CharField(max_length=255) contact_email = models.EmailField(max_length=255) content = models.TextField() Name = models.CharField(max_length=255) Phone_Number = models.CharField(max_length=255) def __str__(self): # __unicode__ on Python 2 return self.what_about forms.py from django.forms import ModelForm from django import forms from .models import Comment class MyCommentForm(forms.ModelForm): class Meta: model = Comment fields = ['what_about', 'content', 'contact_email', 'Name', 'Phone_Number'] views.py from django.shortcuts import render, redirect from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django import forms from django.utils import timezone from.forms import MyCommentForm def email(request): if request.method == 'GET': form = MyCommentForm() else: form = MyCommentForm(request.POST) if form.is_valid(): form.save() cd = form.cleaned_data subject = form.cleaned_data['what_about'] from_email = form.cleaned_data['contact_email'] message = 'contact_email: "{}"\n Phone_Number: "{}"\n Name: "{}"\n content: "{}"'.format(cd['contact_email'], cd['Phone_Number'], cd['Name'], cd['content']) try: …