Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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: … -
How to search in django ManyToMany admin edit
I have a ManyToMany field in django that I want to update in the admin dashboard. It looks like this: However there are 200+ entries here and I would like to search through them in order to update them (instead of scrolling). When I hit a key on keyboard to filter through the list, it searches in the order of the string and doesn't look for substrings. So if I type in the word "holding" I won't get any results. How can I change this so that it searches substrings? -
urls.py works but when I use <int:id> to update a particular item then I get "Current path didn't match any of these" error
My urls.py works when trying to read or create new items. But when trying to update an existing item I do the following: in app/urls.py: ... path('update_goals/<int:id>', update_goals, name='update_goals'), in views.py: def update_goals(request, id): item = Items.objects.get(id=id) form = ItemFilterForm(request.POST or None, instance=item) if form.is_valid(): # validate the form form.save() return redirect(list_items) return render(request, 'items-form.html', {'form': form, 'item': item}) in models.py: class Items(models.Model): id = models.AutoField(db_column='ID', primary_key=True) company = models.CharField(null=True, db_column='Company', max_length=40, blank=True) # Field name made lowercase. ... class Meta: managed = False db_table = 'Items' verbose_name_plural = 'Items' html: {% for i in item %} <a href="{url 'update_goals i.id'}"> <li>{{i.company}}</li> ... </a> {% endfor %} The other paths that I use to read current items and create new items work, but just the update doesn't work. The error: Page Not Found(404) Request URL: http://127.0.0.1:8000/%7Burl%20'update_goals%20i.id'%7D Using the URLconf defined in app1.urls, Django tried these URL patterns, in this order: ... update_goals/<int:id> [name='update_goals'] admin/ The current path, {url 'update_goals i.id'}, didn't match any of these. It might have something to do with the ID column, but I tried using update_goals/<str:company> abd i.company as well and it still gives the same error. -
Debug = False and static files not applied
I am trying to configure my django project I have the folder organization bellow my problem is that my styles.css files in not applied in my understanding, the path in STATICFILES_DIRS is correct but I have a 404 error [18/Nov/2019 13:58:01] "GET /static/css/styles.css HTTP/1.1" 404 2377 what I am doing wrong? - static - admin - django_extensions - project - settings.py - monitor - randomization - registration - static - css - styles.css - images STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) STATIC_ROOT = 'D:/Users/jl3/DevSpace/static/' -
Does django load translation files dynamically in runtime?
Is it possible to reload .po/.mo files in runtime dynamically in a Django web application without restarting the application server? -
Why use a pre-written audit package in Django
I am considering how to implement auditing my database with Django. There are lots of auditing packages and I am decided on using something that logs changes to models in the database, rather than externally, but can anybody give me reasons why I should not try to implement this myself? I have a finite amount of time to implement this (about a week) but should I be aware of any issues or complicating factors? I assume for each model I would need a pre-save signal and post-save signal and I would need to store the model, field, previous value and post-save value to the db -
Django-channels sending message when model changes
I'm using django-channels to organize my websockets on backend. Right now everything is working alright except of message sending to the front-end when info in db is changed. There is http endpoint to change model. Here is my websocket consumer import asyncio from asgiref.sync import async_to_sync, sync_to_async from channels.generic.websocket import AsyncJsonWebsocketConsumer from rest_framework.response import Response from rest_framework import status from channels.db import database_sync_to_async # models and serializers from billing.models import Billing from billing.serializers import BillingSerializer from customers.models import Customer from customers.serializers import CustomersSerializer from shipping.models import Shipping from shipping.serializers import ShippingSerializer from .models import Order from .serializers import OrdersSerializer from .views import OrdersViewSet from .exceptions import ClientError from .utils import get_orders_or_error, get_orders_or_warning class OrdersConsumer(AsyncJsonWebsocketConsumer): async def connect(self): orders = await get_orders_or_warning() if 'user' in self.scope: await self.close() else: await self.accept() self.orders = set(orders) # await self.create_order(content) async def receive_json(self, content): command = content.get('command', None) orders = await get_orders_or_warning() # print(list(self.orders)) # print(set(orders)) try: if command == "join": await self.join_room(JWT_Token=content['token']) elif command == "leave": await self.leave_room() elif command == "send": await self.send_room(content['message']) except ClientError as e: await self.send_json({"error": e.code}) async def disconnect(self, code): for room_id in list(self.rooms): try: self.send_json({ 'type': 'CLOSE', 'message': "Socket closed" }) await self.leave_room(content['token']) except ClientError: pass async …