Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have no errors in the apache log for deploying django, but my page doesn't load
Good morning everyone, I am deploying a django application on Apache and at the moment there are no errors in the LOG after I add the root folder after the first slash in the WSGIScriptAlias line /projeto_cad_usuarios C:/Apache24/htdocs/Cadastro/ project_cad_users/project_cad_users/wsgi.py But in the browser it does not load my application, it only shows the folders and files of the project. Below is the log: [Tue Jul 04 10:31:25.317454 2023] [mpm_winnt:notice] [pid 5672:tid 520] AH00455: Apache/2.4.57 (Win64) mod_wsgi/4.9.5.dev1 Python/3.11 configured -- resuming normal operations [Tue Jul 04 10:31:25.318481 2023] [mpm_winnt:notice] [pid 5672:tid 520] AH00456: Apache Lounge VS17 Server built: May 31 2023 10:48:22 [Tue Jul 04 10:31:25.318481 2023] [core:notice] [pid 5672:tid 520] AH00094: Command line: 'httpd -d C:/Apache24' [Tue Jul 04 10:31:25.320473 2023] [mpm_winnt:notice] [pid 5672:tid 520] AH00418: Parent: Created child process 3856 [Tue Jul 04 10:31:25.727677 2023] [wsgi:info] [pid 3856:tid 564] mod_wsgi (pid=3856): Initializing Python. [Tue Jul 04 10:31:25.740643 2023] [wsgi:info] [pid 3856:tid 564] mod_wsgi (pid=3856): Attach interpreter ''. [Tue Jul 04 10:31:25.748622 2023] [wsgi:info] [pid 3856:tid 564] mod_wsgi (pid=3856): Adding 'C:/Apache24/htdocs/Cadastro/env/Lib/site-packages' to path. [Tue Jul 04 10:31:25.765605 2023] [wsgi:info] [pid 3856:tid 564] mod_wsgi (pid=3856): Imported 'mod_wsgi'. [Tue Jul 04 10:31:25.768597 2023] [mpm_winnt:notice] [pid 3856:tid 564] AH00354: Child: Starting 64 worker … -
Django Multitenant - Populate connection list using default database
I have a Django Project with multitenant. Each client has is own database. I want to create a table in the default database containing the client. Something like this: class Tenant(models.Model): name = model.CharField(max_length=20) I want to use this model so that I can populate DATABASES setting or django connections and to avoid writing more code. How can I do it? -
Retrieve function for viewset without model
I am using object without RDS entry. Model class MyDummy(object): def __init__(self, **kwargs): for field in ('id', 'detail'): setattr(self, field, kwargs.get(field, None)) mydummys = { 1: MyDummy(id=1, detail={"test":"test"}), 2: MyDummy(id=2,detail={"test2":"test2"}) } Serializer class MyDummySerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) detail = serializers.JSONField(allow_null=True) def create(self, validated_data): return MyDummy(id=None, **validated_data) def update(self, instance, validated_data): for field, value in validated_data.items(): setattr(instance, field, value) return instance list function works well for now class MyDummyViewSet(viewsets.ViewSet): serializer_class = s.MyDummySerializer def list(self, request): serializer = s.MyDummySerializer( instance=m.mydummys.values(), many=True) return Response(serializer.data) However now I want to make retreive for url like api/mydummy/1 class MyDummyViewSet(viewsets.ViewSet): serializer_class = s.MyDummySerializer def list(self, request): serializer = s.MyDummySerializer( instance=m.mydummys.values(), many=True) return Response(serializer.data) def retrieve(self, request, pk=None): serializer = s.MyDummySerializer( instance=m.mydummys.values(), many=False) return Response(serializer.data) It returns, { "detail": null } I think I should narrowing by id in retrieve. How can I make it ? -
$ : The term '$' is not recognized as the name of a cmdlet, function, script file, or operable program
I'm trying to setup django but when I writevthe command an error appears in cmd : $ django-admin startproject new-app error :$ : The term '$' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 $ python manage.py startapp chatbot ~ CategoryInfo : ObjectNotFound: ($:String) [], CommandNotFoundException FullyQualifiedErrorId : CommandNotFoundException How can I solve this problem ? -
How to make django-tenants work with django-q
Django newbie here. I'm trying to make django-q work with django-tenants. I am getting this error: 13:38:41 [Q] ERROR relation "django_q_schedule" does not exist LINE 1: ...edule"."task", "django_q_schedule"."cluster" FROM "django_q_... ^ I assume that the issue is that django-q looks at the public schema and doesn't find the task and schedule table. Settings.py: SHARED_APPS = ( 'django_tenants', # mandatory 'companies', # you must list the app where your tenant model resides in 'accounts.apps.AccountsConfig', 'django.contrib.humanize', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) TENANT_APPS = ( # your tenant-specific apps 'django_q', 'loads', 'dispatchers', 'accounts.apps.AccountsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS] I also tried following django-tenants-q instructions, but the python3 manage.py mscluster command does not work. -
Error Sudo Docker Compose Yaml Error - Top-level object must be a mapping
I tried the command sudo docker compose run web django-admin startproject moneymattersweekly . and received the following: parsing /Users/eleahburman/Desktop/code/money-matters-weekly/docker-compose.yaml: Top-level object must be a mapping . Here is my yaml file version: "3" services: web: build: . command: python manage.py runserver 0.0.0.0:3000 volumes: - .:/code ports: - "3000:3000" and here is my Dockerfile : # syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ What is wrong with this? I tried adding version: "3" and version: '3' to my yaml and it did nothing. I also tried redownloading docker. -
Django - ManyToMany field with autocomplete functionality in admin
I have this model: class Foo(models.Model): name = models.CharField(max_length=200) number = models.BigIntegerField() description = models.TextField() related_foos = models.ManyToManyField('self', blank=True) I want to achieve an autocomplete functionality for the related_foos field in Django admin. I have tried this, but this does not work: class FooAdmin(admin.ModelAdmin): autocomplete_fields = ['related_foos'] search_fields = ["name", "number", "description", "related_foos"] admin.site.register(Foo, FooAdmin) While this gives the correct widget for autocomplete, the search itself does not work. Therefore, the autocomplete also does not work. When I try to look in the console, I see that it performs some kind of AJAX call but it gets the HTTP 500 error with this message: django.core.exceptions.FieldError: Unsupported lookup 'icontains' for ForeignKey or join on the field not permitted. Any ideas how to achieve the correct autocomplete functionality for a ManyToMany field with searching on the fields that I want? -
Filtering avg sum via OrderingFilter
I need to filter avg (non-model) field via OrderingFilter. My models.py class Product(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, verbose_name="store") sku = models.CharField(max_length=255, blank=True, default="", verbose_name="SKU") name = models.CharField(max_length=255, blank=True, default="", verbose_name="name") class ProductInfo(models.Model): default_related_name = "productinfo" product = models.OneToOneField("Product", on_delete=models.CASCADE, null=True, verbose_name="product") barcode = models.CharField(max_length=255, null=True, verbose_name="barcode") price = models.DecimalField(max_digits=7, decimal_places=2, default=Decimal(0), verbose_name="price") cost_price = models.DecimalField(max_digits=7, decimal_places=2, default=Decimal(0), verbose_name="cost price") vat = models.DecimalField(max_digits=3, decimal_places=1, default=Decimal(0), verbose_name="% tax") I filter Product via OrderingFilter My filters.py from products.models import Product from django_filters import OrderingFilter from django_filters.rest_framework import FilterSet class ProductFilter(FilterSet): order_by_field = "ordering" ordering = OrderingFilter( fields=( "name", (("productinfo__price"), ("price")), (("productinfo__barcode"), ("barcode")), ) ) class Meta: model = Product I need to calculate the profit from the sales. This can be done in a separate function or I can use an annotation. price-cost_price-taxes_sum=profit But this parameter is not a model field. Can I somehow add it to the filter? The goal is to get goods that bring more profit by sorting. -
Server static files from different machine with docker containers and nginx as reverse proxy
I have a two machines. First machine runs several docker containers (django(uwsgi), db and nginx). Second server runs also several docker containers ( django(dahpne), redis, db ). On first machine nginx serves static files from Django(uwsgi) everything work correctly. I'm trying to configure nginx to serve static files also from the second server. Without success. Please help me I'm out of ideas. I tried many things and my current configuration looks like: nginx (on first machine) map $http_upgrade $connection_upgrade { default upgrade; '' close; } ... server { listen 443 ssl; server_name ${DOMAIN} www.${DOMAIN}; access_log /var/log/nginx/access.log main; error_log /var/log/nginx/error.log; ssl_certificate /etc/letsencrypt/live/${DOMAIN}/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/${DOMAIN}/privkey.pem; include /etc/nginx/options-ssl-nginx.conf; ssl_dhparam /vol/proxy/ssl-dhparams.pem; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; location /static { alias /vol/static; } location / { uwsgi_pass ${P1_HOST}:${P1_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } location /dashboard { proxy_pass http://dashboardproject; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $host; #proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; location /dashboard/d2/static { alias /vol/web/static/dashboard/; #try_files $uri $uri/ =404; } } } Proxy docker compose ... proxy: build: context: ./proxy ... volumes: - certbot-web:/vol/www - proxy-dhparams:/vol/proxy - certbot-certs:/etc/letsencrypt - static-data:/vol/static networks: - p_internal_network volumes: certbot-web: proxy-dhparams: certbot-certs: postgres-data: static-data: ... And the configuration of docker … -
TypeError in Django view while using F expressions in queryset annotations
I have a Django view that handles search functionality in my application. It filters questions and codes based on a user's query and calculates relevance scores using Django's F expressions. However, I'm encountering a TypeError when trying to use the F expression in my queryset annotations. Here's the relevant code snippet from my `SearchResultView: class SearchResultView(TemplateView): template_name = 'codeisc/search_result_page.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['user'] = self.request.user if self.request.user.is_authenticated else None query = kwargs.get('query') keywords = query.split() questions = Question.objects.filter(Q(short_description__icontains=query) | Q(description__icontains=query)) for keyword in keywords: questions = questions.annotate( relevance_score=( F('short_description__icontains', keyword) + F('description__icontains', keyword) ) ) questions = questions.order_by('-relevance_score') context['questions'] = questions codes = Code.objects.filter(Q(short_description__icontains=query) | Q(code_text__icontains=query)) for keyword in keywords: codes = codes.annotate( relevance_score=( F('short_description__icontains', keyword) + F('code_text__icontains', keyword) ) ) codes = codes.order_by('-relevance_score') context['codes'] = codes return context When I try to run it I get this Error: Exception Type: TypeError Exception Value: F.__init__() takes 2 positional arguments but 3 were given and my models: class Code(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Code_Author") short_description = models.CharField(max_length=100, null=False, default="No Description Provided") code_text = models.TextField(blank=True, null=False) created_at = models.DateTimeField(default=timezone.now) TYPE_CHOICES = [ ("TXT", "TextFile"), ("PY", "Python"), ("JS", "Javascript"), ("C", "C"), ("CPP", "C++"), ("CS", "Csharp"), ("JV", "Java"), ] type = … -
Django crispy-forms TemplateDoesNotExist
I am new in Django, so I was trying structures in the book "Django for Beginners by William S Wincent" about how to attach crispy forms to my signup page! However, in the middle of my progress in the topic, I faced to TemplateDoesNotExist exception! Error: Error description Here is where the error raises: Error description And here is my settings.py configuration: ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', "accounts", "pages", ] CRISPY_TEMPLATE_PACK = "bootstrap4" ... django = 4.2.3 django-crispy-forms = 2.0 I've tried to create a Sign Up Page, configuring its views and urls properly to host crispy_forms in my project. Also crispy_forms(Version 2.0) is installed. Packages installed in my virtual environment -
How to enroll a studend in a course for in a django web app?
i hope somebody can provide a bit of advice. I need help figuring out how to connect a custom user with the course model, and enroll a customer into a course. We need to allow users to buy a course, register and consume the lessons. Everything about the course is working. It is rendering the courses, modules and lessons. Also all authentication part is okay, i have created a sepparate registraion view for registering a customer role. But i can't figure out how to connect the Course model with it's creator and customer who will buy and consume the course. This is the accounts app models.py file: from django.db import models # import abstract user from django.contrib.auth.models import AbstractUser # when using file upload path, the error appears when editing profile def file_upload_path(instance, filename): return f'user-{instance.id}/images/{filename}' # DEFINE OUR CUSTOM USER class User(AbstractUser): class Role(models.TextChoices): ADMIN = 'ADMIN', 'Admin' OWNER = 'OWNER', 'Owner' EMPLOYEE = 'EMPLOYEE', 'Employee' MODERATOR = 'MODERATOR', 'Moderator' CUSTOMER = 'CUSTOMER', 'Customer' email = models.EmailField(unique=True, max_length=50) username = models.CharField(unique=True, max_length=50) role = models.CharField(max_length=20, choices=Role.choices, null=True, blank=True) phone_number = models.CharField(max_length=20, null=True, blank=True) image = models.ImageField(upload_to=file_upload_path, default='default-images/profile.png', null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] agree_to_terms = models.BooleanField('I agree … -
Why I got an error 500 internal server when I deploy my Django project?
I just deploy my Django project in cpanel and now when I want to use my RegisterView to create a user after I POST JSON data with the register field required, the user is created in the database but it gives me a My RegisterView: class RegisterView(APIView): """ Register a new user. """ permission_classes = [AllowAny] def post(self, request): """ Getting the user's information for register. """ try: email = request.data["email"] username = request.data["username"] password = request.data["password"] confirm_password = request.data["confirm_password"] full_name = request.data["full_name"] simple_description = request.data["simple_description"] biography = request.data["biography"] profile_picture = request.FILES.get("profile_picture") if User.objects.filter(email=email).exists(): return Response(data={"error": "Email has been already used."}, status=status.HTTP_400_BAD_REQUEST) if User.objects.filter(username=username).exists(): return Response(data={"error": "Username has been already used."}, status=status.HTTP_400_BAD_REQUEST) if password != confirm_password: return Response(data={"error": "Passwords do not match."}, status=status.HTTP_400_BAD_REQUEST) user = User.objects.create( username=username, email=email, password=password, full_name=full_name, simple_description=simple_description, biography=biography, ) if profile_picture: user.profile_picture = profile_picture user.save() Notification.objects.create( author=user, title="Create account", description=CREATE_ACCOUNT_DESCRIPTION ) return Response(data={'message': 'User has been successfully created.'}, status=status.HTTP_200_OK) except RequestException: return Response(data={"error": "An error occurred. Please check your internet connection."}, status=status.HTTP_503_SERVICE_UNAVAILABLE) The JSON data i posted: { "email": "example@gmail.com", "password": "password123", "confirm_password": "password123", "full_name": "John Doe", "simple_description": "Tourist", "biography": "I love traveling.", "username": "johndoe" } I tied to create a user in the admin panel … -
Allow Case insensitive in Char form in Django
I have an model where i have an foreign key and char field, i want them to be save in unique together but Case insensitive over char field example (1, central) and (1, Central) both should be allowed to save If (1, central) is saved and when I am adding (1, Central) I am getting below error error Tags with this Rooms and Aws room_name already exists. MODEL.py class Tags(): Rooms = models.ForeignKey(Rooms, related_name='rooms') room_name = models.CharField( verbose_name=_('room_name'), max_length=100, null=False, blank=False, default="", ) class Meta: unique_together = (('Rooms', 'room_name')) -
Relation does not exist in Django
The backend of the app I'm working at is created with Django. When I updated a project from GitHub, I started to get such an error when I try to run the project via docker-compose. Traceback (most recent call last): perfect_cv_local_django | File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute perfect_cv_local_django | return self.cursor.execute(sql, params) perfect_cv_local_django | psycopg2.errors.UndefinedTable: relation "..." does not exist perfect_cv_local_django | LINE 1: SELECT COUNT(*) AS "__count" FROM "..." I've already tried to migrate the DB, but I keep getting the same mistake. P.S I'm working on frontend part of this app so I'm not really familiar with backend. -
Django error with "STATIC" and reverse for 'register' not found
Hey guys a fellow Django developer here. The static word is coming in red as an error. including the % and } <body id="bg" style="background-image: url({% static 'users/images/bg.png' %});"> Error recieved when server is running. Errors recieved in Editor. Base.html <!doctype html> {% load static %} <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!--Css Style --> <link rel="stylesheet" href="{% static 'users/static/css/main.css' %}" type="text/css"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <!--Font Link--> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&family=Open+Sans:wght@800&display=swap" rel="stylesheet"> </head> <body id="bg" style="background-image: url({% static 'users/images/bg.png' %});"> {% load static %} <nav class="navbar navbar-expand-lg navbar-dark bg-dark" id="main-navbar"> <div class="container"> <a class="navbar-brand" href="{% url 'home' %}"><img src="{% static 'images/in-logo-1.svg' %}" alt="" ></a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-link active" aria-current="page" href="#">Home</a> <a class="nav-link" href="#">Market</a> <a class="nav-link" href="#">Company</a> <a class="nav-link" href="#">Education</a> <a class="nav-link" href="#">Resouces</a> </div> <form class="d-flex" id="authstyle"> {% if user.is_authenticated %} <a href="{% url 'profile' %}" class="btn" style="color: white; background-color: #fd5e14;"type="submit" id="header-links"> Profile </a> <a href="{% url 'logout' %}" class="btn" style="color: white; background-color: #fd5e14;"type="submit" id="header-links"> Logout </a> {% else %} <a href="{% url 'register' %}" class="btn" style="color: white; background-color: … -
Django redirect ends up with an infinite loop
I have the following code in my urls.py: urlpatterns = [ path("admin/", admin.site.urls), re_path(r'^api/users/$', views_udf.users_list), re_path(r'^api/users/([0-9])$', views_udf.users_detail), re_path(r'^api/predictions/new', views_fp.create_prediction_link, name='new-path-prediction'), re_path(fr'^api/predictions/{link}', views_fp.create_prediction, name='new-prediction'), ] And the following code in my views.py: @api_view(["GET"]) def create_prediction(request): from datetime import date today = date.today().strftime("%b %d, %Y") prediction_text = create_prediction_text(today) entries = Prediction.objects.all() entries.delete() prediction = Prediction.objects.create(prediction_text=prediction_text) prediction.save() current_entries = Prediction.objects.all() serializer = PredictionSerializer(current_entries, context={'request': request}, many=True) return Response(serializer.data) @api_view(["GET"]) def create_prediction_link(request): return redirect(fr'^api/predictions/{link}') Done according to tutorials, redirecting ends up with an infinite redirect loop, which is weird given that: The page redirects to a different page, not to itself The view in the page in redirected page is different Should I have a different link basis? If not, what is the reason for the infinite loop happening? Did I miss something crucial in my code being inattentive? Found no similar questions here and on the web apart from intentional infinite redirect, ready to provide additional details -
ProgrammingError: column artgallery_artist.id does not exist
I started writing a Django app that will eventually lead to an art gallery store. I use custom user in this project. I created the Artist model in app artgallery and after makemigrations and migrate, I encountered this error when go to admin/artgallery/artist: ProgrammingError at /admin/artgallery/artist/ column artgallery_artist.id does not exist column artgallery_artist.id does not exist LINE 1: SELECT "artgallery_artist"."id", "artgallery_artist"."name_i... ^ Even though I deleted the migrations file several times and run makemigrations and migrate it again, the problem was not solved. I also checked the inside of the migrations file and saw that there is an id column. Artist model: def get_profile_img_upload_path(self): return f'profile_images'/{self.pk}/{"profile_image.png"} def get_default_profile_image(): return 'profile_images/dummy_image.png' class Artist(models.Model): name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) profile_image = models.ImageField( max_length = 255, upload_to = get_profile_img_upload_path, null = True, blank = True, default = get_default_profile_image, ) nickname = models.CharField(max_length=100, null=True, blank=True) bio = models.CharField(max_length=300, null=True, blank=True) goal = models.CharField(verbose_name="goal and motivation of artist", max_length=100, null=True) activity = models.CharField(choices = fields_of_art(), max_length=50) ''' Social Media ''' instagram_username = models.CharField(verbose_name="Instagram", max_length=50) twitter_username = models.CharField(verbose_name="Twitter", max_length=50) linkedin_username = models.CharField(verbose_name="Linkedin", max_length=50) pinterest_username = models.CharField(verbose_name="Pinterest", max_length=50) def get_instagram_urlpath(self): return f'https://www.instagram.com'/'{self.instagram_username}' def get_twitter_urlpath(self): return f'https://twitter.com'/'{self.twitter_username}' def get_linkedin_urlpath(self): return f'https://www.linkedin.com/in'/'{self.linkedin_username}' def get_pinterest_urlpath(self): return f'https://www.pinterest.com'/'{self.pinterest_username}' CustomUser model: class CustomUser(AbstractUser): … -
Login does not redirect to dashboard, rather it returns same login page
I have defined a view that redirect logged in users to their dashboard, but when I enter the login details on the login form, it just reloads and display the same login page but with empty field instead of redirecting to the dashboard. My views.py: def doctor_login_view(request): if request.method == 'POST': form = DoctorLoginForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(request, email=email, password=password) print(user) if user is not None: login(request, user) return redirect('doctor_dashboard') # Redirect to the doctors' dashboard else: form.add_error(None, 'Invalid email or password.') else: form = DoctorLoginForm() return render(request, 'doctor_login.html', {'form': form}) My forms.py: class DoctorLoginForm(forms.Form): email = forms.EmailField(max_length=255) password = forms.CharField(widget=forms.PasswordInput) My urls.py: path('doctor/login/', views.doctor_login_view, name='doctor_login'), Login Template: {% extends 'base.html' %} {% block content %} <div class="container"> <h2>Doctor Login</h2> <form method="post" action="{% url 'doctor_login' %}"> {% csrf_token %} <!-- Login form fields --> <div class="form-group"> <label for="email">Email Address</label> <input type="email" class="form-control" id="email" name="email" required> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" id="password" name="password" required> </div> <button type="submit" class="btn btn-primary">Login</button> </form> <p class="mt-3">Don't have an account? <a href="{% url 'doctor_registration' %}" class="btn btn-link">Register</a></p> </div> {% endblock %} I have tried to check if the url path is correct and the post method … -
Passing slug field into template form action and views
I have two models first is Service that contains all of provided services and second is the Order for users if they want to order any kind of Service. service model class Service(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(unique=True, allow_unicode=True, default='-') current_queue = models.PositiveSmallIntegerField(null=True, blank=True, default=0) max_queue = models.PositiveSmallIntegerField(null=True, blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) return super(Service, self).save(args, kwargs) def __str__(self) -> str: return f'{self.title} {self.current_queue}' order model from django.conf import settings User = settings.AUTH_USER_MODEL class OrderService(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) description = models.TextField(null=True, blank=True) def __str__(self) -> str: return f"{self.user} {self.service}" what I want to do is : When a user choose any service, service name and the user gets by my views automatically (user by his request and service by its slug), but the problem is when I try to get the form, the slug field doesn't work, I think the problem is the template because when I send no action it doesn't do anything but when I send the slug into action it launch error and says no url match for this url views.py in Order @login_required(login_url='LOGIN') def order_for_service(request, slug): if request.method == "POST": form = UserOrder(request.POST) if form.is_valid(): object = … -
Django - In Memory Channels Layers vs Heroku Redis
Considering adding some push notifications to a web app built with Django hosted on Heroku. I am pondering the pros and cons of InMemoryChannelLayer vs Heroku Redis. 'Heroku & Redis' seems is a better option for scalability. But budget is limited, so InMemoryChannelLayerhave a better appeal right now! The use of the app is limited to a few users to measure a few things, and probably wouldn't require full scalability option at this stage. On the scalability front however, wondering what sort of scalability people refer to? I saw that in-memory storage is not suitable for application with high traffic or large number of users at the same time and can consume a significant amount of memory causing potential performance issues. I am wondering at what sort of level of use am I likely to run into this sort of problem? Are we talking 1000 users at the same time? 100? 10? EDIT - Obviously, I am assuming I cannot use Redis without paying for the addon. If I am wrong, that would be a good argument in favour of Redis :) -
How to create app in Django in Visual Studio Code?
I wrote in terminal in Visual Studio Code like this command: python manage.py startapp shop. I was counting to create new Django app but it threw an error like this: C:\Users\vpolo\AppData\Local\Programs\Python\Python311\python.exe: can't open file 'C:\Users\vpolo\Documents\courses\manage.py': [Errno 2] No such file or directory. Can You help me? I've tried to create a new Django app. -
Wagtail 2.10 update breaks SVGs
I have an old codebase written using wagtail at work and I have to update the wagtail version from 2.9 to 2.10. I tried this thing and the icons from the cms literally break. They do not show up at all. Looks like the 2.10 update migrates the font icons to svg icons. The HTML looks good, but there is no svg path to reference to for some reason. <svg class="icon icon-folder-open-inverse icon--menuitem" aria-hidden="true"> :before <use href="#icon-folder-open-inverse"></use> </svg> From other examples, looks like I should have the svgs with paths defined at the top of the body tag, but there are none. Tried to rerun collectstatic, but with no success. Does anyone have any idea why or how to solve this? -
Django get authors in serie through book-object
For a hobby project I am building a django-app that displays the books in a private collection. I have 3 models relevant to this question: Serie, Book and Author: from django.db import models class Author(models.Model): pass class Book(models.Model): authors = models.ManyToManyField(Author) class Serie(models.Model): books = models.ManyToManyField(Book) If I have a Serie-object, what is a good way to get all authors in the serie? (Some series in the collection have books written by different authors) -
Please explain the essence of the task related to Django models
Good afternoon! I ask for help in explaining the task of using DRF. The task is to develop an authorization and news server. I basically understand what I need to do, but here are some steps from the explanation I don't understand. I need to have a Users model (which has a username field and an encrypted password field). I can't figure out if I need to use the built-in Django - User model or create this model myself. It is also written in the explanation that admin users may not overlap with users in the Users table I tried to create my own Users class, but I couldn't figure out which type of field to choose for the password.