Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django "render" is not accessed Pylance
i got this problem after downloading django and creating an app, in the file "views.py" the import "from django.shortcuts import render" says django "render" is not accessed Pylance, and my index(request) function has this message "request" is not accessed Pylance, i have downloaded it correctly and reinstalled but still don't working. my code with the message It's not a sintax error -
How to download image or files from Django model
I'm kinda new to python and I'm creating a website that users can buy Hi-Res images and now I'm looking for a way to let user to download the images that they've bought, from the Django model, Here is my pic model: class Pic(models.Model): name = models.CharField(max_length = 60, blank = False) description_sizes = models.TextField(blank = False, name = 'des_sizes', max_length = 360) captured_time = models.DateField(blank = False) price = models.IntegerField(blank = False) preview = models.ImageField(upload_to = f'static/post/preview/', null = False, blank = False) tags = models.CharField(max_length = 1000, blank = False) image_files = models.FileField(upload_to ='posts/ogFiles', null = True, blank = False) My views.py : def singlePostView(request, pic_id = None): pic = Pic.objects.get(id = pic_id) print(pic) context = { 'pic':pic, } return render(request,"post/single_post_view.html", context) I'm looking for way to make a button or link to download the image_file from pic model in the single view, and I've been searching for this for couple of days now and I've just came across these : xsendfile module or using serve like this : <a href="/project/download"> Download Document </a> and in urls.py: url(r'^download/(?P<path>.*)$', serve, {'document root': settings.MEDIA_ROOT}), well for xsendfile module it's not really an efficient way bc was originally designed for Apache … -
HTML tags are showing up in browser when rendering a django formset (template)
I'm learning django and I have an issue when rendering out a formset. I have a modelform and created a modelformset_factory from it. When I'm rendering out the template html tag are showing up on the webpage(UI). In the html every tag is closed accordingly. Can you help me how can I solve this problem? Thank you. My template: {% for form in test_formset %} {% csrf_token %} <td> <input class="form-control" type="text" value="{{ form.name }}" name="name_{{ form.id | default:'' }}" /> </td> {% endfor %} {{ test_formset.management_form }} Attached you can see an image how it appears in UI. image here -
Am I missing something in my urlpatterns?
I'm trying to create a simple update function for my recipes, and i'm having some trouble with my urlpatterns. This is my desired url path, but I keep getting an 404 (Page not found) error. path('update-recipe/<slug:recipe_slug>/', views.update_recipe, name='update_recipe'), my views.py file is like this. def update_recipe(request, recipe_slug): form = RecipeForm() return render(request, 'recipes/update_recipe.html', {'form': form}) if i change my urlpattern to the following, everything seems to work correctly. But that isnt what I'm trying to achieve. path('<slug:recipe_slug>/', views.update_recipe, name='update_recipe'), The output with the above url. I dont seem to understand what I'm doing wrong, I've tried following videos to the dot as well, but i get the same result. -
django formset.is_valid() return false
while working on django inline formset formset.is_valid() code is not working properly models.py class product_list(models.Model): date=models.DateTimeField(auto_now_add=True,null=True) deal=models.ForeignKey(dealForm, null=True, blank=True , on_delete=models.CASCADE) pro_name=models.ForeignKey(wareForm, null=True, on_delete=models.CASCADE) pro_quantity=models.IntegerField() def __str__(self): return self.name in views.py file formset.is_valid() is return false. i think my code have problem in defining Delivery Formset data but still trying to figure out what's wrong in this code also not show deal field in template views.py def myproduct(request, pk): x=wareForm.objects.all() DeliveryFormSet=inlineformset_factory(dealForm, product_list, fields=('deal','pro_name','pro_quantity'), extra=len(x), can_delete=False) dealer=dealForm.objects.get(id=pk) formset=DeliveryFormSet(queryset= product_list.objects.none() , instance=dealer) #date=datetime.datetime.now().strftime("%d-%m-%y") if request.method == 'POST': formset=DeliveryFormSet(request.POST,instance=dealer) if formset.is_valid(): for f in formset: print ('testing') return HttpResponseRedirect('delivery.html') else: formset.errors context={'name':'Product list','formset':formset,'dealer':dealer} return render(request, 'product.html',context)` template {% extends "base.html" %} {% block content %} <div class=container> <div style="text-align: center;"> <h1>Dealer Name: {{dealer.proprietor_name}}</h1> </div> <div> <form action="" method="post"> {% csrf_token %} {{form.management_form}} {% for field in formset %} {{field}} <hr> {% endfor %} <input type="submit" value="Submit" class="btn btn-primary"> </form> </div> </div> {% endblock %} -
Static files are not loading in Django
Why I am receiving files can't be found error while loading all the static files even after setting everything correctly. ERROR CODE: Admin Section - settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '') - 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('Welcome.urls')), path('auth/', include('Authentication.urls')), path('ad/', include('Ads.urls')), path('user/', include('UserDashboard.urls')), path('admin/', include('AdminDashboard.urls')), ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Apps Section - template <link href="{% static 'css/user/style.css' %}" rel="stylesheet"> - Folder Structure -
Django query filter by another dataset
I have 2 User models: User: Default user model: Account: Custom User model, which is an extension of the defualt user model, as I wanted to add a custom field to it called 'Status'. The problem is that I wanted to filter the data based on the current User, so id usually do something like: Account.objects.filter(usernmae = User).values_list('status', flat=True) The problem is that the Account dataset doesnt have the username but they both have the same ID. I was thinking of doing something like this: Status = Account.objects.filter(user_id=User.objects.filter(username = user).values_list('id', flat=True)).values_list('status', flat=True) But then i get the following error: I imagine there is a way better way of doing it, if yall could help me out. -
How to go 2 layers deep reverse relations inside django models?
I'm using a single User model for authentication and creating multiple "type" accounts using the User model. Every type has a different dashboard so different things to show. Organization -> Teacher -> Student Q - I want to list the teachers and their corresponding students when inside a organization account ? It is a listView so I want to know how would I use revere relations to list all the students under specific teachers from an Organization account ? class User(AbstractUser): ... class Organization(models.Model): user_id = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='superAdmin') ... class Teacher(models.Model): user_id = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='faculty') super_admin_id = models.ForeignKey( SuperAdmin, on_delete=models.CASCADE, related_name='faculty') ... class Student(models.Model): user_id = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user') faculty_id = models.ForeignKey( Faculty, on_delete=models.CASCADE, related_name='student') ... If there's any advice on how I can improve the existing model schema, I'd like to know that as well. -
How to show row numbers in django admin listview using the frontend
I wanted to show row number in django admin listview as in the image tried doing it in the admin.py with the following code in different modeladmins: indexCnt = 0 def index_counter(self, obj): count = Basic_inspection.objects.all().count() if self.indexCnt < count: self.indexCnt += 1 else: self.indexCnt = 1 return self.indexCnt But there are problems with this approach, it gets disordered when changing the list page, changing the "sort by" or even when multiple requests to the site. How can I show row numbers in listview using the templates? -
value too long for type character varying(100) in django
i am trying to add an item from admin panel but when i click to save then it throws me above-mentioned error and i don't have any slug field in my model here is the trace back of that error do i have to paste the model or you got the issue Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (value too long for type character varying(100) ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 232, in inner return view(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1657, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1540, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1586, in _changeform_view self.save_model(request, new_object, form, not add) File … -
cPanel Django Deploy: Passengerfile.json' for reading: Permission denied (errno=13)
I am trying to deploy my first Django application via my GoDaddy cPanel. I created my application in a virtual environment, but I'm stuck. I installed django then create wsgi file also. but now when I run the site it shows me this: Passenger error #2 An error occurred while trying to access '/home/u4sgzlaz0pwz/repositories/rentaltake/Passengerfile.json': Error opening '/home/u4sgzlaz0pwz/repositories/rentaltake/Passengerfile.json' for reading: Permission denied (errno=13) Apache doesn't have read permissions to that file. Please fix the relevant file permissions. -
Html tags are displayed on webpage, after rendering django template
{% for neighborhood in neighborhoods_formset %} {% csrf_token %} <td> <input class="form-control" type="text" value="{{ neighborhood.name }}" name="name_{{ neighborhood.id | default:'' }}" /> </td> {% endfor %} {{ neighborhoods_formset.management_form }} I used modelfomset_factory to create a formset, but I have this issue when trying to render it. Here you can see how it appears -
Django Custom Model Data Field Is Using Wrong Function
Here is model.py: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import PermissionsMixin from django.core import signing from django.db import models class EncryptedApiField(models.TextField): def __init__(self, *args, **kwargs): super(EncryptedApiField, self).__init__(*args, **kwargs) def get_db_prep_save(self, value, connection): value = super().get_db_prep_value(value, connection) if value is None: return value print('get_db_prep_save') return ((signing.dumps(str(value))).encode('utf-8')).decode('utf-8') def to_python(self, value): if value is None: return value return signing.loads(value) def from_db_value(self, value, *args, **kwargs): return self.to_python(value) class CustomAccountManager(BaseUserManager): def create_superuser(self, email, username, first_name, password, **other_fields): return self.create_user(email, username, first_name, password, **other_fields) def create_user(self, email, username, first_name, password, **other_fields): email = self.normalize_email(email) user = self.model(email=email, username=username, first_name=first_name, **other_fields) user.set_password(password) user.save() return user class NewUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) username = models.CharField(max_length=255, unique=True) email = models.CharField(max_length=255, unique=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_subscribed = models.BooleanField(default=False) subscription_level = models.IntegerField(default=0) test = EncryptedApiField(blank=True) objects = CustomAccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['test', 'email', 'first_name', 'last_name'] def __str__(self): return self.username I'm trying to create a custom data field where the data is automatically encrypted/decrypted the problem is when I createsuperuser the EncryptedApiField class runs to_python instead of get_db_prep_save thus I'm getting django.core.signing.BadSignature: No ":" found in value error I'm also not getting print('get_db_prep_save') in the terminal but a print in to_python would work … -
getting error when try to run "rasa x" in terminal using anaconda3 with python 3.7.0
(rasa_conda_env) C:\Users\Admin\Desktop\rasa_conda>rasa x Starting Rasa X in local mode... 🚀 Traceback (most recent call last): File "C:\Users\Admin\anaconda3\envs\rasa_conda_env\lib\site-packages\rasa\cli\x.py", line 502, in run_locally domain_path=domain_path, File "C:\Users\Admin\anaconda3\envs\rasa_conda_env\lib\site-packages\rasax\community\local.py", line 226, in main rasax.community.jwt.initialise_jwt_keys() File "C:\Users\Admin\anaconda3\envs\rasa_conda_env\lib\site-packages\rasax\community\jwt.py", line 68, in initialise_jwt_keys private_key, public_key = cryptography.generate_rsa_key_pair() File "C:\Users\Admin\anaconda3\envs\rasa_conda_env\lib\site-packages\rasax\community\cryptography.py", line 28, in generate_rsa_key_pair backend=default_backend(), File "C:\Users\Admin\anaconda3\envs\rasa_conda_env\lib\site-packages\cryptography\hazmat\backends_init_.py", line 14, in default_backend from cryptography.hazmat.backends.openssl.backend import backend File "C:\Users\Admin\anaconda3\envs\rasa_conda_env\lib\site-packages\cryptography\hazmat\backends\openssl_init_.py", line 6, in from cryptography.hazmat.backends.openssl.backend import backend File "C:\Users\Admin\anaconda3\envs\rasa_conda_env\lib\site-packages\cryptography\hazmat\backends\openssl\backend.py", line 113, in from cryptography.hazmat.bindings.openssl import binding File "C:\Users\Admin\anaconda3\envs\rasa_conda_env\lib\site-packages\cryptography\hazmat\bindings\openssl\binding.py", line 14, in from cryptography.hazmat.bindings._openssl import ffi, lib ImportError: DLL load failed: The specified procedure could not be found. Sorry, something went wrong (see error above). Make sure to start Rasa X with valid data and valid domain and config files. Please, also check any warnings that popped up. If you need help fixing the issue visit our forum: https://forum.rasa.com/. -
Posts which are not liked by user
I am building a Blog App and I am trying to show posts which are not liked by request.user, I have tried :- from django.db.models import Exists checkIt = BlogPost.objects.annotate(is_liked=Exists( Like.objects.filter(user=request.user))) But it is showing all the posts. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) blog = models.ForeignKey(BlogPost, on_delete=models.CASCADE) views.py def unliked_posts(request): posts = BlogPost.objects.filter(like__user=request.user).exclude(like__user=request.user) context = {'posts':posts} return render(request, 'unliked_posts.html', context) I have tried many time but it didn't worked for me. I will really appreciate your Help. Thank You -
Django DRF - Nested serializers for OneToOne related models results in KeyError when retrieving data objects
Background I have an OneToOne relation between a type of user (UsertypeA) and my custom base user (UserProfile). However, there is an issue when hitting the API endpoint to retrieve all objects of UsertypeA, I keep getting "Got KeyError when attempting to get a value for field 'user' on serializer UserTypeASerializer. The serializer field might be named incorrectly and not match any attribute or key on the 'dict' instance. Original exception text was: 'usertypeA'." I tried and follow the Django-OneToOne-Relations and DRF-nested-serializers docs as much as I can, but still cannot find the issue of the logic below, and why my UserTypeA.user attribute is not getting serialized UserProfile: # models.py class UserProfile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=150, unique=True) ... # serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: fields = ('email', 'username', 'first_name', 'last_name', ...) model = UserProfile def create(self, validated_data): return UserProfile.objects.create_user(validated_data) def update(self, instance, validated_data): return UserProfile.objects.update_user(instance, validated_data) UserTypeA # models.py class UserTypeA(models.Model): usertypeA_uuid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField( UserProfile, on_delete=models.CASCADE, related_name='usertypeA', related_query_name='usertypeA') ... @property def username(self): return self.user.username def __str__(self): return str(self.usertypeA_uuid) # serializers.py class UserTypeASerializer(serializers.ModelSerializer): user = UserSerializer(required=True, source='usertypeA') class Meta: fields = ('usertypeA_uuid', 'user', 'membership_type' ...) model = UsertypeA depth = 1 def … -
Custom Primary Key in Django
so I am creating a project called an "Electronic Reference Library" (ERL). I am using Django 3.2 to create this app and here is a model of the Resource Table. class Resource (models.Model): resource_id = models.CharField(primary_key=True, max_length=20) type = models.CharField(choices=RESOURCETYPE, default="WebLink", max_length=10) link = models.URLField() subject = models.ForeignKey(YearGroupSubject, on_delete=models.CASCADE) topic = models.CharField(max_length=50) description = models.TextField() unit_no = models.CharField(max_length=10) search_query = models.CharField(max_length=300) status = models.CharField(choices=STATUS, default="Pending", max_length=30) posted_by = models.ForeignKey(ProfileStaff) posted = models.DateTimeField(auto_now=True) approved_time = models.DateTimeField(null=True, blank=True) views = models.PositiveIntegerField(default=0) So in this case my client wanted a custom Primary Key, where the format has to be something like MATH-YYMMDD-HHMMSS-00. Where MATH can be replaced by the primary key of the YearGroupSubject table which is a 4 letter string. Where YYMMDD-HHMMSS is replaced by the current date and time. Replacing the 00 with any random integer (can even be 5 integers long, not a worry). But I am not aware of how to have a custom made primary key, which is automatically generated by Django. Is this possible? If not is there any other better alternative? Any help would be greatly appreciated. Thanks! -
Django Models : How to update value if case matches else keep the current value
I want to perform an update operation on a Django queryset conditionally such that the value of an attribute is updated only when it matches a condition otherwise keep the value it is currently having. I know that conditional updates in django are performed using Case, When, then, default but not getting how to keep the existing value for the default case. I tried leaving default from the query but then it throws an error. I want something like the following. Say there are 4 types of schemes: PRO, REGULAR, HOME, FREE. Customer.objects.filter(age__lte=18)\ .update(type=Case(When(type=HOME, then=FREE), default=<keep current value>), subscribed=False) -
How to pass concatenated functions as a argument in django model method
I am trying to pass timezone.now() + timedelta(days=-2) and timezone.now() as arguments in django model method but am getting def performance(user, timezone.now() + timedelta(days=-2), timezone.now()): ^ SyntaxError: invalid syntax I know the error is as a result of the concatenation but I dont know how to solve this problem. class User(AbstractUser): ......................... fields ......................... def get_performance(self, timezone.now() + timedelta(days=-2), timezone.now()): actual = Sum("scores", filter=Q(status="completed")) q = self.taskassignt.filter( due__gte=timezone.now() + timedelta(days=-2), due__lt=timezone.now() ).annotate(actual=actual, total=Sum("scores")) return (q[0].actual / q[0].total) * 100 -
Mulitple Django Projects as PWAs
I read this question: Django multiple Project using same database tables I am developing a PWA using Python/Django, but I thought, to help with authentication and authorization, I should have two versions, since I have one admin (owner). I am developing a fitness app. The owner (my client) can add/edit/update etc exercises, create workouts with these exercises, add new clients, assigned workouts to clients, etc The Client version, (my client's clients) will be able to complete registration, view workouts, view workouts by exercises, rate workouts. Should I even do this? Can I do this? If so, do I still need to create models in the client version? How would I even access these tables? Thank you for your suggestions. -
Image doesn't render from MySql database in my webpage
I have a database and table where i have store some info about some automobiles. The problem here is all the information saved in the database (through modelform) shows up in output page except the image. I get b'' in column of image. However, if i add the models from my admin site, i get b'Image_Name' in the image column but not image. Opps! I don't have enough points to paste the picture here! -
Views are different but rendering same template
i want to use slug field in both url which is path('<slug:title>/',views.news_read,name="news_read"), path('<slug:title>/',views.movie_read,name="movie_read"), but both the url picking same template instead of their template i am trying to create blog site i don't understand both the url are uniques so why django is picking wrong template my views for both the url def movie_read(request, title): movie = Movie.objects.filter(urltitle=title) if request.method == 'POST': form = Commentform(request.POST) if form.is_valid(): form.save() messages.success(request, 'Thank You For Your Comment') else: form = Commentform() return render(request,'movie_read.html',{'movie':movie,'form':form}) def news_read(request, title): news = News.objects.filter(urltitle=title) if request.method == 'POST': form = Commentform(request.POST) if form.is_valid(): form.save() messages.success(request, 'Thank You For Your Comment') else: form = Commentform() return render(request,'news_read.html',{'news':news,'form':form}) but i when do some change like this it work path('<slug:title>/news',views.news_read,name="news_read"), path('<slug:title>/movie',views.movie_read,name="movie_read"), but this doesn't look good any idea what to do solve the issue -
Django filter module: lookup expression (year) does not return the desired queryset
I am using the django-filter module. I would like to get all objects where the year is 2011 or greater. this is my setup ... Actual behaviour: When I enter a year, then I get the error message: "Enter a valid date." and the queryset is unchanged. I tried entering a date instead of the year, but then the whole page fails with the error message Field 'None' expected a number but got datetime.date(2011, 1, 1). The model: class BaseInvoice(models.Model): id = ShortUUIDField(primary_key=True) invoive_number = models.CharField(max_length=50) invoicing_party_ID = models.ForeignKey(InvoicingParty, on_delete=models.CASCADE) invoice_type = models.CharField( max_length=2, choices=invoice_type, default='IN' ) realestate_id = models.ForeignKey(RealEstate, on_delete=models.CASCADE) user_group = models.ForeignKey(Group, on_delete=models.CASCADE) year_of_contribution = models.DateField(auto_now=False, auto_now_add=False) start_of_period = models.DateField(auto_now=False, auto_now_add=False) end_of_period = models.DateField(auto_now=False, auto_now_add=False) interval = models.ForeignKey(Interval, on_delete=models.CASCADE, default=0) currency = models.ForeignKey(Currency, on_delete=models.CASCADE, default='EUR') class Meta: abstract = True class RealEstateTax(BaseInvoice): realestate_tax = models.DecimalField(max_digits=20, decimal_places=2) The Filter import django_filters from django_filters import DateFilter from .models import * class InvoiceFilter(django_filters.FilterSet): billing_year = DateFilter( label='Abrechnungsjahr', field_name='start_of_period', lookup_expr='year__gt' ) class Meta: model = RealEstateTax fields = ['realestate_id', 'billing_year'] The view from realestate.models import RealEstate from django.shortcuts import render from django.http import HttpResponse from .models import * from .filters import InvoiceFilter from django.db.models import Sum def utilities_bill(request): realestate_tax = RealEstateTax.objects.all() insurance_invoice … -
Heroku returns desc="No web processes running" while running Django even with a Procfile?
Ran into an issue with Django returning at=error code=H14 desc="No web processes running" method=GET path="/set-crf/" host=appxxxx.herokuapp.com request_id=8c8ded0a-5470-46c3-b371-29602549d533 fwd="100.38.206.95" dyno= connect= service= status=503 bytes= protocol=https while trying to connect to the app. After adding a Procfile, importing django-heroku and setting up requirements.txt, nothing seems to work. Here's what I have so far: Relevant Code Procfile: web: gunicorn rpa_django.wsgi settings.py: import django_heroku from pathlib import Path from corsheaders.defaults import default_headers import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'pc_algo', ] MIDDLEWARE = [ ..., "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", ..., 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] ROOT_URLCONF = 'rpa_django.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'rpa_django.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } … -
Querying Reverse ManyToMany Relationship in Django
I have a category Model and a Product Model in my django application... the product model has a many2many field pointing to the category model... and the product model has a created field to denote when it was created. how do i filter the categories model based on the created field of the product?