Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter ManyToMany fields using django-filter
How can I filter a ManyToMany field with django-filter I would like to display an input field on a template where you can filter Student to get these results: all of the Students that speak English (Student.languages contains 'English') all of the Students that speak English and German (Student.languages contains 'English' and 'German') # models.py class Student(models.Model): name = models.CharField(...) languages = models.ManyToManyField(Language) class Language(models.Model): language = models.CharField(...) # English / German / ... level = models.CharField(...) # B1 / B2 / C1 / ... #filters.py import django_filters as filters from .models import Employee class EmployeeFilter(filters.FilterSet): class Meta: model = Employee fields = ['name', 'languages'] How should I modify the EmployeeFilter to make it ready to filter the Students according to their spoken languages? I tried declaring a class variable named languages like so: class EmployeeFilter(filters.FilterSet): languages = filters.ModelChoiceFilter( queryset = Languages.objects.all() ) class Meta: model = Employee fields = ['name', 'languages'] but it did not work, the filter had no effect. Thanks for your help, it is well appreciated! -
subprocess.PIPE not working in django model
So I have this model in which there is isRunning property. When it is set to True it spawns a subprocessing instance and saves it to subprocessObject . It looks like this. class Monitor(models.Model): Name = models.CharField(max_length=143) # Some other stuff CommandToExecute = models.CharField(max_length=1000, default="python -c print('HelloWorld')") subprocessObject = None @property def isRunning(self): return False @isRunning.getter def isRunning(self): if self.subprocessObject is None or self.subprocessObject.poll() is None: return False return True @isRunning.setter def isRunning(self, value): if value is True and self.isRunning is False: self.subprocessObject = subprocess.Popen(self.CommandToExecute.split(" "), stdout=sys.stdout, stdin=sys.stdin, shell=True) elif value is False and self.isRunning is None: self.subprocessObject.stdin.close() self.subprocessObject.stdout.close() self.subprocessObject.terminate() self.subprocessObject == None def __str__(self): return self.Name For now I have a simple file that prints something each second with flush=True. The problem is that there is an error looking like this: OSError: [Errno 22] Invalid argument Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='cp1252'> OSError: [Errno 22] Invalid argument When I changed subprocess.PIPE to sys.stdout and when I started the subprocess in a view it worked as expected so it's probably problem with subprocess.PIPE in models? Should I start the process in a view or is there an solution? -
Django Form auto submit when user open page
I have different forms on my template. Each of these forms are displayed against specific venues for which rules/ conditions are set. The submission of the form results in a set of points being added. The rule I am struggling with relates to the following situation: If a user opens a page of a venue_1 and if venue_1 has a rule that considers that +1 is added when the page is open; then +1 point is added to the user point count on page load. It seems in order to achieve this I need to use some JavaScript. As this is a recurring question on this forum I tried the different solutions offered but cannot seem to make it work. I must be missing something. models.py class Venue(models.Model, HitCountMixin): name = models.CharField(verbose_name="Name",max_length=100, blank=True) class VenueLoyaltyPointRule(models.Model): venue = models.ForeignKey(Venue, null = True, blank= True, on_delete=models.CASCADE) points = models.IntegerField(verbose_name="loylaty_points_rule", null = True, blank=True) auto_submit = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) views.py def venue_loyalty_add_point_rule(request,userprofile_id): url = request.META.get('HTTP_REFERER') venue = UserProfile.objects.filter(user=request.user).values('venue') venue_loyalty_point_rule = get_object_or_404(VenueLoyaltyPointRule, venue=request.user.userprofile.venue) submitted = False if request.method == "POST": form = LoyaltyCardForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.add_points = venue_loyalty_point_rule.points data.user_id = userprofile_id data.venue_id = venue data.save() form.save() messages.success(request, 'Points added!') return … -
ProgrammingError: column ... must appear in the GROUP BY clause or be used in an aggregate function
Django's documentation mentions aggregation: pubs = Publisher.objects.annotate(num_books=Count('book')) My code is full of similar constructs (adding a count of something to a queryset, using annotate), and this always worked well. Now suddenly, for reasons unknown, I'm getting this error: ProgrammingError: column ... must appear in the GROUP BY clause or be used in an aggregate function In fact, I have the same version of Django on my dev and prod, and everything works on dev, but fails on prod (typical). Spontaneously. For no apparent reason. And I cannot add the named column to the GROUP BY clause, because then it wants me to add the next column, and the next, and the next, etc. I can also not add some random aggregate function. In short: the solutions that the error mentions make no sense! There are many more questions with this same error, many unanswered. I have no solution, but it seems this error started appearing lately, in Django versions 4+, at least for me. I've tried the failing SQL query directly within Postgres and it fails there as well, of course, with exactly the same error. The fault is not with Django. The only way to make this annotate query … -
Stop logging parameters for django background tasks?
I'm using Django Background Tasks in my app for a task that requires user authentication. To create the task, I use a command like: my_cool_task(pks, request.POST.get('username'), request.POST.get('password')) I just realized that the username and password parameters are getting stored in the Django Admin tables for the tasks, which in this case creates a security issue. Is there a way to not store these parameters? Or is there a better way to authenticate a process that will take longer than it takes for a server timeout error? -
error : django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. When I run the testapscheduler.py file, I get the above error. Is it because I only run one file in the Dajngo frame that I get the above error? How can I test it? testapscheduler.py: import logging from models import Todo from apscheduler.schedulers.background import BackgroundScheduler from datetime import datetime, timedelta import pytz import requests def notify_todo(): # 現在の日時を取得 now = datetime.now(pytz.timezone('Asia/Tokyo')) # 締め切りが30分以内のTODOリストを取得 todos = Todo.objects.filter( deadline__gt=now - timedelta(minutes=30), deadline__lt=now + timedelta(minutes=30), ttime__isnull=False, ttime__gt=now.time() ) # 30分以内のTODOリストの数を出力 # ログの出力名を設定 logger = logging.getLogger('mylog') #ログレベルを設定 logger.setLevel(logging.DEBUG) #ログをコンソール出力するための設定 sh = logging.StreamHandler() logger.addHandler(sh) logger.debug(f'{len(todos)}個のTODOリストが締め切り30分以内にあります。') for todo in todos: #LINE NotifyのAPIトークンを取得 api_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # 通知メッセージの作成 message = f"【{todo.title}】\n締切時間:{todo.deadline.strftime('%Y/%m/%d %H:%M')}\n詳細:{todo.description}" # LINE Notifyに通知を送信 headers = {'Authorization': f'Bearer {api_token}'} payload = {'message': message} requests.post('https://notify-api.line.me/api/notify', headers=headers, data=payload) def start(): scheduler =BackgroundScheduler(timezone='Asia/Tokyo') scheduler.add_job(notify_todo, 'interval', seconds=2) # 2秒ごとに実行 scheduler.start() models.py from django.db import models class Todo(models.Model): title = models.CharField("タスク名", max_length=30) description = models.TextField("詳細", blank=True) deadline = models.DateField("締切") ttime = models.TimeField("") def __str__(self): return self.title -
I am working on django website for a restaurent ,in order to display every day's menu on my homepage what should I do
How to handle the django articles in order to display the menu of restaurent on my website's homepage every day? How can I add and update menu on homepage? I tried to add a modal based menu pop ups when admin logins but didn't worked -
ModuleNotFoundError: No module named 'bootstrap5'
i have installed boostrap 5 and wrote it down on installed apps and this error keeps popping up i´ve tried everything, unisntalling and installing, writing this: python3 -m pip install django-bootstrap5, and nothing works -
How to return object insted of id's, and auto create foreingKey object (get python with django)
I'm creating a simple rest api This is my actual result from devices [ { "id_device": "a099d2ce-812b-4d85-8c8b-cfe71057fbe7", "name": "Interruptor 4", "identifier": "teste1", "group": "39407ef6-1a3e-4965-9b61-96f6c40b76b3", "options": [ "1b383a37-5229-4ae0-9649-f76aa32eeda0", "4ff5406a-8c7b-4517-9ec0-14fd4f68f30b", "a541216d-f509-4461-85ca-444491ac9217", "3debe828-edd6-4d83-bfd8-2776a1594380" ] }, { "id_device": "dc9f672f-6759-4b1f-ac65-e3d78e09833d", "name": "teste", "identifier": "teste", "group": "39407ef6-1a3e-4965-9b61-96f6c40b76b3", "options": [ "a76c54cf-b11a-4a5e-986b-3e38a86568cd", "ef736b76-4bac-42f1-9393-c01e18787108", "84e6c598-072f-4bb8-90e9-34019547534f" ] } ] my models.py from uuid import uuid4 from django.db import models class Options(models.Model): id_option = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) identifier = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class Groups(models.Model): id_group = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class Devices(models.Model): id_device = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) identifier = models.CharField(max_length=255) options = models.ManyToManyField(Options) group = models.ForeignKey(Groups, on_delete=models.CASCADE, default="") viewsets from rest_framework import viewsets from devices.api import serializers from devices import models class DevicesViewsets(viewsets.ModelViewSet): serializer_class = serializers.DevicesSerializer queryset = models.Devices.objects.all() class OptionsViewsets(viewsets.ModelViewSet): serializer_class = serializers.OptionsSerializer queryset = models.Options.objects.all() class GroupsViewsets(viewsets.ModelViewSet): serializer_class = serializers.GroupsSerializer queryset = models.Groups.objects.all() serializers from rest_framework import serializers from devices import models class DevicesSerializer(serializers.ModelSerializer): class Meta: model = models.Devices fields = '__all__' class OptionsSerializer(serializers.ModelSerializer): class Meta: model = models.Options fields = '__all__' class GroupsSerializer(serializers.ModelSerializer): class Meta: model = models.Groups fields = '__all__' I try some … -
I'm looking for an Available/unavailable/maybe Available date picker html
I'm looking to create a date picker in django html where the user can use a traffic light system to update a calendar saying if they are available (green) unavailable (amber) not available (red). The user would them submit the answers to update a data base. Lots of date pickers only have the available/unavailable. I can't see options for the 'maybe available'. Any ideas where to start. -
What is the business logic/rule of this function in views.py?
I am working on learning management system and got a piece of code from a source. This function is in my views.py file. It adds a semester. But I'm not clear about the business rules of this function. Means why I'm not able to mark more then one semester as is_current_semester. Please help me to get the basic idea behind the working of this code. Thank you @login_required @lecturer_required def semester_update_view(request, pk): semester = Semester.objects.get(pk=pk) if request.method == 'POST': if request.POST.get('is_current_semester') == 'True': # returns string of 'True' if the user selected yes for 'is current semester' unset_semester = Semester.objects.get(is_current_semester=True) unset_semester.is_current_semester = False unset_semester.save() unset_session = Session.objects.get(is_current_session=True) unset_session.is_current_session = False unset_session.save() new_session = request.POST.get('session') form = SemesterForm(request.POST, instance=semester) if form.is_valid(): set_session = Session.objects.get(pk=new_session) set_session.is_current_session = True set_session.save() form.save() messages.success(request, 'Semester updated successfully !') return redirect('semester_list') else: form = SemesterForm(request.POST, instance=semester) if form.is_valid(): form.save() return redirect('semester_list') else: form = SemesterForm(instance=semester) return render(request, 'app/semester_update.html', {'form': form}) -
How do I Access fields from one table through another table in Django
Please how do I link and access the fields: 'location' and 'building_type' from Property table in Client table. (I want to be able to get the 'location' and 'building_type' information for Client table from Property table ) class Property(models.Model): location = models.CharField(choices=Property_Location, max_length=120) building_type= models.CharField(choices=Property_Type, max_length=120) class Client(models.Model): first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) phone = models.IntegerField() location=() building_type =() I tried using PK & related_name for both, but it ended up showing me just the details of 'location' for both the location and building_type fields -
Django Runserver Error: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1:3306' (111)")
I have checked the answers to these questions and many others but my problem isn't still solved yet: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (111)" mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on '127.0.0.1:3306' (111 Connection refused) I got a new system (Windows,same as the old one) and installed Ubuntu 22.04 and install Django and other dependencies, including pipenv to manage the packages. In my old system, the project was in a Dropbox folder and I have navigated to it in the new system, but when I run python manage.py runserver I get ...lib/python3.10/site-packages/MySQLdb/connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1:3306' (111)") My database setting is also okay and MySQL80 is running when I checked Windows Services DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_db', 'USER': 'root', 'PASSWORD': 'my_password', 'HOST': '127.0.0.1', 'PORT': '3306', } } Meanwhile, the old system works just fine. -
How to avoid redirect after like in Django?
I've created likes logic by sending a post request to the specific url. Disadvantage of this method is that I can't avoid redirect. Even HTTPresponseRedirect to the current page is frustrating for user, cause it bangs viewport to the start of the page. I don't understand ajax, but wouldn't mind to use java script if needed. Most likely solution is to create it in Django somehow, but I think it might be impossible. So, any solutions are welcome! -
How to add google pay payment gateway with react?
Hello guys I am trying to integrate a payment gateway for my first e-commerce process build with react and Django as the backend. I tried with Razorpay but they halted onboarding new merchants. After watching some videos I found that we can add google pay also with react with the google pay react button. I found this package https://www.npmjs.com/package/@google-pay/button-reactto integrate payment, but it didn't show up option, just the card option and when I tried with the card in response it didn't show a proper response. it gives a token not a transaction or id as Razorpay or other payments give. Please guide me if anybody integrates payment with this library. -
DjangoChatbox Using WebSocket and Django Channels
Hey I Create a django chatbox using websocket while watching a tutorial In tutorial the websocket connection is working properly but in my project the websocket connection is not start it always shows close state..............please help me enter image description here Here is the error enter image description here second error consumer.py :_ import json from django.contrib.auth.models import User from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from .models import Room, Message class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): data = json.loads(text_data) print(data) message = data['message'] username = data['username'] room = data['room'] await self.save_message(username, room, message) # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username } ) # Receive message from room group async def chat_message(self, event): message = event['message'] username = event['username'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'username': username })) @database_sync_to_async def save_message(self, username, room, message): user = User.objects.get(username=username) room = Room.objects.get(slug=room) Message.objects.create(user=user, room=room, content=message) routing.py :- from django.urls import path from . import consumers websocket_urlpatterns = … -
DRF How to overide the way objects are written to DB
I have a field in my model that contains a string. That string is given in plaintext when there is a create, patch or partial patch call to the API endpoint. But the value stored in the DB should be encrypted. But if there is a list or retrieve call, then the encrypted value should be displayed. Having the field as "write_only" is not an option as I need to retrieve the encrypted string via the API. So the problem is that I have to take the input value and encrypt before it gets stored on the DB. But when I retrieve the objects then the value should be displayed as it is stored in the DB. One solution I was thinking of was to use different serializers for the different methods in the Viewset and having a method field that encrypts the string. And a simple CharField to display the value in the other serializer. Another could be to change the object model itself to have the functionality build in the model. But maybe there is a better way to do it? -
Sum together list of F expressions
Is there a way to specify (in an annotation or aggregation) that a sequence of F expressions should be summed together without manually typing out F("first_prop") + F("second_prop") + ...? I want something similar to how python's sum() function allows you to pass an iterable and get the sum of the values in the iterable i.e. sum([1,2,3]) returns 6. Concretely, I want something that looks like this: class Tree(TimeStampedModel): leaf_count = models.IntegerField() branch_count = models.IntegerField() Tree.objects.create(leaf_count=60, branch_count=8) Tree.objects.create(leaf_count=30, branch_count=3) # now I want to annotate a combined count using my imaginary IterableSum aggregator combined_sums = list( Tree.objects.all().annotate( combined_count=IterableSum(fields=[F("leaf_count"), F("branch_count")]) ).values_list("combined_count", flat=True) ) combined_sums # [68, 33] How can I achieve this? -
Django query to combine two tables without aggregation
I want to write a django query and avoid raw sql doing the following: Lets imaging I have those two tables resulting from django query (query under the table): Table 1: Name Count First 4 Second 7 Third 2 Fourth 12 Fith 5 Query: q1 = Entity.objects.filter(some_condition=1)\ .values( "name", ).annotate(Count("name")) Table 2: Name Count First 13 Second 6 Third 2 Fourth 12 Sixth 3 Query: q2 = Entity.objects.filter(some_condition=2)\ .values( "name", ).annotate(Count("name")) What I want to achieve is the following table using just Django query: Name Count table 1 Count table 2 First 4 13 Second 7 6 Third 2 2 Fourth 12 12 Fith 5 0 Sixth 0 3 Two solutions seems to solve it but didn't work. If I use 3 = (q1 | q2) the column "count" will be aggregated and there will be just one count column. If I'm using q1.union(q2) I get the error message: django.db.utils.DatabaseError: ORDER BY not allowed in subqueries of compound statements. -
Cannot login to Django admin by `Apache/mod_wsgi` but it worked normally by `python runserver`
Everything of my django project is OK when I accessed to it by running python runserver. But if I accessed to my django project remotely via Apache/mod_wsgi, I cannot login with valid passwd, like the picture below: That error occured after my env being re-established because of my python updating. Here is my env list: aldryn-apphooks-config==0.6.0 asgiref==3.6.0 click==7.1.2 cmsplugin-polls==0.1.0 defusedxml==0.6.0 diff-match-patch==20200713 dj-database-url==0.5.0 Django==3.1.7 django-admin-ip-restrictor==2.2.0 django-appdata==0.3.2 django-awesomplete==0.2.1 django-bootstrap3==14.2.0 django-classy-tags==2.0.0 django-cms==3.7.4 django-cors-headers==3.6.0 django-crispy-forms==1.10.0 django-filer==2.0.2 django-formtools==2.2 django-import-export==2.4.0 django-ipware==3.0.2 django-js-asset==1.2.2 django-jsonfield==1.4.1 django-markdownx==3.0.1 django-mdeditor==0.1.18 django-meta==2.0.0 django-mptt==0.11.0 django-parler==2.2 django-polymorphic==3.0.0 django-reversion==3.0.8 django-sekizai==2.0.0 django-sortedm2m==3.0.2 django-tagging==0.5.0 django-tagging-autocomplete==0.5.1 django-taggit==1.4.0 django-taggit-autosuggest==0.3.8 django-taggit-templatetags==0.2.5 django-templatetag-sugar==1.0 django-treebeard==4.3.1 djangocms-admin-style==1.5.0 djangocms-apphook-setup==0.4.1 djangocms-attributes-field==2.0.0 djangocms-blog==1.2.3 djangocms-bootstrap4==1.6.0 djangocms-file==2.4.0 djangocms-googlemap==1.4.0 djangocms-icon==1.5.0 djangocms-installer==1.2.3 djangocms-link==2.6.1 djangocms-picture==2.4.0 djangocms-snippet==2.3.0 djangocms-style==2.3.0 djangocms-text-ckeditor==3.10.0 djangocms-video==2.3.0 djangorestframework==3.12.2 easy-thumbnails==2.7 et-xmlfile==1.0.1 future==0.18.2 html5lib==1.1 httplib2==0.9.2 jdcal==1.4.1 jieba==0.42.1 joblib==1.0.0 lxml==4.9.2 Markdown==3.3.3 MarkupPy==1.14 nltk==3.5 odfpy==1.4.1 openpyxl==3.0.5 Pillow==7.2.0 psycopg2==2.8.6 pytz==2020.1 PyYAML==5.3.1 regex==2020.11.13 six==1.15.0 sqlparse==0.3.1 tablib==3.0.0 tqdm==4.55.0 tzlocal==2.1 Unidecode==1.1.1 webencodings==0.5.1 Whoosh==2.7.4 xlrd==2.0.1 xlwt==1.3.0 I had tried to adjust some cache settings in settings.py according to django FAQ, but nothing helps. CSRF_COOKIE_SECURE= False SESSION_COOKIE_SECURE= False SESSION_COOKIE_DOMAIN= "159.226.116.202" -
Django Forms: Django-select2 Not rendering multi select box correctly
Im using django-select2 : https://django-select2.readthedocs.io/en/latest/index.html Im attempting to create a multiple tag select dropdown box similar to this: [![MultiSelectTagBox][1]][1] The problem is its not loading as expected: [![Actual Rendering of Form][2]][2] Below is my code. Im using the Select2TagWidget currently but I have tried the following other widgets: ModelSelect2MultipleWidget Select2MultipleWidget forms.py class BankForm(ModelForm): required_css_class = "required" formField1 = forms.ModelMultipleChoiceField( queryset=Bank.objects.all(), label="Lead Bank", widget=Select2TagWidget, ) class Meta: model = AdditionalBank fields = [ "formField1", ] """ Labels for the fields we didn't override """ labels = {} urls.py Ive added the correct path to my urls.py file path("select2/", include("django_select2.urls")), I have the redis queue setup correctly in my settings.py file. Im pretty confident the rest of the configuration is setup correctly outlined in the docs for django-select2 My Front end form is rendering this html/css: <select name="lead\_bank" lang="None" data-minimum-input-length="1" data-theme="default" data-allow-clear="false" data-tags="true" data-token-separators="\[\&quot;,\&quot;, \&quot; \&quot;\]" required="" id="id\_lead\_bank" class="django-select2" multiple=""> <option value="1">Citi</option> <option value="2" selected="">USBank</option> <option value="3">Wells Fargo</option> <option value="4" selected="">NY Bank</option> </select> [1]: https://i.stack.imgur.com/15ij6.png [2]: https://i.stack.imgur.com/YPDMS.png Keep in mind I am very new to front end dev. Primarily a backend dev. Thank you in advance ! -
Django OuterRef access grandparent
I've this piece of code parent_product_subquery = Count(Subquery(Product.objects.filter( Q(Q(description__id__in=[OuterRef('pk')]) | Q(productvariant__name__id__in = [OuterRef('pk')])), user=self.request.user, **filter_kwargs, ).only('pk'))) obj = get_object_or_404(Translation.objects.annotate(is_user_owner=parent_product_subquery), pk=self.kwargs['translation_id']) print(obj.is_user_owner) if obj.is_user_owner: return obj it always prints False, what am I doing wrong? -
Pass "next" url in Django from login page to signup page
For one of form view, I use LoginRequiredMixin and when a user is not logged in and it redirects to the login page with parameters "/login/?next=/foo/bar/". There is a signup link below the page for those who don't have an account. I want to have such link to signup that I want it to have the parameters "/signup/next=/foo/bar/". I don't know how to include the parameters in {% url %} tag. How can I make it possible? Answers in Class Based Views please. -
In Django, how to check if user is in site_id (site_id are created by after)
the objective of the system is to check if the user is in such site_id or not to display a part of the html page to him here I do it with groups : views.py def is_admin(user): return user.groups.filter(id=1).exists() def is_client(user): return user.groups.filter(id=4).exists() template (main_list.html) {% for group in request.user.groups.all %} {% if 1 == group.id %} and I would like to do it with my site_id (Foreign Key) here is my first attempt : views.py def is_siteone(user): return user.site_id.filter(id=1).exists() template (main_list.html) {% if is_siteone %} models.py class Site(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=255) version = models.CharField(verbose_name='Program version', blank=False, default='1.0', max_length=20) def __str__(self): return self.name def filter(self, id): pass but it returns the following error error return Do you have any ideas on how to proceed? My site_id is a Foreign key of a Site table in table auth_user of Django -
Django How to make the transition from one post to another and back
There is a model and posts attached to it. I can not figure out how to make the transition from one post to the next and back. I read many articles, but I did not find a suitable one for myself. Here is my code. How can this be done? Where did I make a mistake and how can I fix it? http://127.0.0.1:8000/seasons/season-1/episode-2 NoReverseMatch at /seasons/season-1/episode-2 NoReverseMatch at Reverse for 'episode-detail' with arguments '('', 'episode-1')' not found. 1 pattern(s) tried: ['seasons/(?P<seasonpost_slug>[-a-zA-Z0-9_]+)/(?P<episodepost_slug>[-a-zA-Z0-9_]+)\Z'] Error during template rendering previous return render(request, 'content/episode.html', { … Local vars current_episode <episode: episode-2> episodepost <QuerySet [<episode: episode-2>]> episodepost_slug 'episode-2' next_episode <episode: episode-3> previous_episode <episode: episode-1> request <WSGIRequest: GET '/seasons/season-1/episode-2'> seasonpost_slug 'season-1' class season(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... def __str__(self): return self.slug def get_absolute_url(self): return reverse('seasonpost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) class episode(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('SLUG')) ... cat = models.ForeignKey('season', on_delete=models.PROTECT, null=True) def __str__(self): return self.slug def get_absolute_url(self): return reverse('episodepost', kwargs={'seasonpost_slug': self.slug, 'episodepost_slug': self.slug}) Views def ContentHome(request): homepages=home.objects.all() season_menu=season.objects.all() seasonpages=season.objects.all() return render(request, 'content/home.html',{ 'season_menu':season_menu, 'home':homepages, 'season':seasonpages}) def ContentSeasons(request): seasonspages=seasons.objects.all() homepages=home.objects.all() season_menu=season.objects.all() seasonpages=season.objects.all() return render(request, 'content/seasons.html',{ 'season_menu':season_menu, 'home':homepages, 'seasons':seasonspages, 'season':seasonpages}) def ContentSeason(request, seasonpost_slug): seasonpages = get_list_or_404(season, slug=seasonpost_slug) homepages=home.objects.all() seasonspages=seasons.objects.all() season_menu=season.objects.all() episodepost = episode.objects.filter() seasonpages=season.objects.filter(slug=seasonpost_slug) …