Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Admin: Show related inline ManyToMany objects as MultipleChoiceField
I've overridden the UserAdmin class and wanted to add a user profile and some related objects as inline. I get now a table with related objects. But that's not really ideal for my application, it's a bit cumbersome to change the related objects, and there's no need to add new objects this way. I'd like to have simple MultipleChoiceField containing the related objects. Is there an easy way to achieve this? Here's my userprofile/admin.py: from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from django.utils.translation import gettext_lazy as _ from django_admin_listfilter_dropdown.filters import RelatedOnlyDropdownFilter from driverslog.models import Branch from driverslog.models import Car from .models import Userprofile User = get_user_model() class ProfileInline(admin.TabularInline): model = Userprofile can_delete = False max_num = 0 extra = 0 fk_name = 'user' class CarInline(admin.TabularInline): model = Car.users.through can_delete = True verbose_name = _('Car') verbose_name_plural = _('Cars') extra = 0 class BranchInline(admin.TabularInline): model = Branch.users.through can_delete = True verbose_name = _('Branch') verbose_name_plural = _('Branches') extra = 0 class CustomUserAdmin(UserAdmin): inlines = (ProfileInline, BranchInline, CarInline) list_display = ('username', 'first_name', 'last_name', 'is_staff', 'is_superuser', 'represents') list_filter = ('is_active', 'is_staff', 'is_superuser', ('groups', RelatedOnlyDropdownFilter), ('branches', RelatedOnlyDropdownFilter), ('profile__represent', RelatedOnlyDropdownFilter), ('car', RelatedOnlyDropdownFilter)) def represents(self, obj): return obj.profile.represent.count() represents.short_description = _('Represents') admin.site.unregister(User) admin.site.register(User, … -
Python Django duplicate loop
i fetch two table from my db like this: query_tags = Tags.objects.all() query_usertags = UserNews.objects.all() context = {'query_tags': query_tags, 'query_utags': query_usertags} and in my html , i try that: {% for tags in query_tags %} {% for utags in query_utags %} {% if utags.user_tag == tags.name and utags.userid == user.id %} <input disabled type="checkbox" id="development" value={{ tags.name }} name="user_interest"> <label class="light" for="development">{{ tags.name }}</label><br> {% else %} <input type="checkbox" id="development" value={{ tags.name }} name="user_interest"> <label class="light" for="development">{{ tags.name }}</label><br> {% endif %} {% endfor %} {% endfor %} but my problem is output gonna duplicated cuz of second loop can you help me ? -
Django Ajax Javascript: Why Does My Function Use Class Name Instead Of id
I am trying to make a like post button that won't refresh the page so im trying to use ajax to do this. I am trying to log the id to see if it works but it just logs like_form (which is the class for the form). Scripts: <script> $(document).ready(function() { $('.like_form').submit(function(e){ e.preventDefault() const post_id = $(this).attr('id') console.log(post_id) const url = $(this).attr('action') let res; const likes = $(`.like_count${post_id}`).text() const trimCount = parseInt(likes) console.log(trimCount + 1) }) }); </script> form <form id="like_form" action="{% url 'like_post' item.id %}" class="like_form" id="{{ item.id }}"> console: like_form -
How do i get email of a user after signing them in with django all auth
I am using django all auth to authenticate users but after authentication there is no email being saved to the database how can i get the email of the user? Thanks in advance -
Django Unicorn Failed About SQLite Version
I deployed django app to CentOS 7 Server. I want to use Nginx and Gunicorn. By the way i tried to make steps, gunicorn best.wsgi:application --preload -b 0.0.0.0:8000 when i run this code whit virtual environment gunicorn outputs like; [2021-01-11 14:56:16 +0000] [93067] [INFO] Starting gunicorn 20.0.4 [2021-01-11 14:56:16 +0000] [93067] [INFO] Listening at: http://0.0.0.0:8000 (93067) [2021-01-11 14:56:16 +0000] [93067] [INFO] Using worker: sync [2021-01-11 14:56:16 +0000] [93070] [INFO] Booting worker with pid: 93070 and working... But when i try to write gunicorn.service like : [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=root WorkingDirectory=/root/best/best ExecStart=/root/best/virtenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/root/best/best [Install] WantedBy=multi-user.target I am getting error like : django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). I get this error before and i solved it but its about my virtual environment, i downloaded sqlite version and it worked ('import sqlite3; sqlite3.sqlite_version' output is 3.30.0). But i dont know how i fix it in Gunicorn side. (Maybe its about gunicorn doesn't see my virtual environment but i can't found how i change this) Any suggestion to solve it? Thx to all. -
What is the conventional way to write external SQL files in Django
I'm making a Django app that connects to a PostreSQL database other than the database used by the Django app itself. currently, I'm writing SQL code inside constant strings in python files, most queries contain multiple variables which are retrieved from the python script at runtime like: import psycopg2 connection = psycopg2.connect("connection information")) cursor = connection.cursor() customer_id = 5 cursor.execute('SELECT * FROM sometable WHERE id = {0}'.format(customer_id)) Howere, the SQL code will be more sophisticated than this and I have many different queries that need to be saved and reused and putting just inside python files is a very bad and unorganized way so I would prefer to save them in external files but also I wanna make sure I'm still following Django's conventions. So where should I be saving my custom .sql fils? is there any special utility for this in Django? -
How to obfuscate vue js code used in django template as inline script?
I am developing an app using django as backend, and django templates for front end (Pages reload when navigating between urls). For some advanced features, I had to use ajax communication between the template and the backend to avoid reloading for each action. So I ended up using vue js to react to server responses and also to build a pretty sophisticated UI. Usually I use django compressor & uglifyjs to minify and mangle the variable names of my scripts build with jquery or vanilla js on each user request (middleware) using {% compress %}. This time with vue, when I mangle the data and function names, their references from the html in the v-if and v-bind: ...etc remains the same as before causing the UI to break because the v- instructions in the html doesn't use the new variable names after the mangling. I want to know if there is a way to parse the html and rename the refrences with django compressor. In case compressor doesn't provide such feature, is there some npm package or other tool/script that I can manually feed a file.html containing both HTML and my vue js code and it does the renaming and … -
best practice to add/remove single objects from a many to many field via generic api view
So I have a view like this class MemberRolePutDeleteView(MultipleFieldMixin, PutDeleteAPIView): """ An API view to create member-roles as well as delete the same. Although the role is returned by the get_object method, we only remove the same from the referenced member, and don't delete/modify it. """ queryset = api_models.Role.objects.all() permission_classes = [IsAuthenticated, ManageRoles] lookup_fields = ['cluster_id', 'pk'] def destroy(self, request, *args, **kwargs): role = self.get_object() member = api_models.Member.objects.get(user__id=self.kwargs['user_id'], cluster=role.cluster) member.roles.remove(role) return Response(status=204) def update(self, request, *args, **kwargs): role = self.get_object() member = api_models.Member.objects.get(user__id=self.kwargs['user_id'], cluster=role.cluster) member.roles.add(role) return Response(status=204) I get the object I want via the get_object method. Now, in the api view, I want to remove the same from member.roles or add to it, instead of actually deleting the object. I am doing this right now by overriding the methods. However, I think that there is a better way to achieve this. Can someone please help me to do the same? thanks a lot! -
Add or Remove Row in Input Table Along With Some Available Jinja
I have an HTML table with some jinja(inside the value attribute). my template: <form class="" method="POST"> {% csrf_token %} <table class="table table-hover my-5"> <thead class=""> <tr> <th>No</th> <th>Name</th> <th>rank</th> <th>gmail</th> <th>Delete?</th> </tr> </thead> <tbody class="my_dynamic_table"> {% for i in report_tableA %} <tr> <td>i</td> <td><input type="text" name="name" value="{{ i.name }}"></td> <td><input type="text" name="rank" value="{{ i.rank }}"></td> <td><input type="email" name="gmail" value="{{ i.gmail }}"></td> <td><i class="fa fa-times-circle" style="font-size: 22px; color: red;"></i></td> </tr> {% endfor %} </tbody> </table> <div class="row mx-5"> <button class="btn btn-warning">Add row</button> <button type="Submit" class="btn btn-primary ml-auto">Submit</button> </div> </form> Now my problem is how can I implement the functionality of the Add row button and the Delete icon(inside last td)? Here Add row function will add a new row inside the table also with a blank value attribute. I have practiced it before by the following stackoverflow link. but now the problem is jinja is also added here. I will be very grateful if you help me to fix this out. -
Same column pointing to 2 different foreign keys in Django
I have 3 models in Django: Student Teacher Publication A single publication can have multiple authors, who can be both students and teachers. Since a student and teacher can have multiple publications and a publication can have multiple teachers and students as authors, I am using a M2M relationship using a through table called PublicationAuthor. However, I am not sure how to get my authors column in my through table. My effort so far : from django.db import models class Student(models.Model): name = models.CharField(max_length=50) publication = models.ManyToManyField(Publication, through=PublicationAuthor, related_name='students') class Teacher(models.Model): name = models.CharField(max_length=50) publication = models.ManyToManyField(Publication, through=PublicationAuthor, related_name='students') class Publication(models.Model): title = models.CharField(max_length=50) class PublicationAuthor(models.Model): publication = models.ForeignKey(Publication, on_delete=models.CASCADE) authors = -
Different submit button for the form on one page (django)
Hello sorry for the inconvenience. I want advice from you. I have question and answer inputs. In the question input, the question is written and in the answer input, the user must enter the answer. How can I do this in html so that there is a separate submit button for each form You can not see the code because I have not completed it yet I just wonder how the html logic is done for example (image) There are 2 forms rendered in the photo but there can be many Thanks for the help -
How to control selection of items in Django's QuerySet in html template?
I need 2 buttons that would control which item from QuerySet should be displayed as a part of video player to change playlist videos back and forth (all other features are done and good). In views.py I have function that sends QuerySet through "video.objects.all()" and I can select any item in HTML template by calling like "videos.all.1.video.url". But IDs arre hardcoded and for loop doesn't seems to be fitting here. So I'm stuck how and where to control items by IDs. Should be html (java?) or in Django's views.py? Some pointing the right direction would help. -
django-filter using a URL parameter and a related foreign key name
I have the following two models class Foo(models.Model): name = models.CharField(max_length=200) class Bar(models.Model): a = models.ForeignKey( "Foo", related_name="bars", on_delete=models.SET_NULL, null=True, ) Now I data in the following link http://127.0.0.1:8000/en/api/v2/dm/ and has the form: [ { "id": 4, "name": "whatever1", "bars": [ 203 ] }, { "id": 5, "name": "whatever2", "bars": [ 228, 113, ] }, ] I also have a template which would add the following parameter to the previous link http://127.0.0.1:8000/en/api/v2/dm/?bar=113 where bar indicates the id of a bar, notice that each bar's id appears only once, what I need is to filter the data in the previous link so if bar=113 it would only display [ { "id": 5, "name": "whatever2", "bars": [ 228, 113, ] }, ] I managed to do so doing the following class AView(ListAPIView): serializer_class = ASerializer def get_queryset(self): queryset = A.objects.all() bar = self.request.query_params.get('bar', None) queryset = queryset.filter(bars=bar) return queryset where ASerializer is class ASerializer(serializers.ModelSerializer): class Meta: model = A fields = ("id", "name", "bars") my question is, can I achieve the same using django-filter and filterset_class or filterset_fields?? -
drf-spectacular issue with filterset_fields
I am trying to implement drf-spectacular to an existing Django REST API. However I am getting the following error, when attempting to run ./manage.py spectacular --file schema.yml Error: TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: client, tenant_id, subtenant_id, data_stream_id The filters do work, but don't seem to play nicely with the drf-spectacular lib. Can anyone please advise on how this might be solved? Specs as follows: Python 3.7.2 Django 3.0.2 django-filter 2.2.0 django-rest-framework 0.1.0 djangorestframework 3.12.1 drf-spectacular 0.12.0 Viewset example: class DataStreamViewSet(viewsets.ModelViewSet): """Standard ViewSet for the DataStream Model.""" queryset = DataStream.objects.all() serializer_class = DataStreamSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ('client', 'tenant_id', 'subtenant_id', 'data_stream_id',) Serializer example: class DataStreamSerializer(serializers.ModelSerializer): """Class to validate an uploaded DataStream.""" class Meta: """Nested Meta Class.""" model = DataStream fields = '__all__' -
Django create tree table efficiently MPTT
I need to implement a table of different products inside a dashboard in a hierarchial structure / tree. I'd need to do that in the most efficient way, as currently the page takes for ever to load. The tree has 3-4 dimensions in total. I'm using django-mptt for creating the queries on the backend. Which template tags of django-mptt should I use and how should I combine it with HTML in order to create the rows inside the table? Example would be great. -
I created an API in DRF in which i can create coupon code in admin panel, can anyone guide me how i can redeem using script
I created an simple Django rest framework api where i create Coupon in admin panel now i want to validate/redeem that coupon using simple python script or javascript or HTML but i don't know how, Please anyone can help? Here is my models.py File : from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Coupon(models.Model): code = models.CharField(max_length=50, unique=True) valid_from = models.DateTimeField() valid_to = models.DateTimeField() discount = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) active = models.BooleanField() def __str__(self): return self.code Here is my views.py file from django.shortcuts import render from .models import Coupon from .serializers import CouponSerializer from rest_framework import viewsets class CouponViewSet(viewsets.ModelViewSet): queryset = Coupon.objects.all() serializer_class = CouponSerializer Here is my serializer.py file from rest_framework import serializers from .models import Coupon class CouponSerializer(serializers.ModelSerializer): class Meta: model = Coupon fields = '__all__' Please if possible help, Thank you. -
Graphql query error handling like mutation error
we can easily catch validation error from graphql mutations but if we need to raise some exception from query resolver what would be the standard way. for example: some_value = some_model.objects.get(id=1) if not some_value: raise ValidationError(field: "Error message") -
dj-rest-auth api endpoints urls page not found
settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # drf, rest_auth, allauth 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth.registration', # apps 'board_subject_restful', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ] } SITE_ID = 1 urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('', include('board_subject_restful.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), ] When attempting to connect to rest-auth/ url, the following error occurs. api-auth/, rest-auth/registration/, all rest-auth Api endpoints urls The same error also occurred. *dj-rest-auth is the same situation enter image description here -
Django demand login in url
I have a Django page with content that changes depending on whether the user is authenticated or not (more content when the user is authenticated) Is there a way to provide an URL to this page, but login the user first if he's not logged in, and do nothing if the user is already logged in? There is the https://www.example.com/login/?next=/mypage/ syntax, but this will ask for a login even if the user is already logged in. Any way to achieve this easily? -
'at=error code=H10' WHILE DEPLOYING TO HEROKU
So i have a project that i am trying to deploy to heroku and i keep getting the above error, let me share my code and if you need any other part of the code please ask, thank you It shows an application error when i open the app through heroku first, the heroku logs --tail brings this result 2021-01-11T13:11:58.739363+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app 2021-01-11T13:11:58.739364+00:00 app[web.1]: mod = importlib.import_module(module) 2021-01-11T13:11:58.739364+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2021-01-11T13:11:58.739365+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-01-11T13:11:58.739365+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-01-11T13:11:58.739366+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-01-11T13:11:58.739366+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked 2021-01-11T13:11:58.739366+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 671, in _load_unlocked 2021-01-11T13:11:58.739367+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 783, in exec_module 2021-01-11T13:11:58.739367+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2021-01-11T13:11:58.739368+00:00 app[web.1]: File "/app/personalgallery/wsgi.py", line 16, in <module> 2021-01-11T13:11:58.739368+00:00 app[web.1]: application = get_wsgi_application() 2021-01-11T13:11:58.739368+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-01-11T13:11:58.739369+00:00 app[web.1]: django.setup(set_prefix=False) 2021-01-11T13:11:58.739369+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 19, in setup 2021-01-11T13:11:58.739369+00:00 app[web.1]: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2021-01-11T13:11:58.739370+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ 2021-01-11T13:11:58.739370+00:00 app[web.1]: self._setup(name) 2021-01-11T13:11:58.739374+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 69, in _setup 2021-01-11T13:11:58.739374+00:00 app[web.1]: self._wrapped = Settings(settings_module) … -
I want import my terminal(print) data to database in selenium project, i am using sqlite3
management/commands/pyr.py **from selenium import webdriver from django.core.management.base import BaseCommand from databackup.amazon.models import Amazon print1 = webdriver.Chrome(executable_path='/home/sr/PycharmProjects/selenium/automation/KPTGR/chromedriver')** **print1.get('https://www.google.com/') got = print1.find_element_by_id('SIvCob') print(got.text)** *#till here everything works fine in terminal as "Google offered in: हिन्दी বাংলা తెలుగు मराठी தமிழ் ગુજરાતી ಕನ್ನಡ മലയാളം ਪੰਜਾਬੀ"* #now I am trying to send (got.text) into my database model named 'Amazon' and 'order_detail' as its textfield. **class Command(BaseCommand): help = 'Some description...' def handle(self, *args, **options): # … run selenium … Amazon.objects.create( got )** #after implementing class, this gave error as 'you must either define the environment variable DJANGO_SETTINGS_MODULE or ...'* is there any other method to access my terminal data to database or I can improve this command -
how to load javascript in django templates
i'm trying to apply my JS file to templates but it doesn't applied. i tried using <script src="{% static 'js/main.js' %}" type="text/javascrpit"></script> instead of <link rel="stylesheet" href="{% static 'js/main.js' %}"> plus stored my static files in my app folder instead of root directory HTML {% load static%} <!-- css --> <link rel="stylesheet" href="{% static 'css/main.css' %}"> <!-- js --> <link rel="stylesheet" href="{% static 'js/main.js' %}"> JS const searchBtn = document.querySelector(".search_btn") const cancelBtn = document.querySelector(".cancel_btn") //const searchBtn = document.querySelector(".search_btn") const searchBox = document.querySelector(".searchBox") searchBtn.onclick = () =>{ searchBox.classList.add("active"); } settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'statics'), os.path.join(BASE_DIR, 'vendor'), ] and TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], ..... directory django: 3.1.5 python: 3.8.5 -
Update Query list in Django
I'm having a trouble on how can I automatically update my amount_unpaid when the time I updated my amount_paidcolumn. The result of amount_unpaid should be subtract my amount - amount_paid = amount_unpaid . The way I updated my data is using list like the code below, please check this out, Any help is much appreciated Thanks in advance. AttributeError: 'QuerySet' object has no attribute 'amount' def update_remarks(request): product_ids = request.POST.getlist('id[]') amt_paid = request.POST.get('amount_paid') for id in product_ids: unpaid_update = (Person.objects.filter(pk=id).amount - amt_paid) #Error no attribute Amount Person.objects.filter(pk=id).update(amount_paid = amt_paid) # this should update every amount_unpaid based on subtracted amount column Person.objects.filter(pk=id).update(amount_paid = amt_paid) -
django DetailView url hiding pk
//i have a detailview in Django http://www.test.nl/detail_view/1/ //is there a way to hide the /1/ in the url so users don't see that? -
Can we club multiple generic class based views in django?
I want to display a list of items and also a form to add further items at the end of the list. Hence I was thinking of creating a view as something below: I have come across a class called ListCreateAPIView but I don't want to use django rest framework. Please let me know your suggestions if and how can I club two generic class based view and how the path in urls.py would look like. Further how should we refer to the list and create form objects in 'listnadd_task.html'? <views.py> from django.views.generic import ListView, CreateView from .models import Task from .forms import CreateTask class ListAndAddView(ListView, CreateView) model = Task form_class = CreateTask context_object_name = 'listnadd_task' ...