Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to filter out items from RelatedManager in a ModelViewSet?
I'm using DRF for a simple API, and I was wondering if there's a way to achieve this behavior: I've got two models similar to the following: class Table(models.Model): name = models.CharField(max_length=100) ... class Column(models.Model): original_name = models.CharField(max_length=100) name = models.CharField(max_length=100, blank=True, null=True) ... table = models.ForeignKey(Table, on_delete=models.CASCADE, related_name="columns") And their serializers as follows: class ColumnSerializer(serializers.HyperlinkedModelSerializer): table = serializers.HyperlinkedRelatedField( read_only=True, view_name="table-detail" ) class Meta: model = Column fields = ["url", "name", "table"] class TableSerializer(serializers.HyperlinkedModelSerializer): dataset = serializers.HyperlinkedRelatedField( read_only=True, view_name="dataset-detail" ) tags = serializers.SlugRelatedField( many=True, slug_field="name", queryset=Tag.objects.all() ) columns = ColumnSerializer(many=True, read_only=True) class Meta: model = Table fields = [ "url", "name", ... "columns", ] This returns me an output similar to { ... "results": [ { "url": "http://0.0.0.0:8001/api/tables/1/", "name": "some-name", "columns": [ { "url": "http://0.0.0.0:8001/api/columns/1/", "name": "id", "table": "http://0.0.0.0:8001/api/tables/1/" }, ... } which is totally fine. But what I'd really want to do is, if a Column has name=None, it's filtered out from every API ViewSet. I've managed to do it on the ColumnViewSet by doing queryset = queryset.filter(name__isnull=False), but I can't do it for the TableViewSet or others that might show a Column list. I've tried tinkering with the ColumnSerializer, but the best I could get from it was … -
Is it possible to rename the application's group name in Django?
For example, you have "Groups" and "Users" under "AUTHORIZATION AND AUTHENTICATION" (or something named like that). If you make a new app and register its model, it's gonna write out the name of the application. I want to rename that in the admin. -
GNUPLOT integration with web application
I would like to point out that I am just learning programming, so I am not so experienced. I would like to create a web application in django REST framework as backend and ractjs as front end, which would create graphs using gnuplot,I would like the application to work more or less like an overleaf where the user enters the commands from gnuplot and when the button is pressed the finished graph appears. My question is what's the best way to integrate or invoke gnuplot to work like that and what's tools i should use? I saw a similar topic on the forum but no answer to his question Text. Would javascipt be a good choice or would python be sufficient for such a task? Any tips are welcome. -
NoReverseMatch at /allbook Reverse for 'random_book' with arguments '('',)' not found. 1 pattern(s) tried: ['info/(?P<pk>[0-9]+)\\Z']
NoReverseMatch at /allbook Reverse for 'random_book' with arguments '('',)' not found. 1 pattern(s) tried: ['info/(?P[0-9]+)\Z'] views.py class MoreInfoView(View): def get(self, request, id): book_info = BookModel.objects.filter(id=id).first() stuff = get_object_or_404(BookModel, id=self.kwargs['id']) total_likes = stuff.total_likes() return render(request, 'bookapp/more_info.html', context={ 'id': id, 'book_info': book_info, 'book': BookModel, 'total_likes': total_likes, }) def random_book(self): book_pks = list(BookModel.objects.values_list('id', flat=True)) pk = random.choice(book_pks) book = BookModel.objects.get(pk=pk) return HttpResponse(book) html <li class="navigation"><a class="nav-link" href="{% url 'random_book' pk %}">random</a></li> url.py urlpatterns = [ path('', index, name='index'), path('allbook', AllBookView.as_view(), name='allbook'), path('addbook', AddBookView.as_view(), name='addbook'), path('register', RegisterView.as_view(), name='reg'), path('login', LoginView.as_view(), name='login'), path('logout', LogoutView.as_view(), name='logout'), path('info/<int:id>', MoreInfoView.as_view(), name='more_info'), path('profile', profileview, name='profile'), path('password-change', ChangePasswordView.as_view(), name='change_pass'), path('like/<int:pk>', LikeView, name='like_book'), path('info/<int:pk>', views.random_book, name='random_book'), -
i got decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
views.py @api_view(["POST", "GET"]) @permission_classes([IsAuthenticated]) def add_order(request, pk): print(request.user) customer = md.Customer.objects.get(pk=pk) if request.method == "POST": description = request.data['description'] price = request.data['price'] order = md.Order.objects.create(customer=customer, date_created=zt.now(), description=description, price=float(price), customer_total_when_created=customer.total_owe[0] ) try: is_paid = request.data['is_paid'] if is_paid == "on": who_paid = request.data['who_paid'] payment_method = request.data['payment_method'] who_took_money = request.user if who_paid == customer.name: order.who_paid = customer elif who_paid == customer.parent: order.who_paid = customer.parent order.payment_method = payment_method order.who_took_money = who_took_money order.date_paid = zt.now() customer.total = customer.total_owe customer.save() order.save() except: print("no payment succeed") order_api = OrderSerializer(order) return Response(order_api.data) customer_api = CustomerSerializer(customer) parent_api = CustomerSerializer(customer.parent) context = { "customer": customer_api.data, "parent":parent_api.data, "sample": [ {"description": "secreal", "price": "12.21", "is_paid": "on", "who_paid": "azra", "payment_method": "CARD"} ] } return Response(context) models.py class Order(models.Model): payment_method_list = [("CASH","CASH"),("CARD","CARD")] customer = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True,blank=True,) who_paid = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True,blank=True, related_name='%(class)s_requests_created') who_took_money = models.ForeignKey(User,on_delete=models.CASCADE,null=True,blank=True, related_name='who_took_money') payment_method = models.CharField(choices=payment_method_list,max_length=4,default="CASH",blank=True,null=True) date_paid = models.DateTimeField(blank=True,null=True) date_created = models.DateTimeField(blank=True, null=True) date_modified = models.DateTimeField(blank=True, null=True, auto_now=True) is_paid = models.BooleanField(default=False, blank=True,null=True) customer_total_when_paid = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True) customer_total_when_created = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True) description = models.TextField(blank=True,null=True) price = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True) def __str__(self): return self.description[0:12] from django.db.models.signals import post_save def update_total_owe_created_order(sender,instance,created,**kwargs): if created: order = instance customer = order.customer customer.total = customer.total_owe[0] customer.save() post_save.connect(update_total_owe_created_order,sender=Order) def update_total_owe_updated_order(sender,instance,created,**kwargs): if created==False: order = instance customer = order.customer customer.total = customer.total_owe[0] customer.save() post_save.connect(update_total_owe_updated_order,sender=Order) I have an … -
Django Gunicorn - Failed to find attribute 'application'
I had a Django/Gunicorn app running just fine, but after a code update it stopped working due to this gunicorn error. I don't think anything has changed regarding that setup, so I am at a loss as to why it won't work now. /etc/systemd/system/triform.service [Unit] Description=triform daemon Requires=triform.socket After=network.target [Service] User=django Group=www-data WorkingDirectory=/home/triform/django ExecStart=/home/triform/django/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ triform.wsgi:application [Install] WantedBy=multi-user.target /etc/systemd/system/triform.socket [Unit] Description=triform socket [Socket] ListenStream=/run/triform.sock [Install] WantedBy=sockets.target /home/triform/django/triform/wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'triform.settings') application = get_wsgi_application() in /home/triform/django/triform/settings.py: WSGI_APPLICATION = 'triform.wsgi.application' -
How to cache query data per request
I have a decorator that fetches some data from DB and modifies response context data. This decorator is applied to several views, the problem is that every time the decorator function is being executed it makes the DB query again. I would like to cache the result of a DB only per request, on page refresh/new request I would like to fetch data again. views.py def set_data(): def wrapper(request): # fetching data from db data = get_some_data_from_db() response = view(request) response.context_data["data"] = data return response.render() return wrap @set_data def view1(request): return TemplateResponse(request, "template1.httml", context) @set_data def view2(request): return TemplateResponse(request, "template2.httml", context) I've tried to use django-request-cache library, but this doesn't solve this problem. ANy idea how can i achieve it? -
How to Change django 404 error into own html design
File not found error come in django , i want to change into own html 404 code design page or replace it. What i do for change it? -
django using request in auth form(passwordchangeview)
class PasswordsChangeView( PasswordChangeView ): form_class = PasswordChangeForm success_url = reverse_lazy('password_success') ##admin filteration group = list(request.user.groups.values_list('name',flat = True)) the request in above is not defined , it works for my function which i have request, but in auth form i don't know how to pass the request, any idea role='admin' type = search( group ,role) extra_context={'t': type} -
Access decorators from multiple views in Django
As I am learning Django, I am running into this issue I have not found a solution for. Imagine I have 5 apps in my project: * project * accounts * profiles * products * services In my accounts project, I have all of the logic for authentication and have created a decorators.py file under accounts that I would like to check from any of the apps. Under accounts, in my views.py, I simply import the decorators.py as such: from .decorators import * At this point, however, I am not seeing how to import the same decorators.py from the views.py file in other apps. -
Save Django Model when list_editable fields are changed in Django Admin change_list view
I have a Django Model which I'm trying to update from the Admin change_list view when a field that is listed in list_editable has a change event fired. Right now the only way to save the updates is by clicking a "Save" button and then the page reloads. I don't want the page to reload at all. I just want it to update the model asynchronously. For example I have the following model. class Example(models.Model): name = models.CharField() hide = models.BooleanField(default=False) In the Admin Form I have class ExampleAdmin(admin.ModelAdmin): list_display = [ "name", "hide" ] list_editable = [ "name", "hide" ] When viewing the change list for Examples now I will see the values listed out with an editable text input for name and a checkbox for hide. I would like to listen for events on those inputs and when they are fired send an async request to update the specific model. -
Is this the correct way of making primary keys in django?
class profiles(models.model): customer_ID = models.IntegerField().primary_key Is this the correct way of making a primary key in django?? -
how to copy data from model to another model in Django after filtering?
here is the models: class Rooms(models.Model): name=models.CharField(max_length=100) image=models.URLField() max_person=models.CharField(max_length=100) office=models.CharField(max_length=200) status=models.CharField(max_length=200) cost=models.CharField(null=True,max_length=250) roomId=models.CharField(max_length=100,null=True) Address= models.CharField(max_length=100,null=True) def __str__(self): return str(self.name) class Available_Rooms(models.Model): users=models.ForeignKey(Rooms,on_delete=models.CASCADE) name=models.CharField(max_length=100) image=models.URLField() max_person=models.CharField(max_length=100) office=models.CharField(max_length=200) status=models.CharField(max_length=200) cost=models.CharField(null=True,max_length=250) roomId=models.CharField(max_length=100,null=True) Address= models.CharField(max_length=100,null=True) def __str__(self): return str(self.name) at model "rooms" there is 100 objects (rooms) and what I want filter it and list rooms that have maxperson = 4 availablity= Rooms.objects.filter(maxperson="4").all() and want to to copy the rooms details to the other model "Available_Rooms" any idea how that can be done? many thanks in advance -
How to iteratively render the first X fields in a Django form
I'm rendering a form in a Django html template by using a for loop and iterating over the fields. I want to add some sections & headers inside my form, so is there a way to 'slice' the form fields or otherwise iteratively display only a subsection of fields? Something like {% for field in form.slice(0, 5) %} <!-- render first 5 fields --> <h2>Section 2</h2> <p>Some text about next section</p> {% for field in form.slice(5, 10) %} <!-- render the next 5, etc. --> I know the worst case answer is to render each field manually, but it's a VERY long form. Here's my existing form code. {% for field in form %} <div class="field"> <label class="label" for="{{field.id_for_label}}"> {{field.label}} </label> <div class="control">{{field}}</div> {% if field.help_text %} <p class="help">{{field.help_text}}</p> {% endif %} <ul class="errorlist"> {% for error in field.errors %} <li class="is-danger help">{{error}}</li> {% endfor %} </ul> </div> {% endfor %} -
Django version downgraded when I install third party Django package
When we upgrade Django version this two packages prompted incompatible Installing collected packages: django Attempting uninstall: django Found existing installation: Django 3.1.6 Uninstalling Django-3.1.6: Successfully uninstalled Django-3.1.6 ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the foll owing dependency conflicts. django-helpdesk 0.3.4 requires Django<4,>=2.2, but you have django 4.0.4 which is incompatible. django-celery-beat 2.2.1 requires Django<4.0,>=2.2, but you have django 4.0.4 which is incompatible. Successfully installed django-4.0.4 When we try to upgrade packages(django-helpdesk) django core version was downgraded. Is this not a bug? pip install django-helpdesk --upgrade -------- -------- -------- Installing collected packages: Django Attempting uninstall: Django Found existing installation: Django 4.0.4 Uninstalling Django-4.0.4: Successfully uninstalled Django-4.0.4 Successfully installed Django-3.2.13 Please help me -
Python Django login logout logic
In this question I won't add any code. Just wanted to know whether I should redirect the user to home page if user is already authenticated in the system but tries to visit login page. What is the best solution? -
Trouble with Django and Google Charts
I'm trying to make my page update in real time but for some reason the code get's stuck on "var = new_data ..." function refresh() { $.ajax({ type:"GET", url: "{% url 'get_data' %}", data:{ poll_id: {{ poll.id }} }, success: function(data) { // the code stops running here var new_data = google.visualization.arrayToDataTable(data); var options = { title: "Results", legend: 'none' }; var chart = new google.visualization.PieChart(document.getElementById('chart_div')); chart.draw(new_data, options); }, }); setTimeout(function () { refresh() }, 1000); }; } -
sql query not work in django but dose in sql shell
i have a project in django 3 and try to create a filter for finding conflicted item via datetime in postgresql 13. when i use below script via postgesql shell, it worked!. SELECT a.*, b.* FROM users_task AS a JOIN users_task AS b ON daterange(a."startDatetime"::date, a."endDatetime"::date) && daterange(b."startDatetime"::date, b."endDatetime"::date) WHERE (a."startDatetime"::date, a."endDatetime"::date) <= (b."startDatetime"::date, b."endDatetime"::date) but when i use it in my code, not work and return empty. return tsk.objects.raw(''' SELECT a.*, b.* FROM users_task AS a JOIN users_task AS b ON daterange(a."startDatetime"::date, a."endDatetime"::date) && daterange(b."startDatetime"::date, b."endDatetime"::date) WHERE (a."startDatetime"::date, a."endDatetime"::date) <= (b."startDatetime"::date, b."endDatetime"::date) ''') i found &&(contains) not work when inserted in my code. please help me. -
django get module path in shell
I am on a really big project that jump among many modules, here's a difficulty, sometimes I add a print in certain line of particular file, for testing purposes. after building, I run the file from shell, and there is a line output comes from nowhere pops up in my command line (well, not exactly nowhere, I forgot where I added the print), I need a stronger print like: print('test') # test flags/urls.py 348 therefore, I am building a put function, from inspect import currentframe def put(value): frameinfo = currentframe() location = 'path to this module' print(f'{value} {location} {frameinfo.f_back.f_lineno}') put({'name': 'jason'}) # {'name': 'jason'} path to this module 9 when I tried to work out the path, something unexpected happened. flags/test.py print(__file__) # /Applications/MAMP/htdocs/canvas/src/zzd/env/lib/python3.7/site-packages/django/core/management/commands/shell.py shell (env) 🌹 python manage.py shell < '/Applications/MAMP/htdocs/canvas/src/zzd/zzd/flags/tests.py' /Applications/MAMP/htdocs/canvas/src/zzd/env/lib/python3.7/site-packages/django/core/management/commands/shell.py it turns out to always return the path of shell.py, instead of my module file path. I wonder why this happens, would be very gratefully for your help. -
Run different python files on Django startup
After running my Django project, I want my different python files to run concurrently until I terminate the project. When I run "python manage.py runserver" I want different python files to run at the same time. Is there a way to do this in django? I searched but couldn't find the exact result I wanted. -
Django FIlter: Filtering object hidden in multi layered model structure
I have a following django model relationship: model Project(): model Vehicle(): ForeignKey(Project) model Concept(): ManyToManyField(Vehicle) model Analysis(): ForeignKey(Concept) I want to sort out all Analyses objects which are connected to a Project with a known id. Concept can be for more than one vehicle but all the vehicles within a concept will be limited to only one Project. Or should i justadd to all following models a foreignkey with a project field? Thanks -
How can I add Datepicker in DjangoCreateView
#view.py class JobCreateView(CreateView): model = Job template_name = 'Job_create.html' fields = ['Company' ,'Job_title','Department','Start_date','end_date','Consent'] def form_valid(self, form): form.instance.Alumni_id = self.request.user.alumni return super().form_valid(form) def get_form(self): '''add date picker in forms''' form = super(JobCreateView, self).get_form() form.fields['end_date'].widget = forms.SelectDateWidget() return form from get_form function I got this kind of date Input but I want a date picker that's look like a calender -
django add method to standard Model class
from articles.models import Article label = f'{Article._meta.app_label}.{Article._meta.object_name}' I need to use label for almost all inherited classes from from django.db import models.Model, I want to add this method to the standard Model class without changing library file. if there is built-in way to mix-in a bunch functions to model class without adding inheritance classes and changing initial file, please let me know, I more than grateful. class Model(metaclass=ModelBase): def label(cls): return f'{cls._meta.app_label}.{cls._meta.object_name}' -
How to deal with django migration postgres deadlock?
So, I was deploying the django app to production and then the infamous postgres deadlock situation happened. This happens during the migration. Django version: 3.2 Postgres 13 Google cloud sql postgres. OperationalError deadlock detected DETAIL: Process 112506 waits for AccessExclusiveLock on relation 29425 of database 27145; blocked by process 112926. Process 112926 waits for RowShareLock on relation 29381 of database 27145; blocked by process 112506. HINT: See server log for query details. I ran this query to get the process info: SELECT 29425::regclass,29381::regclass from pg_locks; and result: regclass | regclass "custom_requestlog" "auth_user" "custom_requestlog" "auth_user" I am not sure how to proceed ahead, as the pgaudit has been enabled but it doesnt show anything and also the query insights is not that helpful. Attached is image of query insights. Any help would be helpful please! -
Error won't showing up, Form validation with Django
I just started learning Django for my new Forum project, I'm trying to find it out myself but this problem has been bothering me since 2 days. I am trying to make a registration validation for my form, I am using messages.error(request, "Text") to make an error appear on screen, but it doesn't work, and just shows nothing. Here is a part of my HTML code: <div class="limiter"> <div class="container-login100" style="background:black;"> <div class="wrap-login100"> <form class="login100-form validate-form" method='POST' action="{% url 'users:register' %}" > {% csrf_token %} <span class="login100-form-logo"> <i class="zmdi zmdi-landscape"></i> </span> <span class="login100-form-title p-b-34 p-t-27"> Register </span> <div class="wrap-input100 validate-input" data-validate = "Enter username"> <input class="input100" type="text" name="username" placeholder="Username" required> <span class="focus-input100" data-placeholder="&#xf207;"></span> </div> <div class="wrap-input100 validate-input" data-validate="Enter password"> <input class="input100" type="password" name="pass" placeholder="Password" required> <span class="focus-input100" data-placeholder="&#xf191;"></span> </div> <div class="wrap-input100 validate-input" data-validate="Confirm password"> <input class="input100" type="password" name="pass-confirm" placeholder="Confirm Password" required> <span class="focus-input100" data-placeholder="&#xf191;"></span> </div> <div class="wrap-input100 validate-input" data-validate="Enter Email"> <input class="input100" type="email" name="mail" placeholder="E-Mail" required> <span class="focus-input100" data-placeholder="&#xf191;"></span> </div> <div class="container-login100-form-btn"> <button class="login100-form-btn"> Register </button> </div> <div class="text-center p-t-90"> <a class="txt1" href="login"> Already registered? </a> </div> </form> </div> </div> </div> Here is my views.py register function: def register(request): if request.method == "POST": username = request.POST["username"] password = request.POST["pass"] password_confirm …