Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SASS/SCSS django
PHOTO - show mistake(https://i.stack.imgur.com/wXCf5.png) Why got red underline (photo) as some problem in code, is there are some mistake? But it work properly... And the same question to sass in link... What to do for remove this "mistake". {% load sass_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="{% sass_src 'css/main.scss' %}" rel="stylesheet" type="text/css"/> <title>Django Sass</title> </head> <body> <h1>WORK</h1> </body> <html> -
name is not passing through a function to another function in django
i am trying to pass a variable called name to pass to a function which is present in another function. I want to pass the variable name to the function plane and check if the values are matching with any of the names in my database. my views.py is from django.shortcuts import render,redirect from django.contrib.auth.forms import AuthenticationForm from .models import Logs,Plane from .forms import Login from django.contrib import messages from django.contrib.auth import authenticate, login ,logout from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from django.http import HttpResponse import json from django.http import JsonResponse # Create your views here. def loger(request): global name formy = AuthenticationForm() c=[] a=Logs.objects.all() if request.method == 'POST': formy = AuthenticationForm(data=request.POST) name=request.POST.get('username') password = request.POST.get('password') obj=Logs() obj.get_special_combination_value for b in a: if name == b.name and password == b.password: return redirect('ticket',pk=b.id) return render(request,'project/loger.html',{'formy':formy,'a':a}) def homepage(request): form=Login() if request.method=='POST': form=Login(request.POST) if form.is_valid(): user=form.save() plane_instance = Plane(name=user.name, password=user.password) plane_instance.save() return redirect('ticket',pk=user.pk) return render(request,'project/homepage.html',{'form':form}) def ticket(request,pk): tic=Logs.objects.get(id=pk) return render(request,'project/ticket.html',{'tic':tic}) def forgor(request): a=Logs.objects.all() if request.method=='POST': username=request.POST.get('name') password=request.POST.get('password') obj=Logs() obj.get_special_combination_value Logs.objects.filter(name=username).update(password=password) return redirect('homepage') return render(request,'project/forgor.html',{'a':a}) def plane(request): print(name) a=Logs.objects.all() b=Plane.objects.all() for c in b: if name==c.name: log_instance=Plane.objects.get(id=c.id) plane_instance=Plane.objects.get(id=c.id) for d in a: if name==d.name: plane_instance1=Logs.objects.get(id=d.id) if request.method == 'POST': checkbox_dict_json = request.POST.get('checkboxDict') … -
Python Dramatiq - how can I get environment variables?
I'm trying to get environment variables using dramatiq: @dramatiq.actor def create_instance(): subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"] credential = DefaultAzureCredential() But I get this error: KeyError: 'AZURE_SUBSCRIPTION_ID' I think this means dramatiq can't get my environment variables. I tried to get them before calling the function and passing them as arguments: subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"] credential = DefaultAzureCredential() create_instance.send(subscription_id, credential) @dramatiq.actor def create_instance(subscription_id, credential): ... But the problem is the credential can't be passed as an argument: Object of type DefaultAzureCredential is not JSON serializable Is there any solution? Thanks -
Django/Wagtail Language Redirection not working for 3 letter language code (kri)
I have set up Wagtail (latest) for multi-language. Works fine with Portuguese (pt), but I'm trying to work for Krio, which has a 3 character language code: kri. I have had to add Krio manally to LANG_INFO etc, and this works fine in the Wagtail UI, allowing me to set up alternate homepages for pt and kri, but when it comes to do the language redirecting, it fails to redirect to the kri translation. Is it possible I have missed a setting? Can the redirection logic handle 3 letter codes? My language settings: WAGTAIL_I18N_ENABLED = True USE_L10N = True LANGUAGES = [ ('en-GB', "English (Great Britain)"), ('en-US', "English (United States)"), ('en-CA', "English (Canada)"), ('pt', "Portuguese"), ('kri', "Krio (Sierra Leone Creole)"), ] WAGTAIL_CONTENT_LANGUAGES = [ ('en-GB', "English (British)"), ('kri', "Krio (Sierra Leone Creole)"), ('pt', "Portuguese"), ] EXTRA_LANG_INFO = { "kri" : { 'bidi': False, 'code': 'kri', 'name': 'Sierra Leonean Creole (Krio)', 'name_local': 'Krio', }, } LANG_INFO = dict(django.conf.locale.LANG_INFO, **EXTRA_LANG_INFO) django.conf.locale.LANG_INFO = LANG_INFO My middleware: MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "allauth.account.middleware.AccountMiddleware", "wagtail.contrib.redirects.middleware.RedirectMiddleware", ] My urls patterns: urlpatterns = [ # path('django-admin/', admin.site.urls), path('cms/', include(wagtailadmin_urls)), path('documents/', include(wagtaildocs_urls)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Translatable URLs # These will … -
Problem accessing server through .onion domain
I tried to access a django server I was running on my virtual machine (Ubuntu 22.04.3) through an onion domain from my host OS(Windows 11) First I installed tor and edited my torrc file and added these lines: HiddenServiceDir /var/lib/tor/hidden_service/ HiddenServicePort 8002 127.0.0.1:8002 then I saw my host name in /var/lib/tor/hidden_service/hostname. root@soroush-VirtualBox:/home/soroush/Desktop/dw# cat /var/lib/tor/hidden_service/hostname jn46lvmv4uu7bjfveoax.............rxv6ljid.onion then I started a django project and edited settings.py to allow all host names ALLOWED_HOSTS = ['*'] then I started a django server on my 8002 port python manage.py runserver 127.0.0.1:8002 then I tried to access my django server using the onion link. I copied the url in my tor browser on my host OS. but nothing loaded. I didn't even get any requests in my django server. I even tried using tor browser on my phone with a different network but that didn't work neither. the tor service is running and my django server works ok when I use my locan IP (127.0.0.1:8002). but when I try to access it through onion domain I can't. what am I doing wrong? I tried to access my django server through an onion domain but I couldn't -
Django Class Based View: Deny access to future dates unless logged in
I have a Promotion model containing a published_date field. I would like to restrict access to future promotions to logged in users who are 'previewing' their promotion. class Promotion(models.Model): title = models.CharField(max_length=100, blank=False, null=False) ... promotion_date = models.DateField(blank=False, null=True) At the moment I'm running a simple Class Based DetailView: class PromotionDetailView(generic.DetailView): model = Promotion context_object_name = 'book' template_name = 'PromoManager/book_detail.html' But I am unsure how or when to intercept this request and add the condition for non logged in users to redirect if promotion_date is greater than today. I currently have simple_tag which returns a bootstrap alert highlighting future promotions but this is purely visual. in_the_future = timezone.now().date() if hasattr(book, 'promotion_date') and book.promotion_date > in_the_future: return ...appropriate message... If I was doing it via Function Based Views I would apprach it with an if statement combined with a redirect. I considered the same approach via DetailView/TemplateView and get_context_data but this doesn't feel right. How can I best intercept the request and redirect the page for non-logged in users if the promotion_date is in the future? -
Django BaseDataTableView - filter_queryset method not work
I am using BaseDatatableView and DataTable jquery. I've already written several views for BaseDatatableView and there were no problems until I had to override the 'prepare_results' and 'render_column' methods. I need to present the results of instance methods in a table, so I overwrite the methods of the BaseDatatableView class. This is my code in views.py class MyModelDatatable(BaseDatatableView): model = MyModel columns = ['field1', 'field2', 'id'] columns_searched = [col for col in columns if col != 'id'] def get_initial_queryset(self): return self.model.objects.all() def filter_queryset(self, qs): print('test') # not displayed search_text = self.request.GET.get('search[value]', None) if search_text: search_terms = search_text.split() query = Q() for col in self.columns_searched: or_conditions = Q() for term in search_terms: or_conditions |= Q(**{f'{col}__icontains': term}) query |= or_conditions qs = qs.filter(query) return qs def prepare_results(self, qs): data = [] for item in qs: item_str = str(item) data.append({ 'field1': item_str, 'field2': item.field2, 'id': item.id }) return data def render_column(self, row, column): if column == 'field2': return row.date.strftime('%Y-%m-%d') return super(OrderDatatable, self).render_column(row, column) def get(self, request, *args, **kwargs): return self.get_json_response() def get_json_response(self): draw = int(self.request.GET.get('draw', 1)) total_records = self.get_initial_queryset().count() total_display_records = total_records start = int(self.request.GET.get('start', 0)) length = int(self.request.GET.get('length', 10)) end = start + length data = self.prepare_results(self.get_initial_queryset()[start:end]) response = { 'draw': draw, … -
SSL Certification Requirements Safety Question
I am using Heroku and Redis in a production environment built with Django and have been getting errors with SSL. At first I had this issue: A rediss:// URL must have parameter ssl_cert_reqs and this must be set to CERT_REQUIRED, CERT_OPTIONAL, or CERT_NONE I then tried adding ?ssl_cert_reqs=CERT_REQUIRED To my CELERY_RESULT_BACKEND Which then returned this error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain I then changed the ?ssl_cert_reqs to equal CERT_NONE and this has solved all issues completely. My question is if this fix is safe from any attacks or if this has completely got rid of the SSL certificates. I have read on a few pages that people have used this to fix their issue but I am working on a production app and do not want to compromise on safety. Any help would be greatly appreciated. Thank you, Liam -
Python issue with redis hostname not resolved in docker
I seem to have issues while trying to setup redis instance via python/django. I have a lot of containers running in docker-compose and while other containers are able to connect properly, when trying with Django I get: Step 11/16 : RUN python3 /home/allianceserver/myauth/manage.py collectstatic ---> Running in 749d9931dadb [30/Oct/2023 08:59:47] INFO [allianceauth.eveonline.providers:181] ESI client will be loaded on-demand [30/Oct/2023 08:59:47] ERROR [allianceauth.authentication.task_statistics.helpers:44] Failed to establish a connection with Redis. This EventSeries object is disabled. Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 264, in connect sock = self.retry.call_with_retry( File "/usr/local/lib/python3.9/site-packages/redis/retry.py", line 46, in call_with_retry return do() File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 265, in <lambda> lambda: self._connect(), lambda error: self.disconnect(error) File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 595, in _connect for res in socket.getaddrinfo( File "/usr/local/lib/python3.9/socket.py", line 954, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -2] Name or service not known During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/allianceauth/authentication/task_statistics/helpers.py", line 41, in get_redis_client_or_stub if not redis.ping(): File "/usr/local/lib/python3.9/site-packages/redis/commands/core.py", line 1216, in ping return self.execute_command("PING", **kwargs) File "/usr/local/lib/python3.9/site-packages/redis/client.py", line 533, in execute_command conn = self.connection or pool.get_connection(command_name, **options) File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 1086, in get_connection connection.connect() File "/usr/local/lib/python3.9/site-packages/redis/connection.py", line 270, in connect raise ConnectionError(self._error_message(e)) redis.exceptions.ConnectionError: … -
Django REST framework: get last related object
I am trying to get the last related object in a Django REST framework view. With the current implementation I am getting this error - but I am not sure if this is the correct approach: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer. I have this two models (little bit cleaned up): class Device(models.Model): name = models.TextField() def get_last_status(self): return self.status.last() class DeviceStatus(models.Model): class eDeviceStatus(models.TextChoices): OFFLINE = 'F', _('Offline') ONLINE = 'L', _('Online') device = models.ForeignKey(Device, related_name='status', on_delete=models.CASCADE) status = models.CharField(max_length=1, choices=eDeviceStatus.choices, default=eDeviceStatus.OFFLINE) last_update = models.DateTimeField() with this Device view: class DeviceViewSet(ModelViewSet): serializer_class = DeviceSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): return Device.objects.filter(owner=self.request.user) def perform_create(self, serializer): serializer.save(owner=self.request.user) and this Device serializer: class DeviceSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') last_status = serializers.SerializerMethodField() class Meta: model = Device fields = ['url', 'id', 'name', 'last_status'] def get_last_status(self, obj): s = obj.get_last_status() serializer = DeviceStatusSerializer(s) return serializer.data I would like to have in my api the last status (field: last_status) from the DB. But I am failing to have it correctly implemented. How can I have the last_status correctly set? -
Specify lookup_url_kwarg in the nested route using drf-nested-routers
Using drf-nested-routers we have implemented many nested routes that go two levels in depth. Just as in the documented examples: /clients/ /clients/{pk}/ /clients/{client_pk}/maildrops/ /clients/{client_pk}/maildrops/{pk}/ /clients/{client_pk}/maildrops/{maildrop_pk}/recipients/ /clients/{client_pk}/maildrops/{maildrop_pk}/recipients/{pk}/ However, I don't like the inconsistency in the 4th line. How can I make the lookup_url_kwarg be maildrop_pk there too? /clients/{client_pk}/maildrops/{maildrop_pk}/ If I set the lookup_url_kwarg in the MailDropViewSet to maildrop_pk, then it appears correctly in this route, but the nested routes for MailRecipient become: /clients/{client_pk}/maildrops/{maildrop_maildrop_pk}/recipients/ /clients/{client_pk}/maildrops/{maildrop_maildrop_pk}/recipients/{pk}/ I want to have a consistent naming across all nested routes. -
DRF ViewSet always returns HTTP 200
I'm new to DRF. This is my ViewSet: class AccountViewSet(viewsets.ViewSet): def list(self, request): queryset = User.objects.all() serializer = AccountSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, email=None): queryset = User.objects.all() user = get_object_or_404(queryset, email=email) serializer = AccountSerializer(user) return Response(serializer.data) I have two email addresses in the database. My API client is httpie. When I send a GET request to http://127.0.0.1:8000/api/accounts/ I get back those two emails. So this part works fine. However, when I provide an email address that doesn't exits in the database (as Params or Headers), I again get those two emails instead of 404. I did a little bit of research and change the code like this: class AccountViewSet(viewsets.ViewSet): def list(self, request): queryset = User.objects.all() serializer = AccountSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, email=None): queryset = User.objects.all() try: user = get_object_or_404(queryset, email=email) except User.DoesNotExist: return Response(status=404) serializer = AccountSerializer(user) return Response(serializer.data) Again, 200 with those two emails. Even when I provide an email that does exists, I get both in response. I can't figure out what I'm missing. -
How to maintain data integrity in django
How can I maintain data integrity in django? I see that there is optimistic locking, or mvcc, but I don't know how to implement it. Also, are these the same thing? I think I can implement pessimistic locking using select_for_update. I heard that F() gets the latest information on the database side and adds values to it to maintain consistency, but is it ok for simultaneous cases? I asked chatgpt and chatgpt said that mvcc and optimistic locking are implemented by default by the database, is this true? -
I want to select a record from table to go another page in django
i have a table in my template have a many records that retrieved from the database, each row have a select option that when a user selects an option and click on the button, it must be take him to another page. my template.html: <table id="tblToExcl" class="table table-striped table-bordered table-sm"> <thead class="thead-dark"> <tr> <th>رقم الكتاب</th> <th>تاريخ</th> <th>تاريخ الاضافة</th> <th>ملاحظات</th> <th>اﻻجراء</th> </tr> </thead> <tbody> {% for doc in docs %} <tr> <td>{{ doc.number }}</td> <td>{{ doc.date|date:"Y-m-d"}}</td> <td>{{doc.created_at|date:"Y-m-d"}}</td> <td>{{ doc.note }}</td> <td>{{ doc.status }}</td> <td> <a href="/edit/{{ doc.id }}"><span class="glyphicon glyphicon-pencil" ><i class="far fa-edit" style="color: #116014;"></i></i></span></a> <a href="/delete/{{ doc.id }}"><i class="far fa-trash-alt" style="color: #bf5a40;"></i></a> <a href="/download/{{ doc.id }}"><i class="far fa-file-pdf" style="color: #204a87;"></i></a> </td> <td> <select id="choices" style="background-color:DodgerBlue; color: white;"> <option value="/deliver/{{ doc.id }}/{{doc.number}}/{{doc.date}}/{{doc.note}}/{{doc.document}}/{{doc.status}}">الموارد البشرية</option> <option value="">المالية</option> </select> <button type="button" id="go-button" class="button"><span>تحويل</span></button> </td> </tr> {% endfor %} </tbody> </table> urls.py: urlpatterns = [ path("", views.index, name="index"), path("show", views.show, name="show"), path("docs", views.documents, name="docs"), path("maward-show", views.show_maward, name="maward-show"), path("deliver/<int:id>/<int:number>/<str:date>/<str:note>/<path:document>/<str:status>", views.deliver, name="deliver"),] **views.py: ** def deliver(request, id, number, date, note, document, status): print(document) var = Maward.objects.create(id=id, number=number, date=date, note=note, document=document, status=status) time.sleep(3) return redirect("/show") i added a javascript code to my template as following: <script> $(document).ready(function() { $('#go-button').click(function() { // Get the selected choice var selectedChoice = … -
Django migrations not working properly in ecs
I have a django application on ecs. I push the code to github along with the migrations files. I have a script that runs the migrate command when I deploy. I can create a superuser but when I try to login to admin panel I get relation user_user does not exist error, but when I connect to the RDS directly form my local system I can login, but not from the domain which is attached to the elb -
Unable to run the django server
i'm trying to laucn the django with the command python manage.py runserver but i got this error: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is Fa is False. here is my settings project: DEBUG = True ALLOWED_HOSTS = [] i've tried all the solution proposed by others on the relative question with mine but the difference is that i've not change the settings variable Debug so their solution don't work for me. like to change the value of list settings variable ALLOWEG_HOSTS but it's not working for me. -
Django-Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
There some questions related to this but no answers are helped. I often come accross errors like that but cannot figure out what causes problems. My projects has been running fine but suddenly all of them which using postgresql are stopped, giving following error. Traceback (most recent call last): File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/var/www/crm/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) File "/var/www/crm/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 275, in get_new_connection connection = self.Database.connect(**conn_params) File "/var/www/crm/venv/lib/python3.8/site-packages/psycopg/connection.py", line 728, in connect raise ex.with_traceback(None) psycopg.OperationalError: connection is bad: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/var/www/crm/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/var/www/crm/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.8/contextlib.py", line 74, in inner with self._recreate_cm(): File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/transaction.py", line 198, in __enter__ if not connection.get_autocommit(): File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 464, in get_autocommit self.ensure_connection() File "/var/www/crm/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/var/www/crm/venv/lib/python3.8/site-packages/django/db/utils.py", … -
pathlib.py" is overriding the stdlib module "pathlib"
Creating a Django app in a condo virtual environment(djenv) created the html, updated views.py and urls.py when updating settings.py, getting a problem for this line of code from pathlib import Path "C:\test1\djenv\Lib\pathlib.py" is overriding the stdlib module "pathlib" when I renamed pathlib.py, Django doesn't work properly Is there a way override the stdlib pathlib and use the virtual environments pathlib.py or are there any other fixes for this problem -
Django join tables with two or more FK conditions
I want to join models B and C with two conditions, data_a and human in model_B, and data_a and autor in model_C, but how do I do it with Django ORM class user(models.Model): data_1 = models.CharField(max_length=60) data_2 = models.SmallIntegerField() data_3 = models.IntegerField(blank=True, null=True) class model_A(models.Model): data_1 = models.CharField(max_length=60) data_2 = models.SmallIntegerField() data_3 = models.IntegerField(blank=True, null=True) class model_B(models.Model): data_a = models.ForeignKey(model_A) human = models.ForeignKey(user) data_2 = models.IntegerField() class model_C(models.Model): data_a = models.ForeignKey(model_A) author = models.ForeignKey(user) data_1 = models.CharField(max_length=5) data_2 = models.IntegerField() additional conditions on join in django I've seen this place, but I don't know if it's applicable to my situation -
Django bulk_create() with inexistent ForeignKey
I have 2 models. For simplicity, I deleted all unnecessary fields. class User(models.Model): id = models.CharField(max_length=36, primary_key=True, null=False) age = models.IntegerFiels(default=-1) and class Device(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Through the API, I receive information about devices and create a list with devices. devices = [] for device_data in data: devices.append( Device( user_id=device_data("user_id") ) ) Once I have the list of devices, I add it to the database. Device.objects.bulk_create(devices, ignore_conflicts=True) The problem is that if, when creating a Device, I specified a user_id that is not in the database, I will get a crash because I am trying to link with a non-existent id. Now to get around this I do the following: devices = [] users = [] for device_data in data: users.append( User( id=device_data("user_id", age = -1) ) ) devices.append( Device( user_id=device_data("user_id") ) ) Then, when saving: User.objects.bulk_create(users, ignore_conflicts=True) Device.objects.bulk_create(devices, ignore_conflicts=True) User.objects.filter(age=-1).delete() How can I make sure that when saving, if the specified user_id does not exist, this device is not added? Or add a device, while creating a User with this user_id, but with the rest of the fields by default, and then, at the end, I will delete all users, and with them all devices, where age … -
Django queryset not filtering correctly based on end_date and current_time
I'm encountering an issue with my Django project where I have a model Service with an end_date field. I want to filter services based on whether their end_date is in the future, but I'm facing unexpected behavior. model.py: from django.db import models from apps.user.models import CustomUser from apps.location.models import City from django.utils import timezone class Area(models.Model): name = models.CharField(max_length=70,unique=True) def __str__(self): return self.name class Type_of_housing(models.Model): name = models.CharField(max_length=100,unique=True) areas = models.ManyToManyField(Area,blank=True) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class Subcategory(models.Model): name = models.CharField(max_length=100,unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name class Service(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) type_of_housing = models.ForeignKey(Type_of_housing, on_delete=models.CASCADE) area = models.ForeignKey(Area, on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) location_address = models.CharField(max_length=100) city = models.ForeignKey(City,on_delete=models.CASCADE) is_visible = models.BooleanField(default=True) end_date = models.DateTimeField() def __str__(self): return self.title def save(self, *args, **kwargs): if not self.end_date: # Calculate the end date as 14 days from the current date and time self.end_date = timezone.now() + timezone.timedelta(days=14) super().save(*args, **kwargs) class ServiceImage(models.Model): service = models.ForeignKey(Service, on_delete=models.CASCADE) image = models.ImageField(upload_to='service_images/') def __str__(self): return f"Image for Service: {self.service.description}" and view.py: def service_list(request): current_time = timezone.now() print("Current Time:", current_time) services = Service.objects.all() for service … -
How to get python implemented in Django
I have already defined a function and now wanted to use it on my website and have already tried this <img src="{{ get_pop_img(0) }}" class="card-img-top" alt="jpg"> and my function is def get_pop_img(number): response = requests.get('https://api.jikan.moe/v4/top/manga?filter=bypopularity') img = response.json()['data'][number]['images']['jpg']['image_url'] return img but i only getting errors I also importet my python file in the views.py -
Why does the variable not change its value after admin action has been triggered?
I have two admin actions for the Feedback Model in the admin panel, approved and unapproved. The value for approved in the Feedback Model is default to False. When admin use the action to approve, it turns this value to True and unapproved will turn True to False. This works on the admin panel on the deployed site, however when I'm trying to do the test for the admin.py I ran into an error where the test_approve is passing, while the test_unapprove failed. When I try to debug the test_unapprove I set the approved value as True and then check the value of feedback.approve before the response and it came out as True, which is expected. Then I check again after the response and it still came out as True where it should come out as False. Please have a look if you have any clue why this is happening. If you need any more info please let me know! admin.py @admin.register(Feedback) class FeedbackAdmin(admin.ModelAdmin): list_display = ('username', 'body', 'lesson_id', 'created_on', 'approved') list_filter = ('approved', 'created_on') list_display_links = ('username',) search_fields = ['username', 'user_id', 'body'] actions = ['approved_feedback', 'unapproved_feedback'] def approved_feedback(self, request, queryset): queryset.update(approved=True) def unapproved_feedback(self, request, queryset): queryset.update(approved=False) test_admin.py class TestAdmin(TestCase): … -
Django data problem : new salons always with all users
Problem is that I want to create a new salon, so beginning with only the user who created it. But, when I consult my django database (with localhost:8000/admin/), I notice that every user (UserSalon) is present in every 'Salon'... However, when I print all the users of this salon in the terminal, I can see there is only this one. So wtf? I have this in my models.py: class UserSalon(models.Model): # etc. class Salon(models.Model): salon_users = models.ManyToManyField(UserSalon) # etc. and this is a part of code from my view.py: user_salon_id = request.session.get('user_salon_id') if request.method == 'POST': create_salon_form = CreateSalonForm(request.POST) try: user_salon = UserSalon.objects.get(id=user_salon_id) except UserSalon.DoesNotExist: user_salon = None if create_salon_form.is_valid(): created_id_salon = create_salon_form.cleaned_data['id_salon'] created_key_salon = create_salon_form.cleaned_data['key_salon'] new_salon = Salon.objects.create(id_salon=created_id_salon, key_salon=created_key_salon) new_salon.salon_users.clear() new_salon.salon_users.add(user_salon) new_salon.save() -
How to assign the result of a conditional to a variable in a Django template?
There are two django models, "Production" and "Season". Production has a foreign key to Season (i.e. in rails-speak Season has_many Productions, Production belongs_to Season). I have a detail view for Production, and the page sidebar has the list of all productions in the current season. {% for p in season.production_set.all %} <li class="nav-item"> <a class="nav-link d-flex align-items-center gap-2" href="{% url 'production_detail' season.id p.id %}"> {{p.name}} </a> </li> {% endfor %} {% endblock %} But I would like the nav item to be disabled for the current production being viewed. That means adding the 'disabled' class to a element, and setting the "aria-current" attribute as well. I can use if/else takes, but it ends up being quite verbose and also repetitive, given that I need this logic twice in the same html tag <a class="nav-link d-flex align-items-center gap-2 {% if p.id is not production.id %} active {% else %} disabled {% endif %}" aria-current="{% if p.id is production.id %}true{%else%}false{%endif%}" href="{% url 'production_detail' season.id p.id %}"> So I tried to assign a variable like {% with p.id is not production.id as current %} but no syntax I have tried allowed me to assign a boolean expression to a variable. Is there a …