Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
127.0.0.1:8000/admin/ won't load up
Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 4.0 Exception Type: TypeError Exception Value: 'set' object is not reversible Exception Location: C:\Users\User\PycharmProjects\pythonProject2\venv\lib\site-packages\django\urls\resolvers.py, line 494, in _populate Python Executable: C:\Users\User\PycharmProjects\pythonProject2\venv\Scripts\python.exe Python Version: 3.10.0 Python Path: ['C:\Users\User\PycharmProjects\pythonProject2\mywebsite', 'C:\Users\User\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\User\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\User\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\User\AppData\Local\Programs\Python\Python310', 'C:\Users\User\PycharmProjects\pythonProject2\venv', 'C:\Users\User\PycharmProjects\pythonProject2\venv\lib\site-packages'] Server time: Mon, 27 Dec 2021 18:46:36 +0000 -
Django Admin panel refuses Content Security Policy
I am struggling to use django-csp in my admin panel, I can see my frontend with vue3 and vite, you can see my demo site on here. When I try to log in admin I get a black screen and in the console, I see the error below: Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' fonts.googleapis.com ajax.cloudflare.com static.cloudflareinsights.com www.google-analytics.com ssl.google-analytics.com cdn.ampproject.org www.googletagservices.com pagead2.googlesyndication.com". Either the 'unsafe-inline' keyword, a hash ('sha256-Tq5HCCxkFfCSF4NPeTUcXBhJqVIuv2SvsJXpa2ACR2Y='), or a nonce ('nonce-...') is required to enable inline execution. I configured my django-csp in my settings: # default source as self CSP_DEFAULT_SRC = ("'none'",) CSP_INCLUDE_NONCE_IN = ["default-src"] CSP_STYLE_SRC = ("'self'", 'fonts.googleapis.com', "'unsafe-inline'", "'unsafe-eval'", "https") # scripts from our domain and other domains CSP_SCRIPT_SRC = ("'self'", 'fonts.googleapis.com', "ajax.cloudflare.com", "static.cloudflareinsights.com", "www.google-analytics.com", "ssl.google-analytics.com", "cdn.ampproject.org", "www.googletagservices.com", "pagead2.googlesyndication.com") # images from our domain and other domains CSP_IMG_SRC = ("'self'", "www.google-analytics.com", "raw.githubusercontent.com", "googleads.g.doubleclick.net", "mdbootstrap.com") # loading manifest, workers, frames, etc CSP_FONT_SRC = ("'self'", 'fonts.gstatic.com', 'fonts.googleapis.com') Can you help me to fix this? Thanks -
Django - how to validate data from post that is not in a django form?
I am receiving post data from my template but it's being created with js, it is not a django form. I know that if I am posting a field using a django form I can use form.is_valid() or x = form.cleaned_data['field'] but I don't know how to validate/clean my data when not using a django form. The reason that I'm using js for this form/template is to get a specific look that I couldn't do with a standard django template/form. models.py class AssessComment(models.Model): assessment = models.ForeignKey(Assessment, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) comment = models.TextField(blank=True) js snippet // this js is appended to the grade-form element in the template document.getElementById('grade-form').appendChild(table); comment = document.createElement('td'); commentName = "row-" + n + "-comment"; commentText = document.createElement("textarea"); commentText.setAttribute("name", commentName); rowName[n].appendChild(comment); comment.appendChild(commentText); The above js is putting a textarea in a table and giving it the name commentName. The template sends this as a post to my view. I iterate through several rows of n. template div class="form-group"> <form action="" method="post">{% csrf_token %} <div id="grade-form"></div> <!-- js is inserted here --> <div class="form-group"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div> views.py while s < len(cs): comment = "row-" + str(s) + "-comment" form_comment = request.POST[comment] # … -
Django This backend doesn't support absolute paths after integrating aws S3 bucket
I found similar question on stackoverflow on this topic but still now my problems didn't solved. I am facing following problems after integrating aws S3 bucket: problem 1: Image resizing not working after integrating aws S3 bucket. problem 2: getting this error page after image upload NotImplementedError at /blog/edit/hello/ This backend doesn't support absolute paths. here error details of my terminal "C:\Users\Fdg\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\files\storage.py", line 123, in path raise NotImplementedError("This backend doesn't support absolute paths.") NotImplementedError: This backend doesn't support absolute paths. [27/Dec/2021 23:49:44] "POST /blog/edit/hello/ HTTP/1.1" 500 118419 my settings.py AWS_ACCESS_KEY_ID = "my acess key" AWS_SECRET_ACCESS_KEY = "my secret key" AWS_STORAGE_BUCKET_NAME = "my bucket name" AWS_S3_CUSTOM_DOMAIN = 'my aws domain name' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_DEFAULT_ACL = 'public-read' AWS_S3_FILE_OVERWRITE = False AWS_QUERYSTRING_AUTH = False DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_MEDIA = '/media/' AWS_STATIC = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC) MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_MEDIA) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' here is my models.py for upload images: class BlogHeaderImage(models.Model): image = models.ImageField(upload_to='blog/images/',validators=[validate_file_size,FileExtensionValidator( ['png','jpg'] )]) blog = models.ForeignKey(Blog,on_delete=models.CASCADE,related_name="blog_header_image") def save(self,*args,**kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: out_put_size = (300,300) img.thumbnail(out_put_size) img.save(self.image.path) def __str__(self): return str(self.blog) Though I am getting this error but image is uploading on aws … -
Django get count of total quantity in cart
I 'm trying to get the total quantity of the items I have added to cart. e.g. Item id 1 quantity 1 pc Item id 2 quantity 1 pc Item id 3 quantity 4 pcs There are 6 pcs in total in cart. In cart detail page, I could get correct count using this line {{cart.get_total_qty}} This is my cart.py page: class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)]['product'] = product for item in self.cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] item['quantity'] = int(item['quantity']) yield item def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) def get_total_qty(self): return sum(item['quantity'] for item in self.cart.values()) def clear(self): del self.session[settings.CART_SESSION_ID] self.session.modified = True Now I … -
Getting errors after installing Django AllAuth and migrating
Help! I'm getting errors after installing Django AllAuth and migrating! Errors: File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/opt/virtualenvs/python3/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute django.setup() File "/opt/virtualenvs/python3/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/django/apps/registry.py", line 93, in populate raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: auth``` -
Какие поля нужны для хранения счета? [closed]
Нужна модель матча по пинг понгу. Требуется модель, из которой можно будет взять следующие данные: Время | Игрок1 | Игрок2 | Выигранные сеты игрока1 | сеты игрока2 | счет по сетам например 16.01.01 | олег | данил | 3 | 0 | 11:3, 11: 6, 11: 9 пока что модель выглядит так class Game(models.Model): date = models.DateTimeField(auto_now_add=True) player1 = models.CharField() player2 = models.CharField() sets1 = models.IntegerField() sets2 = models.IntegerField() А какие поля нужны для хранения счета? Еще важно, что количество сетов может быть разным, и соответственно количество счетов по сетам тоже. -
How can I limit access to certain urls depending on the logged in user?
first of all I want to clarify that I am new to this, so if I fail in some concepts I apologize in advance. I have configured the django administration panel, with an administrator user and two other users that I need to have different permissions to access certain urls of the web environment. In the home page there are three titles with links to three different sections of the page: SECTION A, SECTION B AND SECTION C. I want to have a user that has access to all the sections of the page and the other user that has access only to two sections. How can I manage that? Another thing I would need is the following: in my configuration, by default, when you launch the web server, the first thing that opens is the django administration portal, but I need that when you log in with a user, access directly to the url that has permissions. Thanks in advance -
Understand the responsibility of each part of django architecture
Im a little confuse about Django responsibility architecture. In my project, i chose work with CBV and built-in urls. In my studies, i understood that the responsibilities are divided into: Model, View, Template where: Model takes care data and DataBase, from docs : "definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing" View takes care about request and response Template is a hight level layer app to show data correct me if not that. Most of my questions are where to put the codes, eg: In my models i use something like: class Product(models.Model): ..."""other fields""" user = models.ForeignKey(User, on_delete=models.CASCADE) product_title = models.CharField(max_length=255, default='product_title') product_title_seo = models.CharField(max_length=255, default='product_title_seo') slug = models.SlugField(max_length=250,unique=True,null=True) def __str__(self): return self.product_title def get_absolute_url(self): return reverse('product_change', kwargs={'slug': self.slug, 'pk': self.pk}) def save(self, *args, **kwargs): self.product_title_seo = slugify(self.product_goal + " " + self.product_type + " " + self.product_district) self.product_title = slugify(self.product_title) if not self.slug: self.slug = self.product_title_seo return super().save(*args, **kwargs) So as we can see i have 3 methods inside my model class, but i need some treatment for the majority of fields which would represent a considerable increase in methods. This approach is correct, a lot of … -
Is there any specific condition, When to use APIView and when to use ViewSets in Django
IN Serialezers.py file I have seen, that the user is using APIView in one and Modelviewset in few. from django.shortcuts import render from rest_framework import serializers from rest_framework.response import Response from rest_framework.utils import serializer_helpers from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from .models import * from rest_framework import status from .serializers import * class ProductList(APIView): def get(self, request): products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) def post(self, request): serializer = ProductSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class CategoryViewSet(ModelViewSet): serialzer_class = CategorySerializer queryset = Category.objects.all() -
Rounding up a decimal not working properly in python(or django)
I was trying to round up a decimal with the code I found below, but it doesn't seem to work properly in python(django). Here is the code: import math def round_up(n, decimals=0): multiplier = 10 ** decimals return math.ceil(n * multiplier) / multiplier Here are some of the results I get when I run the function: print(round_up(20.232, 2)) print(round_up(20.0, 2)) print(round_up(20.4, 2)) 20.24 20.0 20.4 However, for some reason, I get a weird value when I input 80.4. I am getting 80.41 instead of 80.4: print(round_up(80.4, 2)) 80.41 Is there any other way I can round up decimals in python(django)? I have gotten this off the internet, so there might be some other problems other than the one I mentioned above(inputting 80.4). Basically, I just want to round up a decimal to the second decimal point like above(but of course rounding up 80.4 or 20.3 would just be 80.4 and 20.3 respectively). Thank you, and please leave any questions you have. -
How to send file from system storage django?
I want to send file from my FileSystemStorage as response of a POST request, but every time i getting my error handler triggered. Why? def get_frame(request): frame_number = request.POST['frame_number'] filename = request.POST['filename'] fss = FileSystemStorage() # creating name of file i need name = f'frame_{frame_number}_{filename.replace(".mp4", "")}.png' # execute file path img = fss.path(name) return FileResponse(open(img, 'rb')) script.js for(let i=0; i<=frames_needed; i++) { let frame_number = fps * i // making POST request for 1 frame let img = get_each_frame(frame_number, filename) img.done(function(response) { console.log(response) }) // getting this handler triggered img.fail(function(error) { console.log(error, 'error') }) } get_each_frame function function get_each_frame(frame_number, filename) { let request = $.ajax({ type: "POST", url: "get_frame", data: { 'frame_number': frame_number, 'filename': filename, 'csrfmiddlewaretoken': $('[name=csrfmiddlewaretoken]').val(), }, dataType: "json", }); return request } -
Django Models return fileds as columns for django admin
I looked a lot but I couldn't find a way to return my model to django admin with the columns not only the model name: What I wish to accomplish from my model is to have the fields represent as columns in django admin, such as it is in users: I have a model called Products: from django.db import models # Create your models here. class Product(models.Model): title = models.CharField(max_length=30, null=False, blank=False) price = models.FloatField(null=False, blank=False) description = models.CharField(max_length=250, null=False, blank=False) longDescription = models.TextField(max_length=900, null=True, blank=True) def __str__(self): return self.title It's register on admin site so I can see it as: I'm looking for a way to have my products listed as users, with the id, price, description as columns... Is it possible? Thanks in advance! -
get_extra_restriction() missing 1 required positional argument: 'related_alias' error django
I deployed my django site on heroku and when i run my url which uses django taggit in it error shows up. I am using django taggit for meta keys to find related blogs. -
how to enable/disable buttons in HTML jscript
I am trying to enable buttons on a web page using a js funtion for a django project. I am new this so please be cool :-) <input onclick="change(id)" type="button" value="Modify" id="11" class="btn btn-info"></input> <div class="btn-group" role="group" aria-label="Basic example"> <button type="button" class="btn btn-secondary" disabled="false" id="edit_11">Edit</button> <button type="button" class="btn btn-secondary" disabled="false" id="delete_11">Delete</button> </div> <br></br> <input onclick="change(id)" type="button" value="Modify" id="22" class="btn btn-info">/input> <div class="btn-group" role="group" aria-label="Basic example"> <button type="button" class="btn btn-secondary" disabled="false" id="edit_12">Edit</button> <button type="button" class="btn btn-secondary" disabled="false" id="delete_12">Delete</button> </div> <br></br> <script> function change(id) { var elem = document.getElementById(id); let newID = "edit_".concat(id) if (elem.value=="Undo") { elem.value = "Modify"; choiceEdit = document.getElementsByName(newID) choiceEdit.disabled = false } else { elem.value = "Undo"; choiceEdit = document.getElementsByName(newID) choiceEdit.disabled = true } } </script> What I would like to happen is for the name of the main button change from "Modify" to "Undo", which happens. But I'd also like for the two related Edit and Delete buttons to be enabled so as to press them. Anyone can tell me what I am doing wrong? Thanks! -
Use Django template tags with Alpine.js x-text
I'm using Alpine.js in my Django templates and so far I've been quite happy with the results. However, I would like to use Django template tags for instance floatformat on a value computed by Alpine.js. For now, I am formatting the number directly in Alpine.js and my code look like this: <div x-data="{rawNumber: 1.23456, get formattedNumber() { return Math.round(rawNumber + Number.EPSILON) * 100) / 100 } }"> My formatted number is <span x-text="formatNumber"></span> </div> What I'm looking for is a way to use Django template tags on the value computed by Alpine.js. A very naïve implementation (which of course generates error) would look like this: <div x-data="{rawNumber: 1.23456}"> My formatted number is {{ <span x-text="rawNumber"></span>|floatformat:2 }} </div> -
By using Django and allauth, how can we stop authentication of a user with same email address for two social accounts?
I am new to Django and was trying to implement the below-mentioned scenario which is as such: I have a google account as well as a facebook account with the same email address by using django-allauth. So if I am already logged in using google/facebook account and try to login from facebook/google i.e. the other social account in the same session, I should show that the user has already been logged in with this email ID. My approach is to set email and provider id in the session request and manipulate it in the pre_social_login signal in my social adapter. So far I have defined my middleware as such: middleware.py from django.contrib import messages class SimpleMiddleware(object): def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. if request.path == '/accounts/login/' and request.method == 'GET' and not request.user.is_authenticated: if 'email' not in request.session: request.session['email'] = '' request.session['provider']='' request.session['is_active']='False' response = self.get_response(request) return response my_adapter.py from allauth import account from allauth.socialaccount.adapter import DefaultSocialAccountAdapter class MySocialAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): if request.session['email']=='' and request.session['provider']=='': request.session['email']=sociallogin.account.extra_data['email'] request.request.session['provider']=sociallogin.account.provider request.session['is_active']=False response = self.get_response(request) elif request.session['email']==sociallogin.account.extra_data['email'] … -
How to check file arrived in javascript and HttpResponse object django
Hi everyone and merry christmas Actually my code is working fine, but i can't figure out how to catch a file arrives message in javascript I'm working widh django 2.1 template: ... <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> ... <input type="file" id="prd" name="prd" required> </div> ... <input id="btn_ini" type="submit" name="submit" value="Init process"> </form> ... <script type="text/javascript"> document.addEventListener('???', function(){ // I wish indicate to the user that the process is runnning and don't close the page. // at the moment the logic is working as spected but I can't achieve how to check in javascript when file arrives. }) </script> </body> </html> #views def add_destination(request): ... if request.method == 'POST': ... return handle_uploaded_file(prd) return render(request, 'add-destination.html') def handle_uploaded_file(f) ... file = # processing file ... with open(file, 'rb') as f: file_data = f.read() response = HttpResponse( file_data, content_type='application/force-dowload') response['Content-Disposition'] = 'attachment; filename="proc_{}"'.format(incoming_file_name) return response return None -
Heroku Django Virtual Environment source code modification
I managed to deploy my django app (with mongodb as database) on heroku. But I need to modify some source code in django package in the virtual environment. How can I access to virtual environment created by heroku from requirements.txt ? Or maybe how can I upload directly the virtual environment to heroku and make sure that my GIT django app is working on it? thank you -
Getting "This Field is Required" line in my output of django template
As you can see in this picture, every field is having "This field is required" line which i do not want to print there. Can someone help? Picture.jpg -
Permission_classes([IsAdminUser]) is not working
My function based view has a permission class IsAdminUser, but any user can get the request, please explain where is mistake. from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated, IsAdminUser @api_view(['GET']) @permission_classes([IsAdminUser]) def getUsers(request): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data) -
Crop mongo document with filter
The project stack is Django + MongoDB (djongo library). I have order table with data structure like this { name:"Help", price:123, products:[ { "_id":"some id", "organization":{ "id":1 } }, { "_id":"some id2", "organization":{ "id":2 } } ] } How can I get list order which has item in 'products' set where organization id field is equal 1? When I will get this list how can I delete products set items where organization id field isn't equal 1? So I should get something like this (Price field shouldn't be too) { name:"Help", products:[ { "_id":"some id", "organization":{ "id":1 } } ] } -
TypeError: Field 'facebook_reactions' expected a number but got <class 'rest_framework.fields.IntegerField'>
I am facing an issue when testing my EventViewSet. I get the following error TypeError: Field 'facebook_reactions' expected a number but got <class 'rest_framework.fields.IntegerField'>. This is the test I ran: class EventViewSetTest(BaseTestCase): def test_event_created(self): event_data = { "url": "www.example.com", "tweet_text": "Event successful", "facebook_reactions": 2, } response = self.client.post("/api/events/", event_data) self.assertEqual(status.HTTP_201_CREATED,response.status_code) Here is my views.py: class EventViewSet(ModelViewSet): queryset = Event.objects.all() def get_serializer_class(self): if self.action == "create": return serializers.EventCreateSerializer return serializers.EventSerializer def perform_create(self, serializer): Event.objects.create( url=Link.objects.get_or_create(url=serializer.url)[0], tweet_text=serializer.tweet_text, facebook_reactions=serializer.facebook_reactions, ) Here is my serializers.py: class EventCreateSerializer(serializers.Serializer): url = serializers.URLField tweet_text = serializers.CharField facebook_reactions = serializers.IntegerField class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ["url", "tweet_text", "facebook_reactions"] Help would be much appreciated. Thank you! -
Error: django.core.exceptions.ImproperlyConfigured: NewsCreateVive is missing a QuerySet
I'm just trying to add the simplest form to my website. I'm making an example from a book I get an error: Internal Server Error: /newsboard/add/ Traceback (most recent call last): File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\views\generic\base.py", line 101, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\views\generic\edit.py", line 170, in get return super().get(request, *args, **kwargs) File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\views\generic\edit.py", line 135, in get return self.render_to_response(self.get_context_data()) File "C:\Users\Pavel\Desktop\DjangoWEBIRonBull\IRonBULL\newsboard\views.py", line 14, in get_context_data context = super().get_context_data(**kwargs) File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\views\generic\edit.py", line 68, in get_context_data kwargs['form'] = self.get_form() File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\views\generic\edit.py", line 34, in get_form form_class = self.get_form_class() File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\views\generic\edit.py", line 95, in get_form_class model = self.get_queryset().model File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\views\generic\detail.py", line 69, in get_queryset raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: NewsCreateVive is missing a QuerySet. Define NewsCreateVive.model, NewsCreateVive.queryset, or override NewsCr eateVive.get_queryset(). [27/Dec/2021 19:54:41] "GET /newsboard/add/ HTTP/1.1" 500 98314 At the same time, this is not related to the solutions that I saw when I was looking for an answer to my question. (problem with the file urls.py and using the name of its class inherited from CreateVive) My code: urls.py: from django.urls import path from … -
Add a custom query-function to django admin
I created a custom function. I added to the Django admin panel for a certain model. Now, it can be used and applied to the desired queryset of elements that are stored in this model. I have, let's say, a problem. This model contains a huge quantity of data. I need a queryset only for a certain quantity of those that have a particular field that is not Null (Hence,it contains data). I would like to know if it is possible to create a function for the admin panel that allows for checking all the fields that respect some conditions. In my example, those that have that field that is not Null. I could do the job by simply using either a script or opening the shell. But I would like to try something new. If you have any idea, Thank you!