Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cannot render model attributes by slug to the template
I have set a model including some attributes and can get the model by a slug in views.py. However, I can't render its attributes into the template. Did I miss something? Model.py class article(models.Model): title = models.CharField(max_length=200) content = RichTextUploadingField() slug = models.SlugField(unique=True, max_length=200) def __str__(self): return self.title Views.py def post_details(request, slug): details = get_object_or_404(article, slug=slug) context = { details: 'details' } return render(request, 'post_details.html', context) Urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('<slug:slug>/', views.post_details, name='post_details') ] I have set a URL to get the article model's data by slug in index.html <h4 class="title"><a href="{% url 'post_details' article.slug %}">{{ article.title }}</a></h4> post_details.html <h2>{{ details.slug }}</h2> I can access this template by slug but can't get any attributes by using the 'details' tag -
Using Django-tables2 with class-based view and non-default database throws "NameError: name 'TypeError' is not defined"
I am trying to set up django-tables2 and followed the recommendations in their docs. However, if I call the view, it throws the error File "/home/ubuntu/mysite/mysite_venv/lib/python3.8/site-packages/asgiref/local.py", line 94, in __del__ NameError: name 'TypeError' is not defined Note: From what I could gather, this error message unfortunately also occurs in other contexts as the most upvoted thread deals with an Apache config problem. I would be glad to adjust the title for clarity once the issue has been grasped concisely. Django-tables2 should access (read-only) a legacy MySQL database which I added behind the default SQLite database in settings.py (see further down). My polls/models.py: from django.db import models import datetime from django.db import models from django.utils import timezone ... class Dashboard(models.Model): host = models.CharField(db_column='Host', max_length=255, blank=True, null=True) title = models.TextField(db_column='Title', blank=True, null=True) operation = models.CharField(db_column='Operation', max_length=255, blank=True, null=True) performedat = models.DateTimeField(db_column='PerformedAt', blank=True, null=True) class Meta: managed = False db_table = 'dashboard' In case it's necessary, the underlying table in MySQL looks like this: c.execute('''CREATE TABLE dashboard( id INT PRIMARY KEY AUTO_INCREMENT, Host VARCHAR(255), Title TEXT, Operation VARCHAR(255), PerformedAt DATETIME);''') My polls/views.py: from django.shortcuts import render from django.views.generic.list import ListView from .models import Dashboard from django.http import HttpResponse class DashboardListView(ListView): model = Dashboard … -
Unable to display multiple readonly fields in Django admin, only one will display
I'm trying to display two new rows (fields) in the "posts" section of django admin which are read-only fields that take data from two other database columns. My code works, but it will not create two new fields, it only displays one. I'm relatively new to Django and python, and I'm struggling to figure out how to do this. I spent too much time trying different things only to have no success. In the context of my test, I want to see two readonly fields called "New row 1" and "New row 2", which take the data from two database columns called "est_completion_time" and "downtime". I can only see "New row 2" on the output. This is my code in admin.py: @admin.register(Post) class PostAdmin(admin.ModelAdmin): form = JBForm exclude = ['est_completion_time'] # hide this database column exclude = ['downtime'] # hide this database column readonly_fields = ['placeholder_1'] # display this one readonly_fields = ['placeholder_2'] # display this one @admin.display(description="New row 1") def placeholder_1(self, obj): return obj.est_completion_time # a new readonly field which should display contents of 'est_completion_time' column @admin.display(description='New row 2') def placeholder_2(self, obj): return obj.downtime # a new readonly field which should display contents of 'downtime' column After reading through … -
Django Filter specific user's salary within giving date range
I have Two models : class MonthSalary(models.Model): month = models.DateField(null=True) def __str__(self): return str(self.month.year) + '/' + str(self.month.month) class SalaryPerMonth(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) salary_month = models.ForeignKey(MonthSalary, null=True, on_delete=models.CASCADE) main_salary_per_month = models.PositiveIntegerField(default=0, null=True) net_salary_per_month = models.PositiveIntegerField(default=0, null=True) class Meta: constraints = [ models.UniqueConstraint(fields=["user", "salary_month"], name="all_keys_unique_together")] def __str__(self): return str(self.user.employeedetail.empcode) + ' ' + str(self.net_salary_per_month) + ' LYD ' + str( self.salary_month) In Views I can query all user salaries with : user = request.user salary_per_month = SalaryPerMonth.objects.filter(user=user) In MonthSalary model I added a bunch of months\years not in order Ex "2022-2,2022-4,2022-1,2021-4" when I filter user's salary by ordering the date "related salary_month field" like so : salary_per_month = SalaryPerMonth.objects.filter(user=user).order_by('salary_month') It's not in order. Q1 = How how filter by Year ? Q2 = How to order by month ? -
how to make subdomains in django?
I want to make a panel which has two main urls by the name user and admin and also each of the "user" and "admin" urls have other urls. for example -> " site.com/panel/user/id/profile " OR " site.com/panel/admin/id/addItem " . but idk how can I make this main urls and subdomain urls :) -> ecoverde/urls.py : from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')), path('panel/', include('panel.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ecoverde/panel/urls.py ((this is where i want to add two main urls and other sub urls) : from .views import userPanel, Compare, saves from django.urls import path urlpatterns = [ #main urls that i want path('user dashboard/<str:pk>', userPanel, name='userPanel'), path('admin dashboard/<str:pk>', adminPanel, name='adminPanel'), #sub urls that i want path('compare', Compare, name='compare'), path('saves', saves, name='saves'), #... ] -
Django, unable to locate static files when using Dropbox
I'm new to Django and I'm trying to understand the static and media files. I'm following this practical example which uses AWS As I don't have AWS but Dropbox, I used django-storages but with Dropbox instead of AWS. It works fine while storing the files locally. However, when pointing to Dropbox, I'm able to upload them but when loading the django app it fails as it does not find the icons. Dropbox folder structure is as follows: Dropbox Aplicaciones ptstg bulma.min.css admin img icon1.jpg ... fonts ... css ... js ... The value of my variables in SETTINGS are: DROPBOX_ROOT_PATH = '/Aplicaciones/ptstg' DROPBOX_LOCATION = 'static' STATIC_FILES = 'staticfiles' STATIC_URL = f'{DROPBOX_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage' I'm expecting to store and access the static and image files from the root folder /Aplicaciones/ptstg. And it does. However, it uploads all files into a folder called 'admin' with the icons inside img folder (same img folder name is used when locally, and it works). When I try to reload my site, it fails and it complain: Exception Value: ApiError('dea1242d617d4ef9a8b9afe5ab06fd97', GetTemporaryLinkError('path', LookupError('not_found', None))) And it points to the following file: Error during template rendering in template /usr/src/app/upload/templates/upload.html, error at line 8 1 … -
django admin error target lists can have at most 1664 entries
I want to use from django admin to add some data and check them in my project but i have a strange error please help me to understand what is this error and how can I solve it. my model: class Task(BaseModels.AbstractField): STATUS_CHOICES = ( ('شروع نشده', 'شروع نشده'), ('درحال انجام', 'درحال انجام'), ('خاتمه یافته', 'خاتمه یافته'), ('لغو', 'لغو'), ('ارجاع به آینده', 'ارجاع به آینده'), ('ارجاع به دیگری', 'ارجاع به دیگری'), ) PRIORITY_STATUS = ( ('معمولی', 'معمولی'), ('فوری', 'فوری'), ('آنی', 'آنی'), ) reference = models.ForeignKey('self', on_delete=models.PROTECT, related_name='children',verbose_name='تکلیف مرجع') project = models.ForeignKey('TaskManager.Project', on_delete=models.PROTECT, related_name='tasks', verbose_name='پروژه') category = models.ForeignKey('TaskManager.TaskCategory', on_delete=models.PROTECT, related_name='tasks', verbose_name='دسته بندی تکلیف') content = models.TextField(verbose_name='توضیحات') expert = models.ForeignKey('Identity.User', on_delete=models.PROTECT, related_name='expert_tasks', verbose_name='کارشناس') expert_head = models.ForeignKey('Identity.User', on_delete=models.PROTECT, related_name='expert_head_tasks', verbose_name='کارشناس مسئول') priority = models.CharField(max_length=10, choices=PRIORITY_STATUS, default='معمولی', verbose_name='اولویت') estimated_time = models.IntegerField(verbose_name='زمان مورد نیاز برای انجام(ساعت)') estimated_date = jmodels.jDateField(verbose_name='تاریخ تخمینی اتمام') deadline_date = jmodels.jDateField(default=None, verbose_name='مهلت تحویل') close_date = jmodels.jDateField(verbose_name='تاریخ اختتام') close_content = models.TextField(verbose_name='توضیحات اختتام') status = models.CharField(max_length=15, choices=STATUS_CHOICES, default='شروع نشده', verbose_name='وضعیت') other_expert = models.ForeignKey('Identity.User', null=True, on_delete=models.PROTECT, related_name='other_expert_tasks', verbose_name='کارشناس ارجاع داده شده') meetings = models.ManyToManyField('TaskManager.Meeting', blank=True, through='TaskManager.Task2Meeting', verbose_name='جلسات') my admin: from django.contrib import admin from .models import Meeting, Task class TasksAdmin(admin.ModelAdmin): list_display = ('category', 'expert', 'content', 'priority', 'estimated_time', 'estimated_date', 'deadline_date', 'status') and my error: target lists … -
Form not being made despite having correct format
I am new to django and I am trying to load the 'form' variable into the html page here's the views.py function def show(request): showall = Products.objects.all() print(showall) serializer = POLLSerializer(showall,many=True) print(serializer.data) return render(request,'polls/product_list.html',{"data":serializer.data}) below is the insert page where the form <body> <center> <h1>Edit details of Clothes</h1> </center> <center> <form method="POST"> {% csrf_token %} {{data}} <button class="btn btn-success"><a href="{% url 'polls:show' %}" style="color: red;">Go To Home</a></button> </form> </center> </body> the form itself isnt coming,what could the problem be? -
Django 4.0 pyinstaller 5.1 failed to run runserver command throws an error
Trying to package a django 4.0 project to exe using pyinstaller 5.1 and python 3.9 and it was successfully but i ran into a problem that when i run it in cmd with ./manage.exe runserver i get this error Am currently working in a virtual environment and am using windows 10 operating system The project is a basic test project were am using a single app, a few satic files and sqlite 3 as my default database PyInstaller\hooks\rthooks\pyi_rth_django.py", line 69, in _restart_with_reloader return _old_restart_with_reloader(*args) File "django\utils\autoreload.py", line 263, in restart_with_reloader args = get_child_arguments() File "django\utils\autoreload.py", line 250, in get_child_arguments raise RuntimeError('Script %s does not exist.' % py_script) RuntimeError: Script runserver does not exist. [7892] Failed to execute script 'manage' due to unhandled exception! This is my .spec file # -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis( ['manage.py'], pathex=[], binaries=[], datas=[], hiddenimports=[ 'webapp.urls', 'webapp.apps' ], hookspath=[], hooksconfig={}, runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False, ) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE( pyz, a.scripts, [], exclude_binaries=True, name='manage', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, console=True, disable_windowed_traceback=False, argv_emulation=False, target_arch=None, codesign_identity=None, entitlements_file=None, ) coll = COLLECT( exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, upx_exclude=[], name='manage', ) This is urls.py from django.contrib … -
Why I am unable to make dynamic django dependent dropdown?
Hi I am new to django and I am able to make a static html based select dropdown,however I am struggling to find out where I am going wrong in making a dynamic django dependent select dropwdown for 'Categories',,and I have been making a CRUD with Products having categories,sub categories,colors,size below is the code for my Products model: from tkinter import CASCADE from django.db import models from rest_framework import serializers # Create your models here. CATEGORY_CHOICES = [('ninesixwear','9-6WEAR'),('desiswag','DESI SWAG'),('fusionwear','FUSION WEAR'), ('bridalwear','BRIDAL WEAR')] class Products(models.Model): Categories = serializers.ChoiceField(choices = CATEGORY_CHOICES) sub_categories = models.CharField(max_length=15) Colors = models.CharField(max_length=15) Size = models.CharField(max_length=15) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) prod_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) below is the html made static select dropwdown,but I am having trouble converting into dynamic select dropdown ` -
Django: Applying indexes on abstract models so that children have it
Can we apply indexes on abstract models so that all children inherit it? I have an abstract model which feeds other models : from model_utils.models import UUIDModel from django.db import models class TimeStampedUUIDModel(UUIDModel): created_at = models.DateTimeField(auto_now_add=True, db_index=True) updated_at = models.DateTimeField(auto_now=True, db_index=True) class Meta: abstract = True class ModelA(TimeStampedUUIDModel): name_a = models.CharField(max_length=30) class ModelB(ModelA): name_b = models.CharField(max_length=30) And I wanted to add an index on that abstract model so that I have : class Meta: abstract = True indexes = ( BrinIndex(fields=['created_at']), BrinIndex(fields=['updated_at']), ) I have this error: (models.E016) 'indexes' refers to field 'created_at' which is not local to model 'ModelA'. HINT: This issue may be caused by multi-table inheritance. What is the best way to do meta inheritance on such model ? -
How can we modify permissions such that query parameters are taken into consideration in Django
For context, I have been trying to modify the PostPermissions for the method has_object_permission such that users are allowed to make PATCH requests to change the likes of posts made by other users. However, my code does not to seem to work, and I am not sure why. Any help will be greatly appreciated. My code for PostPermissions is as follows: class PostPermissions(permissions.BasePermission): #Allow authenticated users to access endpoint def has_permission(self, request, view): return True if request.user.is_authenticated or request.user.is_superuser else False def has_object_permission(self, request, view, obj): #allow anyone to view posts through safe HTTP request (GET, OPTIONS, HEAD) if request.method in permissions.SAFE_METHODS: return True data = QueryDict(request.body) #allow users to edit the likes and dislikes of other posts if request.method == 'PATCH' and ('likes' in data or 'dislikes' in data): return True #allow users to edit only their own posts through POST requests by checking that the author of the post is the same as the authenticated user #superusers can edit and delete everyone's posts return request.user == obj.name or request.user.is_superuser The error I got in Postman is as follows: -
How to display a ForeignKey's str instead of pk in an update form using CharField
How do I have my Update form display my Foreign Key's str rather than its pk when using CharField? My models class MyUser(AbstractUser): username=models.CharField(max_length=256,unique=True) def __str__(self): return self.username class Device(models.Model): name=models.CharField(max_length=256,unique=True) owner=models.ForeignKey(MyUser,on_delete=models.CASCADE) def __str__(self): return self.name My form """ User puts in a registered username to the owner field and clean_owner gets and saves the user object to owner field. """ class DeviceForm(forms.ModelForm): owner=forms.CharField() class Meta: model=Device fields=['owner','name'] def clean_owner(self): owner=self.cleaned_data['owner'] try: user_object=MyUser.objects.get(username=owner) except MyUser.DoesNotExist as e: raise forms.ValidationError('User does not exist') return user_object My form above works as intended when creating an object. When updating however, the form displays the owner field as the MyUser object's pk, instead of what is specified in the model's __str__ method. Is there a way to have the update form display the owner.username in the owner field instead of owner.pk? I have tried several solutions of overriding the form's __init__ method but so far to no avail. Thanks! -
Django add just the email of the user that created an individual alert
I am trying to add just the email of the user that created an individual alert to an email notification. Status: each individual user has its own dashboard and they should receive a notification when their own crypto value is below the alert. The problem: at the moment all users receive all email notifications, while the correct would be that a user should receive only the email related to their own cryptos. Question: how can i add just the email of the user that created the individual alert? I tried two different approaches: (i) SerializerMethodField() with initial_data, and (ii) i tried using CustomUserSerializer(data=request.data). The first method threw the error AlertsSerializer' object has no attribute 'initial_data', and the second method threw the error NameError: name 'request' is not defined Do you have any suggestion to add the email of the user to their own alerts correctly ? views.py from email import message from rest_framework import generics from rest_framework import status from .serializers import AlertsSerializer, TickerSerializer, UserlistSerializer from users.serializers import CustomUserSerializer from .models import SectionAlerts, Ticker, NewUser import requests import logging from itertools import chain from importlib import reload import sys import csv from django.http import HttpResponse from django.shortcuts import render from … -
Django check user permissions in template
I am using class based view and are using PermissionRequiredMixin to prevent users without permissions from from accessing the page. However, I also want to check for users permission in the Index page before rendering a link to perform some actions. I used the {% if perms.foo %} and {% if perms.foo.add_vote %} as per the Django documentation. However, it works for my superuser 'admin' but do not for another user 'testuser' who had been granted permissions to View Company. I can't figure out what I am missing here. Need some advise. codes in some_index.html # test codes <p><b>{{user.username}}</b> {% if perms.srrp %} have permission to <u>SRRP</u> app {% if perms.srrp.view_company %} and permission to <u>View Company</u> function # <a href=....>View Company</a> {% endif %}</p> {% else %} do not have any permissions in SRRP app</p> {% endif %} in views.py class CompanyListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): permission_required = ('srrp.view_company') model = Company template_name = 'srrp/view_company.html' The result Login as superuser admin admin have permision to SRRP app and permision to View Company function Login as testuser testuser do not have any permissions in SRRP app -
Ajax refresh generated backend image
I am working on an image generator. The user should be able to insert some variables (such as name etc.) and submit the form with a button. The backend generates the image and shows in the frontend. This should be happen with Ajax since I do not want to reload the page. Otherwise all the user inputs are gone, and the user needs to fill out all the fields again. This code below works so far. There is just one problem. After the img is created and shown in the frontend (works perfectly) it does not generate new images when new input is inserted. It should be able to replace the img with the new generated (with new inputs). This is my Django view: def build(request): if request.method == 'POST': name = request.POST.get('name') createIMG(name) context = {'msg': 'Success'} return JsonResponse(context) And this is my html file <form method="POST" id="form-create"> {% csrf_token %} <button type="submit">Create IMG</button> <input type="text" name="name" id="name" placeholder="Name"> </form> <h4></h4> <div class="out-img"></div> This is my Script <script> $(document).on('submit', '#form-create', function (e) { e.preventDefault() $.ajax({ type: 'POST', url: "{% url 'creator:build' %}", data: { name:$('#name').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), }, success: function (data){ if (data.msg === "Success") { $('h4').html('It worked!'); } … -
get user membership in django
I need to get if request user has membership in my site or not but I got an error can any one help me? user memebership model is class UserMembership(models.Model): user = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='user_membership') membership = models.ForeignKey(Membership, on_delete=models.DO_NOTHING, null=True, related_name='membership') def __str__(self): return self.user.email serializer is : class UserMemberShipSerializer(serializers.ModelSerializer): class Meta: model = UserMembership fields = ['id', 'user', 'membership'] and view is class MembershipView(viewsets.ModelViewSet): model = UserMembership serializer_class = UserMemberShipSerializer def get_user_membership(self): user_membership_qs = UserMembership.objects.get(user=self.request.user) print(user_membership_qs) if user_membership_qs.exists(): return user_membership_qs.first() def get_queryset(self): current_membership = self.get_user_membership(self.request) return current_membership and error is in this line current_membership = self.get_user_membership(self.request) the error is 'current_membership = self.get_user_membership(self.request) TypeError: get_user_membership() takes 1 positional argument but 2 were given' -
AttributeError: 'str' object has no attribute 'get' in django
I have an error that the string object has no attribute 'get' Internal Server Error: /get_details/ Traceback (most recent call last): File "D:\aldobi-work-trial\aldobi_env_39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\aldobi-work-trial\aldobi_env_39\lib\site-packages\django\utils\deprecation.py", line 116, in __call__ response = self.process_response(request, response) File "D:\aldobi-work-trial\aldobi_env_39\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'str' object has no attribute 'get' [02/Jul/2022 10:42:23] "GET /get_details/ HTTP/1.1" 500 75100 authorization code generation functionbelow @csrf_exempt @app.route('/get_details') def get_details(request): if request.method == 'POST': scope = "ZohoBooks.fullaccess.all" client_id = "1000.E7K84WA523DY7E2AOIHTQDVU86BSRK" # client_secret = "e965c690e4590ba0b3531fa1ef8d664b796f167e2e" redirect_uri = "https://admin.aldobi.com/code/" access_type = "offline" url = f"https://accounts.zoho.com/oauth/v2/auth?scope={scope}&client_id={client_id}&state=testing&response_type=code&redirect_uri={redirect_uri}&access_type={access_type}".format(scope, client_id, redirect_uri) webbrowser.open(url) return redirect(url_for('/open_page/<string:code>')) print('redirect is processed ') else: return "PLEASE SELECT POST METHOD" print('method is not post') -
How can I add a extra column with django table2?
I'm learning django and how to use django-table2 app. For now I can display my users in a table on my homepage. But I can't find a way to add a column with a delete button for each row. tables.py class UserListTable(tables.Table): class Meta: model = User exclude = ("password", "is_superuser", "is_staff", "is_active", "last_login", "date_joined") attrs = { 'class': 'paleblue', 'th': { 'class': 'TEST', }, } view.py @login_required(login_url="/login") def home(request): table = UserListTable(User.objects.all()) # Update data when they are sorted RequestConfig(request).configure(table) if isInGroup(request, 'Student'): return render(request, 'main/home_student.html') else: return render(request, 'main/home_staff.html', { 'table': table, }) template {% extends 'main/base.html' %} {% block title %} Home page - Staff {% endblock %} {% block content %} // other code here {% load django_tables2 %} {% render_table table %} {% endblock %} Is it even possible ? I did read the documentation but perhaps I missed where is it explained. -
how django paginator work on 3 list on single page?
I have 3 list to be display on a page and need a paginator that works with all 3? is it possible, if yes then how? i am only able to load 1 list at a time. -
how to add a custom button that can used clicked event in django admin.py
I have a model which named Record, the model have the source code info. Now, I want add a button in the admin site. Current django admin.py code like: @admin.register(Record) class ControlRecord(admin.ModelAdmin): list_display = ["file_path", "go_to_src_code", "func_info", "line"] search_fields = ['file_path', 'func_info'] list_filter = ['severity', 'is_misinformation'] actions = [jump_to_src_code] def go_to_src_code(self, obj): return format_html( '<button onclick= "" >Go</button>' ) go_to_src_code.short_description = "GoToSrcCode" I want to specify the specified method after clicking the button, what should i do? -
Cannot push to heroku with cloudinary storing my staticfiles
I am trying to use cloudinary to store my media and static files for my django project. First I changed my settings so that media files are stored on cloudinary and pushed it to heroku and it worked fine except the staticfiles were not loading. So I changed my settings again so that static files are also stored in cloudinary. It works fine locally with DEBUG=False. When I see the page source of my html locally, it is getting the css and javascript files from cloudinary. So, then I tried pushing it to heroku using git push heroku master. But I get the below error in my heroku logs: Step 11/14 : RUN python manage.py collectstatic --noinput ---> Running in 5b062a8f7c52 Traceback (most recent call last): File "/usr/src/app/manage.py", line 22, in <module> main() File "/usr/src/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 161, in handle if self.is_local_storage() and self.storage.location: File "/usr/local/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 215, in is_local_storage return isinstance(self.storage, FileSystemStorage) File "/usr/local/lib/python3.10/site-packages/django/utils/functional.py", line 248, in inner self._setup() File "/usr/local/lib/python3.10/site-packages/django/contrib/staticfiles/storage.py", … -
How can we add Two auto-generated field in one model in Django
I am in need to create two auto generated field: 1st field is ID and another i am taking position that is equivalent to id or we can say it is also auto generated field in the model. here is the code in which i am integrating: class DeviceControlPolicy(models.Model): vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE) id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000) # schedule_id = models.ForeignKey(ScheduleClassificationGroup, on_delete=models.CASCADE, null=True, default=None) usb_storage_device = models.CharField(max_length=10, default="allow") cd_dvd = models.CharField(max_length=10, default="allow") portable = models.CharField(max_length=10, default="allow") wifi = models.CharField(max_length=10, default="allow") bluetooth = models.CharField(max_length=10, default="allow") webcam = models.CharField(max_length=10, default="allow") serial_port = models.CharField(max_length=10, default="allow") usb_port = models.CharField(max_length=10, default="allow") local_printer = models.CharField(max_length=10, default="allow") network_share = models.CharField(max_length=10, default="allow") card_reader = models.CharField(max_length=10, default="allow") unknown_device = models.CharField(max_length=10, default="allow") position = model.[what do i write here to make it auto generated or equal to id] def __str__(self): return self.name please help me out to solve this. -
Django: Multiselect Unexpected behaviour
Here is my Multiselect <div class="form-group"> <label>Multiple select using select 2</label> <select class="js-example-basic-multiple w-100" id='mls' name="resources" multiple="multiple"> <option value="AL">Alabama</option> <option value="WY">Wyoming</option> <option value="AM">America</option> <option value="CA">Canada</option> <option value="RU">Russia</option> </select> </div> Whenever I try to post despite selecting multiple values I still get only one . Here is stacktrace. Variable Value csrfmiddlewaretoken 'aI5tuSxOtxzGOpMDKR4RcH685yWUFpqkgTeBrYVbQ8kN9ODxnPOytllMTAb11Bib' acc_id '1' resources 'AM' I tried with getlist as well still getting single value we all can see single values are passing in request itself. Not sure what might I am doing wrong here . -
How to exclude 'queryset' characters when using django sqlite orm
I want to send mail to many users using django sendmail. I am using orm in sqlite3 to get the list of recipients stored in db. However, the orm result includes 'queryset', so mail cannot be sent Is there a way to exclude 'queryset' from orm results? as-is I want views.py def send_form(request): if request.method == 'POST': selected_target = request.POST['target'] target = contact.objects.filter(target=selected_target).values_list('email') return render(request, 'view/send_form.html', {'target': target}) def send_success(request): if request.method == 'POST': subject = request.POST['subject'] recipient = request.POST['email'] message = request.POST['message'] send_mail( subject, message, recipient, [recipient], fail_silently=False, ) return render(request, 'view/send_success.html') send result