Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter some items in a manytomany field in Django
I am trying to make an announcement system in my application whereby the Dean can create an announcement and selects the student he is sending them to. I will like to get a way to be able to filter only the specific student announcement(s) on his/her page. models.py class Announcement_by_dean(models.Model): student_id = models.ManyToManyField(add_students_by_manager) message = models.TextField() sent_date = models.DateField(default=datetime.now(), blank=True) updated_date = models.DateField(auto_now=True, blank=True) def __str__(self): return self.id class add_students_by_manager(models.Model): manager_ID = models.ForeignKey(Manager_login_information, on_delete=models.CASCADE) student_ID = models.CharField(max_length=200) student_name = models.CharField(max_length=200) phone_number = models.CharField(max_length=200) address = models.CharField(max_length=200) dob = models.CharField(max_length=200) major = models.CharField(max_length=200) password = models.CharField(max_length=200) def __str__(self): return self.student_name views.py def student_course_list(request): stu_course_id = request.POST.get('stu_course_id') my_announcement = Announcement_by_dean.objects.filter(student_id=request.user.id).order_by('-sent_date') print(my_announcement) context = {"my_announcement":my_announcement} return render(request, "student_course_list.html", context) -
Importing from "django.(any module)" gives me this warning : could not be resolved from sourcePylance (reportMissingModuleSource)
I have just created a Django project in virtual environment and I'm getting this error or warning I'm not quite sure : (module) django Import "django.contrib" could not be resolved from sourcePylance(reportMissingModuleSource) In every line that has import from django . I have searched for this problem and I have tried these so far : 1 - editing Settings.JSON file in VScode by adding : "python.pythonPath": "C:/Users/abdur/dev/cfehome/django_project/Scripts/python.exe", Which is the python.exe location in my virtual environment 2 - I have selected Python Interpreter to the one that is inside the virtual environment like this picture : I have tried the other choice too but didn't work as well . however when I run python manage.py runserver It works without giving me any errors but I'm trying to understand why I'm getting these warnings . -
Django Static Folder Javascript
Hey There I am noob on django.Basically I am trying to add static folder on external javascript file for image slider but I can't If any buddy know the answer please help me.I Need your help -
Why is my django-graphql query returning null, when the property of my model is not?
I am creating a Django application with a GraphQL API (using graphene-django), and I have made the types for my models. However, I have this CompetitorModeType, which is a custom type. The purpose of this is for when I want to access a specific property of a Competitor (or a mode), I can use this type, and in the query, pass the mode a variable. The goal is to pass the Competitor id and the mode I want to access and get it back as response.data.mode or something like that. So it is what I did with the resolver: The problem is that when I do the query, I get the value as null, and I don't why. Here is the query I am doing: As you can see, I am getting null. However, the values are not null, as shown here: And if I do the same query in the Django shell, I don't get null: My theory is that I am not correctly creating the Type. That there is probably a logical error there because the shell is proof that the query works. If anyone knows what is going on, pls help! -
context not passing to included template
I am trying to pass models from my view to the template with the context parameter. The problem is that the context isn't passing to the included template, it is working everywhere else just not in the included template (before applying ajax it works fine). This is my template (gifts_template.html): <form id="form_filter_gifts"> {% csrf_token %} <div class="row"> <div class="col"> <select class='form-select' name="s_filter_gifts_by_date" id="s_filter_gifts_by_date"> <option value="" selected>Show Gift Cards From</option> {% for year, month_list in gifts_years_months.items %} {% for month in month_list %} {% if gifts_selected_year == year and gifts_selected_month == month %} <option value="{{ year }}-{{ month }}" selected>{{ year }}-{{ month }}</option> {% else %} <option value="{{ year }}-{{ month }}">{{ year }}-{{ month }}</option> {% endif %} {% endfor %} {% endfor %} </select> </div> <div class="col"> <input type="submit" name="btn_filter_gifts_date" class="btn btn-light" value='Filter'> </div> </div> <span>Cool!</span> {% if gifts %} <span>Cool!</span> <br style="line-height: 0;" /> <table class="table table-light table-striped"> <thead> <tr> <th scope="col">Date</th> <th scope="col">Gift Amount</th> <th scope="col">Tax</th> </tr> </thead> <tbody> {% for gift in gifts %} <tr> <td>{{ gift.date }}</td> <td>{{ gift.gift_money|floatformat }}</td> <td>{{ gift.gift_tax|floatformat }}</td> </tr> {% endfor %} </tbody> </table> {% endif %} This is the relevant html includer: <!--Balance Modal--> <div class="modal fade" id="balance_modal" … -
Align Bootstrap Tags with Text in List
How can I align the right side of the tag with the left side of the text (image attached)? superlongtagname | text1 shortertagname | text2 tinytagname | text3 Here is my template code (looping through a list of Django objects): <ul> <li> <span class="badge bg-{{ t.get_color_display }}"> {{ t.name }} </span> {{ rn.entry_text }} </li> </ul> I've tried alignment utilities (align-end), floating (on both the li and the span), etc, and nothing seems to work. -
AttributeError: 'list' object has no attribute 'objects' Django Rest
I want to post request django rest but this error.I have two Serializer.I want to post a request for full data not via id. I have a mistake File "C:\Users\Toma\AppData\Local\Programs\Python\Python39\lib\site-packages\rest_framework\serializers.py", line 205, in save self.instance = self.create(validated_data) File "C:\django 5\Новая папка (34)\Новая папка (29)\Новая папка (23) full\Musa\MDShop\serializers.py", line 125, in create new_smartphone = smartphone.objects.create(sm) AttributeError: 'list' object has no attribute 'objects' class OrderCreateSerializer(serializers.ModelSerializer): smartphone=ShopSerializer(many=True) class Meta: model = order fields = '__all__' def create(self, validated_data): smartphone = validated_data.pop('smartphone') smartphone_models = [] for sm in smartphone: print(type(sm)) new_smartphone = smartphone.objects.create(sm) new_smartphone.save() smartphone_models.append(new_smartphone) question = order.objects.create(**validated_data) print(smartphone_models) question.smartphone.set(smartphone_models) class ShopSerializer(serializers.ModelSerializer): img1 = serializers.SerializerMethodField('get_image_url') img2 = serializers.SerializerMethodField('get_image_url') img3 = serializers.SerializerMethodField('get_image_url') img4 = serializers.SerializerMethodField('get_image_url') img5 = serializers.SerializerMethodField('get_image_url') img6 = serializers.SerializerMethodField('get_image_url') class Meta: model = smartphone fields = ("id", "img1", "img2", "img3", "img4", "img5", "img6","title","price","slug") def get_image_url(self, obj): return obj.image.url how to solve this problem how to solve this problem how to solve this problem how to solve this problem -
Passing variables from Javascript to Django
My question is divided in two: if I have in my template a javascript confirmation <input type="submit" name="Next" value="Next" onclick="return confirm('Are you Sure?');"> How do I pass the user input (Ok, Cancel) to a view def SomeView(request): if user click Ok: #Do something The second question is in general how I pass a variable from Javascript to Django <script type="text/javascript"> var jsVar="Test" </script> def SomeView(request): #Use here jsVar -
Ajax Django 404 not found
could someone help me find a way to make my ajax request work? Also, I'd be really thankful if someone explained to me what does success: function(data){} do. So basically, I'm trying to update my cart using ajax, but I get an error "jquery.min.js:2 GET http://192.168.1.17:8000/product/test_product-1/add_to_cart?productId=4&action=add&inputVal=4 404 (Not Found)" All tutorials seem to use URL, but I'm using paths in my urls.py, could that be an issue? I'm using the latest Django version. I have never used ajax, so I don't really know what I'm doing. Please help:) $('.update-cart').click(function(){ var productId = $(this).attr("data-product"); var action = $(this).attr("data-action"); var pack = parseInt($(this).attr("data-pack")); try { var inputVal = parseInt(document.getElementById("quantity").value); if (inputVal%pack != 0){ inputVal += pack - inputVal%pack } } catch { var inputVal = pack } $.ajax( { type:"GET", url: "add_to_cart", data:{ productId: productId, action: action, inputVal: inputVal, }, success: function( data ) { $( '#like'+ productId ).remove(); $( '#message' ).text(data); } }) }); this is my urls.py code: urlpatterns = [ path('add_to_cart/', views.addToCart, name='add_to_cart'), ... ] and this is my view: def addToCart(request): if request.method == 'GET': productId = request.GET['productId'] action = request.GET['action'] quantity = request.GET['inputVal'] customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) addItem = Product.objects.get(id=productId) # getting the … -
Django: Delete or hide currently image path in updateview form?
is there a way to hide or delete this Currently: image path in Updateview form from python? I could use javascript but i want to know if it possible. -
Twitter like comments with django
I want to build a Twitter like comment system with django where users can comment on a post from the feed without going to the detail view. Any ideas -
Managing global objects in Django
Context: I was going through various guides, tutorials and also posts here in the stackoverflow. I need to handle process, e.g., - “pick topic —> show author list —> delete all —> ask confirmation —> show result —> go back to author list” The obvious (and simplistic) approach is to create sets of views for each process. And save process state in session variables or pass via URL-s (however, I discovered this method can be very brittle if too many information is passed). Also I need to tell each view where to go next, and this mushrooms into a bulky chain of instructions repeated for each URL request. Instead, I want two extra things: encapsulate a process at single place re-use views, e.g. to re-use Topic List view to pick a single topic. That is, to work in “picker mode”. (btw, if I try to do this with multiple view classes, the next view class needs to know what to do and where to return…) I also checked django workflow libs, and so on. and still not convinced. Question: if I create global object to encapsulate process and reference it from the current session - is this a good idea? … -
Required field error happans only when using ajax
I have a model named SaleEntry: class SaleEntry(models.Model): date = models.DateField() ebay_price = models.FloatField() amazon_price = models.FloatField() ebay_tax = models.FloatField() paypal_tax = models.FloatField() tm_fee = models.FloatField(default=0.3) promoted = models.FloatField(default=0.0) profit = models.FloatField() discount = models.FloatField(default=0) country = models.CharField(max_length=100, default="-----") user = models.ForeignKey(User, on_delete=models.CASCADE, default=0) def save(self, *args, **kwargs): if not self.pk: # object is being created, thus no primary key field yet change_balance = Balance.objects.get(user=self.user) change_balance.balance = change_balance.balance - self.amazon_price - self.tm_fee + self.discount change_balance.save() super(SaleEntry, self).save(*args, **kwargs) def calc_profit(self): return self.ebay_price - self.amazon_price - self.ebay_tax - self.paypal_tax - self.tm_fee - self.promoted + self.discount def __str__(self): return f'{self.user} - {self.profit}' And I have a form handling this model SaleEntryForm: class SaleEntryForm(ModelForm): class Meta: model = SaleEntry fields = "__all__" widgets = { 'date': DateInput(attrs={'class': 'form-control', 'id':'f_date'}), 'ebay_price': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'eBay Price', 'id':'f_ebay_price', 'onkeyup': 'calc_profit()'}), 'amazon_price': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Amazon Price', 'id':'f_amazon_price', 'onkeyup': 'calc_profit()'}), 'ebay_tax': forms.NumberInput(attrs={'class': 'form-control col-1', 'placeholder': 'eBay Tax', 'id':'f_ebay_tax', 'onkeyup': 'calc_profit()'}), 'paypal_tax': forms.NumberInput(attrs={'class': 'form-control col-1', 'placeholder': 'Paypal Tax', 'id':'f_paypal_tax', 'onkeyup': 'calc_profit()'}), 'tm_fee': forms.NumberInput(attrs={'class': 'form-control col-1', 'placeholder': 'TM Fee', 'id':'f_tm_fee', 'onkeyup': 'calc_profit()'}), 'promoted': forms.NumberInput(attrs={'class': 'form-control col-1', 'placeholder': 'Promoted', 'id':'f_promoted', 'onkeyup': 'calc_profit()'}), 'profit': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Profit', 'readonly':'true', 'id':'f_profit'}), 'discount': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Discount', 'id':'f_discount'}), 'country': forms.TextInput(attrs={'class': 'form-control', 'placeholder': … -
How to include part of the url patterns from an Django app
I have two django apps with URLs app_name = 'app1' urlpatterns = [ path('url1/', ..., name='name1') path('<slug:username>/', ..., name='name2') ] and app_name = 'app2' urlpatterns = [ path('url2/', ..., name='name3') path('<slug:username>/action2/', ..., name='name4') ] This would not work if I include them in the master urlpatterns as urlpatterns = [ path('', include('app1.urls'), path('', include('app2.urls'), ] because url2/ would first match <slug:username>/ and trigger an error for unknown username. There are a few potential solutions but none works very well for me: Use non-slug url2 such as ~url2. That means all urls in app2 has to start with something like ~ or ^. Redefine some URLs in the master urlpatterns but then I will have to import views from the apps and remove urls from the app urlpattern. Use regular expression to explicitly exclude some names from the <slug:username>. This could work but then any changes in app2 urlpatterns need to be reflected in app1's <slug:username> ... exclude certain names. It is possible to do something like urlpatterns = [ path('', include('app1.urls'), # non-user part path('', include('app2.urls'), # non-user part path('', include('app1.urls'), # user part path('', include('app2.urls'), # user part ] so that fixed-name URLs will be matched before <slug:username>? -
Django does not receive POST method in HTML form
HTML is not submitting post method (template that I made from boostrap studio). I tried adding print statements in views.py if method.request == 'POST: and it wont pass the if statement. The problem is that when I try to save the inputs from the form, it wont save in the database. However, when I try to manually code the <form>..</form> in html (same file) django saves the data. Here are my codes that I think are connected to the problem: views.py def profile_settings(request): user = request.user data = Profile.objects.get(pk=user.id) print("AA") if request.method == 'POST': print("AB") form = ProfileDisplayForm(request.POST or None, request.FILES or None, instance=data) print(request.POST) if form.is_valid(): print(request.POST) form.save() else: form = ProfileDisplayForm(instance=data) context = {'form': form} return render(request, 'main/profile_edit.html', context) models.py class Profile(models.Model): account = models.OneToOneField(User, null=True, on_delete=models.CASCADE) age = models.IntegerField(blank=True, null=True, default="Not Set", validators=[MaxValueValidator(100), MinValueValidator(1)]) gender = models.CharField(max_length=6, choices=GENDER_CATEGORY, null=True, default="Not Set") profile_image = models.ImageField(upload_to=get_profile_image_filepath, default='default.jpg', null=True) def __str__(self): return self.account.username forms.py class ProfileDisplayForm(ModelForm): age = forms.IntegerField(widget=forms.NumberInput(attrs={'class': 'form-control',})) class Meta: model = Profile fields = ('age', 'gender', 'profile_image') html -->this is the custom code that I got from bootstrap studio that I think is causing the problem {% extends 'main/base.html' %} {% block title %} Profile Settings {% … -
django Model.objects.filter(feildname = 'some_column') vs Model.objects.all().filter(feildname = 'some_column') which one performs better
I am trying to see which of these will perform better queryset = Model.objects.filter(feildname = 'some_column') queryset = Model.objects.all().filter(feildname = 'some_column') -
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>'
I just started off my project awhile ago, and the server does not allow me to run it. I do not understand why my app_name= appointment could not be recognized by the system. Could someone please help me, thank you. My list are: Booking appointment migrations static templates _init_ admin apps models tests views booking_env bookingweb01 bookingweb01 _pycache_ _init_ asgi setting urls wsgi db.sqlite manage INSTALLED_APPS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'appointment', ] urls.py from django.contrib import admin from django.urls import path from appointment.views import * urlpatterns = [ path('admin/', admin.site.urls), path('', homepage, name= 'homepage'), ] views.py from django.shortcuts import render # Create your views here. def homepage(request): return render(request, 'index.html') After running python manage.py runserver I received the error below: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.496.0_x64__qbz5n2kfra8p0\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.496.0_x64__qbz5n2kfra8p0\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\booking\booking_env\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\booking\booking_env\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\booking\booking_env\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\booking\booking_env\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\booking\booking_env\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\booking\booking_env\lib\site-packages\django\__init__.py", line 24, in … -
How to make send_mail function send bcc emails - Django REST API
I want to send notifications to everybody (except a message author) in the chat if there is a new message in the chat. I want to send one email to all, so that nobody can see the others' email addresses (bcc-blind carbon copy). How can I do so? Here is my view: class WriteMessageCreateAPIView(generics.CreateAPIView): permission_classes = [IsAuthenticated, IsParticipant] serializer_class = MessageSerializer def perform_create(self, serializer): ... chat = serializer.validated_data['chat'] chat_recipients = chat.participants.exclude(id=self.request.user.id) for participant in chat_recipients: MessageRecipient.objects.create(message_id=new_message.id, recipient_id=participant.id) send_new_message_notification(chat.id, new_message.author, chat_recipients) Here an email is sent to all recipients at once, but in cc form (everybody can see each others' email addresses). Here is send_mail function: def send_new_message_notification(chat_id, sender: User, recipients): link = BASE_URL + '/messaging/chat/%s/messages' % chat_id send_email( subject='You have a new message', message='Click the link below to view the message:', link), from_email='some_email@email.com', recipient_list=recipients ) Yes, I could do like this in a view part: for participant in chat_recipients: MessageRecipient.objects.create(message_id=new_message.id, recipient_id=participant.id) send_new_message_notification(chat.id, new_message.author, participant) And send one by one, but it is not efficient. So the question is: is there any method to send an email with to all recipients at once so that they are not able to see each others' email addresses? -
Heroku: ModuleNotFoundError: No module named 'sendgrid_backend'
My django app is using sendgrid and working on local dev. I deployed to Heroku and am getting error on sending mail with heroku log showing: ModuleNotFoundError: No module named 'sendgrid_backend'. I have the EMAIL_BACKEND env variable set to 'sendgrid_backend.SendgridBackend' which works on local. For the Heroku requirements.txt file, I originally had 'sendgrid' (when I first got the error) and then I added 'sendgrid-django' as well which didn't seem to help. On the build, I noticed sendgrid-django version might actually conflict with the current sendgrid version, but regardless same No module error. I also configured Heroku Sendgrid add-on, since I figured that's how Heroku-Sendgrid want it setup. Any help on getting rid of this error "ModuleNotFoundError: No module named 'sendgrid_backend'"? -
Using Taiga6 with Docker and an SMTP Server that does not require authentication
I've recently used the docker images provided for Taiga6 to run an instance using docker-compose on Ubuntu 20.04. Everything seems to work fine, except that I can't seem to get email working quite right. I use Gmail for my company's email, foamfactory.io, but the gmail smtp relay seems to be... finicky at best. I decided to try using https://github.com/bokysan/docker-postfix to have a simple SMTP relay set up as part of the docker-compose.yml file. I can get the email server to start fine, and it will send emails as expected when I connect to the taiga-back container, install cURL, and run the following command: curl --url 'smtp://taiga-email:25' --mail-from 'taiga-noreply@foamfactory.io' --mail-rcpt 'jaywir3@gmail.com' --upload-file mail.txt --insecure However, when I attempt to send an email from Taiga (for example, inviting a user), I get the following exception: taiga-back_1 | ERROR:2021-02-10 17:42:49,044: Internal Server Error: /api/v1/memberships/4/resend_invitation taiga-back_1 | Traceback (most recent call last): taiga-back_1 | File "/opt/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner taiga-back_1 | response = get_response(request) taiga-back_1 | File "/opt/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response taiga-back_1 | response = self.process_exception_by_middleware(e, request) taiga-back_1 | File "/opt/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response taiga-back_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) taiga-back_1 | File "/taiga-back/taiga/base/api/viewsets.py", line 104, in view taiga-back_1 | … -
django issue with url receive from API
http://127.0.0.0:8000/test-pay-redirect?token=60257a578aedc20bd1a6892c&mode=popup&tap_id=chg_TS014820212148r1N41102850 this is redirect link from api i would like to render my urls.py re_path(r"^test-pay-redirect/",views.paytestredirect,name='test_pay_redirect'), path("test-pay-redirect/",views.paytestredirect,name='test_pay_redirect'), i try both but it couldnt connect with this urls -
Error on retrieving json data through django templates in javascript gives Uncaught SyntaxError: missing ) after argument list
I am rendering the json response data through apiview in django restframework, to html template list.html where i want to retrieve this data in a javascript code. However everytime it gives "missing ) after argument list error" even though they are not actually present in the data received (as seen in inspect tools of chrome) Getting the error on var list =JSON.parse("{{data|safe}}") The code apiview from views.py which is rendering the data is : @api_view(['GET','POST']) def memeList(request): if request.method=='GET': meme = Meme.objects.all().order_by('-meme_id')[:100] serializer = MemeSerializer(meme, many=True) elif request.method=='POST': serializer=MemeSerializer(data=request.data) if serializer.is_valid(): serializer.save() serJS = JsonResponse(serializer.data,safe=False) return render(request,'list.html',{'data':serJS.content}) Any solution for this as i have tried all available solutions on the internet still the problem isn't resolved. -
Custom Register Form with Django Rest Auth - Error: save() takes 1 positional argument but 2 were given
I want to create a custom Signup form with Django Rest Auth and Django Allauth but I'm getting an error save() takes 1 positional argument but 2 were given I know that this error is related to the function def save(self, request) provided by Django Rest Auth, but I have no clue how I can change it. What should I do to make it work? Bellow is the respective code for my user Model and Serializer: # Models.py class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new user""" if not email: raise ValueError('Users must have an email address') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): """Creates and saves a new super user""" user = self.create_user(email, password, **extra_fields) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """Custom user model that supports using email instead of username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) age = models.PositiveIntegerField(null=True, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'age'] def __str__(self): return self.email # serializers.py class UserSerializer(serializers.ModelSerializer): """Serializer for the users object""" class Meta: model = get_user_model() fields = ('email', 'password', 'name', 'age') extra_kwargs … -
How to change UserCreationForm error messages in django
I'm trying to change error messages in UserCreationForm. I want to change password field error messages but i don't know how. I tried this: class CreateUserForm(UserCreationForm): error_messages = { 'password_mismatch': "my message", } class Meta: model = User fields = ['username', 'first_name', 'password1', 'password2'] and it works, but i can't figure out how to change other messages like "password is too similar to the username", "password is too short", "password is too common" and "password is entirely numeric". I tried adding to the error_messages 'min_length' key but this doesn't work -
Rendering objects by category in Django
I created a model, in which admin categorizes posts by being new or exclusive. Now I want to view posts, that are only new. here's the code: class Post(models.Model): class Category(models.TextChoices): NEW = 'NP', ('New Post') EXCLUSIVE = 'EP', ('Exclusive Post') post_category = models.CharField( max_length=2, choices=Category.choices, default=Category.NEW, ) title = models.CharField('Title of the post',max_length=50) content = models.TextField('Page content', max_length=500) posted = models.DateTimeField('last updated') def __str__(self): return self.title def is_new(self): return self.post_category in{ self.Category.NEW, self.Category.EXCLUSIVE, } views: def index(request): post_list = Post.objects.filter(post_category).order_by('-posted')[:2] context = { 'post_list': post_list, 'page_list': Pages.objects.all(), } return render(request, 'pages/extension.html', context)