Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why am I getting NoReverseMatch Error - Django
I'm having a reverse error in Django when visiting another URL "comment_post_view" The error is coming from when I visit the comment_post_view page; I'm thinking maybe it's because of the username in url, but I don't know how to go on with it. How can I get it done? URL path('p/<username>/status/<post_id>/', comment_post_view, name='comment_post_view'), path('settings/archive-post/', archive_post_view, name='archive_post_view'), path('archive-post/<id>/', archive_view, name='archive_view'), VIEWS.PY @login_required def comment_post_view(request, username, post_id): page_title = "Post Comment" username_url = get_object_or_404(User, username=username) user_post = get_object_or_404(Post, pk=post_id, poster_profile=username_url) # All users following posts user_profile = request.user.profile posts = Post.objects.filter( Q(id=user_post.id) ).order_by("?").select_related('poster_profile', 'poster_profile__profile').distinct() post_data = [] for post in posts: poster_profile = post.poster_profile.profile mutual_followers_qs = user_profile.following.filter( id__in=poster_profile.following.values_list('id', flat=True) ) post_data.append({ 'post': post, 'mutual_followers': mutual_followers_qs[:3], # You can select any number of followers here 'mutual_count': mutual_followers_qs[2:].count() }) ............................ @login_required def archive_post_view(request): page_title = "Archive Post" posts = Post.objects.filter( Q(is_hide=request.user) ).select_related('poster_profile', 'poster_profile__profile').distinct() post_data = [] for post in posts: poster_profile = post.poster_profile.profile post_data.append({ 'post': post, }) .......................... @login_required def archive_view(request, id): post = get_object_or_404(Post, id=id) if post.is_hide.filter(id=request.user.id).exists(): post.is_hide.remove(request.user) else: post.is_hide.add(request.user) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) TEMPLATE archive_post_view.html {% for item in post_data %} {% if request.user == item.post.poster_profile %} <a href="{% url 'site:archive_view' item.post.id %}">Archive post</a> # Current user {% else %} # Error pointing to β¦ -
How to Safely Upgrade a Package in Django (e.g., django-jalali from 1.0.2 to 2.0.0) Without Breaking Existing Code?
I'm currently working on upgrading an older Django project and I have both a specific and a general question about package upgrades. π Specific Question: Iβm using django-jalali-date==1.0.2 in one of my older projects, and I'd like to upgrade it to 2.0.0 because of some important improvements and features. But before I do that, I want to be sure this won't break anything β especially in forms, models, templates, or static files ({{ form.media }}, template filters like |to_jalali, etc.). So, how can I safely compare the two versions, test compatibility, and ensure everything keeps working as expected? Are there any known breaking changes between these versions? How can I verify if imports like JalaliDateField, AdminJalaliDateWidget, or template tags still work? Any advice on testing or migration steps would be great! π General Question: More broadly, whatβs the best way to safely upgrade any Python/Django package without risking regressions? What strategies do you use when upgrading major versions (e.g., from v1.x.x to v2.x.x)? For example: Do you manually check changelogs and diffs? Do you run tests or use tools like pipdeptree, pytest, or diff tools? Do you create a staging environment first? Any tips for checking backward compatibility (BC)? Iβd β¦ -
Issue with Modelform
This is what I got after coding my ModelForm What could have caused that, I kept trying to debug it, but everything seems right, didnβt know where the errors are coming from This was the error I got after running the server, the first form worked out, as I was trying to redirect to another form, this error threw up raise ValueError ("ModelForm has no model class specified.") ValueError: ModelForm has no model class specified. I want it to work, Iβm actually trying to build a web marketplace with Django, the only issue I go was the modelForm error and it really makes me worried -
Django cannot create record with correct foreign key to CharField with spaces in middle - getting surrounded by single and double quotes like "'a a'"
First of all - I understand that CharField is rather bad primary key, but it's unique in-game name, good 2 use as-is in many places, and may contain spacees. And IMHO the problem will repeat with non pkey field anyway 3 models - source, and two references. The first reference works perfectly in admin UI with the same code, the second - unworkanle during creating record class PilotUsers(AbstractUser, PermissionsMixin): first_name = None last_name = None username = None ed_name = models.CharField(primary_key=True,max_length=60,null=False,blank=False,unique=True,verbose_name='Pilot name in Elite Dangerous', ) squadron_tag = models.ForeignKey('Squadrons', verbose_name='Frontier squadron tag', on_delete=models.PROTECT, default='----') email = models.EmailField(unique=True) USERNAME_FIELD = 'ed_name' REQUIRED_FIELDS = ['email'] objects = PilotUserManager() def __str__(self): return self.ed_name class Meta: app_label = 'common_pages' This is working in admin UI - image below class Cert(DetailsModel, AbstractCert): organizational_unit_name = models.ForeignKey('common_pages.PilotUsers', verbose_name='ED Pilot Name', on_delete=models.PROTECT) class Meta(AbstractCert.Meta): abstract = False swappable = swapper.swappable_setting("posts", "Cert") This class ActionFeed(models.Model): pkey = models.BigAutoField(primary_key=True) received = models.DateTimeField(verbose_name='Date-time') ed_name = models.ForeignKey('common_pages.PilotUsers', verbose_name='ED Pilot Name', on_delete=models.CASCADE) #skipped raw_data = models.JSONField(verbose_name='Raw Data', null=False) is unworkable during creating new record print (f'Pilot = {pilot}') record = ActionFeed(received= ts, ed_name=pilot, #skipped raw_data = entry) The error is Cannot assign "'Al L****]'": "ActionFeed.ed_name" must be a "PilotUsers" instance. Attn - Single β¦ -
Why is `djlint` warning me to add `<meta>` tags even though the file is linted?
I'm working on a Django web project and using djlint to lint and format my HTML templates. I ran the following command to lint one of my templates: djlint html_files/analytics/reports/report_new.html And I got this output: Linting 1/1 files βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ 00:00 html_files/analytics/reports/report_new.html ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ H030 3:0 Consider adding a meta description. <html lang="{{ lang H031 3:0 Consider adding meta keywords. <html lang="{{ lang Linted 1 file, found 2 errors. Even though it says "found 2 errors", the file is actually linted and formatted just fine. Thereβs no crash, and the formatting is applied. What I want to understand: Why are these tagged as errors, when theyβre really just recommendations? Should these be treated as warnings or ignored? Is it best practice to always include <meta name="description"> and <meta name="keywords"> in Django templates β even for internal dashboards? How can I suppress or ignore these suggestions if I donβt want to include them? Let me know if there's a way to configure djlint to stop flagging these without affecting actual linting or formatting. What Iβve tried: I checked the official djlint documentation, and these are listed under SEO-related suggestions. I also tried this command and it worked to silence the warnings: djlint html_files/analytics/reports/report_new.html β¦ -
Web application creating
I am making my own web application which includes many functionalities similar to instagram. Can I build it by just Django framework can someone suggest me what tools or what else I must learn or use . -
psycopg2.errors.UndefinedTable: relation "committees_setting" does not exist
Error: ProgrammingError at /admin/committees/setting/ relation "committees_setting" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "committees_setting" ^ Request Method: GET Request URL: http://localhost:8000/admin/committees/setting/ Django Version: 4.0.8 Exception Type: ProgrammingError Exception Value: relation "committees_setting" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "committees_setting" ^ Exception Location: /usr/local/lib/python3.8/site-packages/django/db/backends/utils.py, line 89, in _execute Python Executable: /usr/local/bin/python Python Version: 3.8.17 Python Path: ['/app', '/app', '/usr/local/lib/python38.zip', '/usr/local/lib/python3.8', '/usr/local/lib/python3.8/lib-dynload', '/usr/local/lib/python3.8/site-packages', '/app/administration', '/app/administration'] My models: Settings: """Settings Committees models""" # Django from django.db import models # Models from administration.utils.models import BaseModel # Exceptions from administration.committees.exceptions import ( SettingsImproperlyConfigured, ) class Setting(BaseModel): """ Settings Committees model A Settings Committees Model contains business information about the committee. """ committee = models.OneToOneField( "committees.Committee", on_delete=models.CASCADE, related_name="settings" ) settings = models.JSONField() def __str__(self): """Return committee name""" return f"{self.committee}' settings" def get_setting(self, key, default=False): """Return dynamic key setting""" return self.settings.get(key, default) def late_fee_settings(self): """Return late fee setting""" late_fee_settings = self.settings.get("late_fee", False) if not late_fee_settings: raise SettingsImproperlyConfigured("late_fee not fount") return late_fee_settings def late_fee_is_active(self): """Return late fee setting""" late_fee_settings = self.late_fee_settings() return late_fee_settings.get("active", False) def late_fee_percentage(self): """Return late fee setting""" late_fee_settings = self.late_fee_settings() late_fee_percentage = late_fee_settings.get("percentage", False) if not late_fee_percentage: raise SettingsImproperlyConfigured("late fee percentage not fount") return late_fee_percentage def late_fee_has_penalty_fee(self): """Return late β¦ -
How to correctly add a custom '--dry-run' argument to a Django Extensions `runjob` command?
I have a custom Django management job created using django_extensions that deletes old database records. To avoid unintended deletions, I want to add a --dry-run argument to simulate deletions without actually removing data. However, when I execute the command with: uv run python manage.py runjob delete_recordings --dry-run I receive this error: manage.py runjob: error: unrecognized arguments: --dry-run Here's how my simplified job class currently looks: from django_extensions.management.jobs import HourlyJob import logging logger = logging.getLogger(__name__) class Job(HourlyJob): @classmethod def add_arguments(cls, parser): parser.add_argument( '--dry-run', action='store_true', help='Execute the job in simulation mode without deleting any data.', default=False, ) def execute(self, *args, **options): dry_run = options.get('dry-run', False) if dry_run: logger.info("Executing in DRY-RUN mode.") # Logic here to delete records or simulate deletion based on dry_run I followed the Django Extensions documentation to add a custom argument (--dry-run). I expected that when running the command with --dry-run, it would recognize the argument and simulate the operation, logging the intended deletions without performing them. However, the command line returns an error indicating that the argument is not recognized. It seems that Django Extensions isn't picking up the custom argument defined in my job class. What is the correct way to add a custom argument (--dry-run) to β¦ -
assign a custom field order_sl
I'm working with a Django model where I need to assign a custom field order_sl that should increment from the last existing value with a specific filter. Here's what I'm doing currently: prev_ordr = Order.objects.filter(abc).values("order_sl").first() if prev_ordr: new_order_sl = prev_ordr.get("order_sl") else: new_order_sl = 100000 ins.order_sl = F("order_sl") + (new_order_sl + 1) ins.save() ins.refresh_from_db() But I believe this approach is problematic: It pulls the last value into Python instead of handling it in the DB. Itβs not thread-safe and likely to break under race conditions if multiple inserts happen at the same time. I'm using PostgreSQL, and I want to ensure that each new row gets a unique, sequential order_sl based on the highest existing value or a dedicated sequence. The order_sl field is not the primary key, and I donβt want to make it an AutoField. β Whatβs the best, Django-safe, PostgreSQL-optimized way to handle this? Would a raw SQL sequence be better? Or should I use select_for_update() with a transaction block? Thanks! -
Understanding F expression in Django
What I have done is - prev_ordr = Order.objects.filter(abc).values("order_sl").first() if prev_ordr: new_order_sl = prev_ordr.get("order_sl") else: new_order_sl = 100000 ins.order_sl = F("order_sl") + (new_order_sl + 1) ins.save() ins.refresh_from_db() return But I'm not sure about this, this is loading the previous value into the python and not directly managing the database (i think so), as it should be in the case of F expression and it may fail race condition. Can you let me know the correct way, I have to increase the value by 1 (from the last row) in the new row. Thanks -
Django DisallowedHost Error Despite Domain Being in ALLOWED_HOSTS
Problem Description I'm getting a DisallowedHost error in my Django production environment, even though the domain is clearly listed in my ALLOWED_HOSTS setting. I am using traefik. Error Message: django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'api.tuitionwave.com'. You may need to add 'api.tuitionwave.com' to ALLOWED_HOSTS. Current Configuration: My production.py settings file includes: ALLOWED_HOSTS configuration ALLOWED_HOSTS = ["api.tuitionwave.com", "localhost", "127.0.0.1", "django"] # Trust proxy headers USE_X_FORWARDED_HOST = True USE_X_FORWARDED_PORT = True # Security settings SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True) What I've Tried Verified that api.tuitionwave.com is explicitly listed in ALLOWED_HOSTS List item Confirmed the settings file is being loaded correctly Checked that there are no whitespace issues in the domain name And here is my traefik.yml File details http: routers: web-router: rule: "Host(`api.tuitionwave.com`)" entryPoints: - web middlewares: - redirect service: django web-secure-router: rule: "Host(`api.tuitionwave.com`)" entryPoints: - web-secure middlewares: - default-headers service: django tls: # https://docs.traefik.io/master/routing/routers/#certresolver certResolver: letsencrypt -
How to intercept a form submit in websocket connection?
I have "inherited" a piece of code from a chat application. I would like to add some custom checks on the user input upon submission, allowing the submit to be aborted on client side if necessary. I have created a submit handler javascript function in order to execute the checks and transformations, including preventDefault as first instruction: async handleSubmit(event) { event.preventDefault(); // Prevent default form submission ... I have linked the handler to the form: <form class="pg-chat-input-bar" ws-send @submit="handleSubmit($event)" enctype="multipart/form-data" > Yet, no matter what, the form is submitted immediately when the submit button is pressed. The server receives the form in parallel to / before the handler being executed. I can assess that the handler is triggered and does what it is supposed to do but unfortunately the form has already been submitted. I tried @submit.prevent, @submit.stop and even combined both but it doesn't change the outcome. I found many posts asking to capture/intercept/interrupt a form submit but the solutions are as simple as what I tried. What am I doing wrong? As I am not starting from scratch I would prefer modify the code as little as possible and use what is already there. Could it be related β¦ -
How to compare a DecimalField value in Django templates for conditional logic?
I'm working on a Django project where users have an Account model with a DecimalField named account_balance. I'm trying to conditionally show a KYC verification link if the user's balance is exactly 100, and show an error if it's less than that. Hereβs my setup: class Account(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) account_balance = models.DecimalField(max_digits=10, decimal_places=2) class KYC(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField() views.py: def settings(request): kycs = KYC.objects.filter(user=request.user) context = { "kycs": kycs, } return render(request, 'public_pages/settings.html', context) template: {% for kyc in kycs %} <p>Your identity is important to the community</p> {% if kyc.user.account.account_balance == 100 %} <a href="{% url 'Kyc_Form' kyc.slug %}">Update KYC</a> {% elif kyc.user.account.account_balance < 100 %} <div class="alert alert-danger"> You need at least 100 coins before applying for KYC. </div> {% endif %} {% endfor %} But this block never renders either the button or the error message. The only thing I see is the static text: <p>Your identity is important to the community</p> I tried printing the balance outside the logic: <p>Balance: {{ kyc.user.account.account_balance }}</p> And it shows something like 100.00. I assume it's a Decimal issue. How can I properly compare a DecimalField like account_balance in the Django template to check β¦ -
Will requests to my site lag and work slowly in django while waiting for celery results?
I use django to create pdf to docx converter using pdf2docx library, and I need to wait a celery task to done and get result from it. Will my site lag and work slowly if a lot of users use it, and how can i do it better? here my views and celery code views.py ''' from django.shortcuts import render from django.http import JsonResponse, HttpResponse from django.http.request import HttpRequest import tempfile import os from .forms import FileUploadForm from django.views.decorators.csrf import csrf_protect from . import tasks from celery.result import AsyncResult @csrf_protect def main_page(request: HttpRequest): if request.method == "GET": # get form = FileUploadForm(request.POST, request.FILES) context = { "form": form } return render(request, 'main/main_page.html', context) if request.method == 'POST' and request.FILES.get('file'): form = FileUploadForm(request.POST, request.FILES) if form.is_valid(): # get file file = request.FILES['file'] size_limit = 2 * 1024 * 1024 # save pdf with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file: if file.size > size_limit: for chunk in file.chunks(): temp_file.write(chunk) else: temp_file.write(file.read()) temp_pdf_path = temp_file.name # start convertor task task: AsyncResult = tasks.convert_pdf_to_docx.delay(temp_pdf_path) # get docx path temp_docx_path = task.wait(timeout=None, interval=0.5) converted_file_name = str(file).replace(".pdf", "") # read docx file and set it in response with open(temp_docx_path, 'rb') as docx_file: file_data = docx_file.read() response = HttpResponse(file_data, β¦ -
django-celery-results: error ModuleNotFoundError: No module named 'django_celery_results'
I try to run "celery -A myproj worker -l info" and it gives me the error ModuleNotFoundError: No module named 'django_celery_results'. All dependencies are installed (django, celery, django-celery-results, redis). I tried to run it with admin rights, but it didn't help as well. I tried changing the python version from 3.13 to 3.11, but also without result. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_celery_results',] -
How to store the refresh token in HttpOnly cookie with Google OAuth2 (PKCE flow) in Django?
I'm using Django with drf_social_oauth2 and oauth2_provider for Google OAuth2 authentication. Iβve successfully implemented the PKCE authorization flow. Step 1: Frontend redirects to: GET /api/v1/o/authorize/?client_id=<client_id>&response_type=code&redirect_uri=http://127.0.0.1:5173/callback&code_challenge=<challenge>&code_challenge_method=S256 Step 2: Frontend exchanges code at: POST /api/v1/o/token/. Backend responds with: { "access_token": "...", "expires_in": 36000, "refresh_token": "...", β this is what I want to move into a cookie ... } My configuration: # urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("api/v1/o/", include("oauth2_provider.urls", namespace="oauth2_provider")), ] # settings.py (snippets) INSTALLED_APPS = [ ... 'oauth2_provider', 'social_django', 'drf_social_oauth2', ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.google.GoogleOAuth2', 'drf_social_oauth2.backends.DjangoOAuth2', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '<your-client-id>' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '<your-client-secret>' REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "oauth2_provider.contrib.rest_framework.OAuth2Authentication", "drf_social_oauth2.authentication.SocialAuthentication", ), } LOGIN_REDIRECT_URL = "/" What works: PKCE is working. Google OAuth2 authorization is integrated using social-auth-app-django and drf-social-oauth2. I can extract the original Google access_token from the user's social_auth.extra_data. What I want: I want to store the refresh_token in a secure HttpOnly cookie instead of returning it in the JSON response β to reduce XSS risks. I would be grateful for any advice, code examples on how to solve this, or references to sources where a solution can be found. -
celery chord callback executes before tasks completes
I have a celery workflow, as presented in the above image. I am facing a scenario where the parent_task_callback is executed before all the sub_parent_task callbacks are executed. None of these tasks has ignore_result set to false nor have I globally set it to false. What am I missing? The code looks like this: @app.task def sub_parent_task(): chord(child_tasks_list)(sub_parent_task_callback.si()) @app.task def parent_task(): chord(sub_parent_tasks_list)(parent_task_callback.si()) -
How to handle error reporting and validation of uploaded files using django-formset?
Short version I'm using django-formset to create a contact form that includes a file upload field. When an incorrect file is selected, no error message is shown. When uploading the form with an incorrect file, the field is cleared and a "Please either submit a file or check the clear checkbox, not both" error is thrown for this field, which is inaccurate. Because the field is cleared I cannot validate it anymore and return a descriptive error message. Is there any documentation that describes how this should be handled? Long version I want to custom validate file uploads while using django-formset. Initially, I'm mainly looking to validate image files, but later other types as well. Problem one Error messages do not show when selecting invalid files. Upon selecting a file that is too large, nothing happens (no errors are shown, no POST request is sent, GUI is not updated). Here I would at least expect a message to display "File size is too big" or so. When selecting a file with an invalid extension, a POST request is sent and the GUI is updated to show the selected file (with or without a valid thumbnail). However, no error message is β¦ -
UnicodeDecodeError when connecting to PostgreSQL using psycopg2, despite UTF-8 encoding everywhere
I'm trying to connect to a local PostgreSQL database using psycopg2 in Python. Here's the code I'm using: import psycopg2 params = { 'dbname': 'database_name', 'user': 'user_name', 'password': 'mypassword', 'host': 'localhost', } for k, v in params.items(): print(f"{k}: {v} (type={type(v)}, encoded={v.encode('utf-8')})") try: conn = psycopg2.connect(**params) print("Connexion OK") conn.close() except Exception as e: print("Connexion Erro") print(type(e), e) The printed output confirms that all parameters are strings and UTF-8 encoded. However, I still get the following error: Connexion Erro <class 'UnicodeDecodeError'> 'utf-8' codec can't decode byte 0xe9 in position 103: invalid continuation byte I also checked the server and client encoding on PostgreSQL using: SHOW server_encoding; SHOW client_encoding; Both return UTF8. Given that all inputs are UTF-8 and the database is configured for UTF-8, I don't understand why this error occurs. Has anyone encountered this before or has an idea of where this byte 0xe9 might come from? What else should I check? -
Seeking a Clear Roadmap for Learning Python and PHP as a Junior Developer (with Remote Work Goals) [closed]
Seeking a Clear Roadmap for Learning Python and PHP as a Junior Developer (with Remote Work Goals) Body: Hello everyone, Iβm a junior developer currently learning both Python and PHP, and I find myself a bit confused about which path to focus on or how to organize my learning. I'm still a student, and my primary goal is to gain enough skills to start working remotely from home β ideally through freelancing platforms or remote internships. I'm looking for a clear and structured roadmap that can guide me in becoming job-ready in either or both languages (Python with frameworks like Django or Flask, and PHP with Laravel). Iβd like to understand: What steps should I take to build a solid backend skill set? What technologies or tools should I prioritize (e.g. databases, APIs, deployment)? Should I focus on one language or is it okay to learn both in parallel? What kind of projects should I build to gain real-world experience? What are the best freelancing platforms or websites for beginners? How can I showcase my skills effectively to land small jobs or internships? If anyone has a well-organized learning roadmap, or professional advice based on your own experience starting out β¦ -
What are web servers exactly and why do we use app servers if we have web servers?
I am new to the field of devops i always get confused between app servers and web server (mostly with app servers). Also why do we need app servers if we have web servers. please explain me both the concepts in easy language but in a technical way so that i can map properly by using examples of uswgi and nginx as app and webs servers respectively -
How can I create a grouped set of elements for Grouped Radio Buttons
How can I create a set of elements to place in views? GROUPED_CHOICES I have a list of elements. [m1-x, m2-x] - the number of repetitions of each group name - the number of elements to group [m1,m1, m1, m1, m2, m2 ] - all group names that must belong to the choices elements. [q, w, e, r, t, y] - choices elements [(βqβ, 'q), (βwβ, βwβ), (βeβ, βeβ),(βrβ, 'r), (βtβ, βtβ), (βyβ, βyβ)] I took this from chatgpt. but I don't know yet how to create such a set of elements. GROUPED_CHOICES = [ ('Fruits', [ ('apple', 'Apple'), ('banana', 'Banana'), ]), ('Vegetables', [ ('carrot', 'Carrot'), ('lettuce', 'Lettuce'), ]), ] from django import forms class FoodForm(forms.Form): food = forms.ChoiceField( choices=GROUPED_CHOICES, widget=forms.RadioSelect ) {% for group_label, group_choices in form.food.field.choices %} <fieldset> <legend>{{ group_label }}</legend> {% for choice_value, choice_label in group_choices %} {# Get the radio input manually using the field's id_for_label logic #} {% with field_id=form.food.auto_id %} {% set widget_id = field_id|string + '_' + choice_value %} {% endwith %} <label for="{{ widget_id }}"> <input type="radio" name="{{ form.food.name }}" value="{{ choice_value }}" id="{{ widget_id }}" {% if form.food.value == choice_value %}checked{% endif %}> {{ choice_label }} </label><br> {% endfor %} </fieldset> β¦ -
How to get mutual followers (mutual friend) for users - Django
How do I get mutual followers (friends of friends) with request.user to be displayed for each users posts, I was able to display the count for mutual followers for each users posts on newsfeed. How can I get it done? What I tried: I was able to do this but I do not think it is the best way because when I use slice to show three mutual users images it does not work properly for all users. This is what I tried: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) profile_pic = models.ImageField(upload_to='UploadedProfilePicture/', default="ProfileAvatar/avatar.png", blank=True) following = models.ManyToManyField( 'Profile', # Refers to the User model itself symmetrical=False, # If A follows B, B doesn't automatically follow A related_name='followers', # Reverse relationship: get followers of a user blank=True, ) class Post(models.Model): poster_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, blank=True,null=True) def following_view(request): posts = Post.objects.filter( Q(poster_profile__profile__followers__user=request.user)).order_by("?").distinct() mymutual_followers = request.user.profile.following.filter(id__in=request.user.profile.following.values_list('id', flat=True)) {% for post in posts %} {% for user_following in mymutual_followers %} {% if user_following in post.poster_profile.profile.following.all|slice:"3" %} <img src="{{ user_following.profile_pic.url }}" class="hover-followers-img"/> {% endif %} {% endfor %} {% endfor %} The code above is what I tried and it worked, but add slice:"3" to show just 3 images do not work properly for some users, so β¦ -
How can I insert additional text elements through a loop into the set of choices form elements in the template?
How can I move the iterable value (radio) from the outer loop to the inner one, bypassing the inner loop iteration? How can I get the value (radio) of the outer loop. I have a nested loop that generates additional fields. The value from the outer loop. I plan to get the value from the outer loop not 30 times - but how many times in the outer loop 5 times. How can I skip the inner iteration? I have been thinking for several days how to make such a scheme. I have a choices field. I am trying to insert section names between them. I can just have 25 choices elements. And I want to divide them into groups. For example, into several groups and implement names for each group. Something similar to a table with categories. In the example in the figure, from 1 to 11 these are choices elements and between them the name of the group by which they are divided. Moreover, each time the number of choices elements is different, as is the grouping. How can I insert additional text elements through a loop into the set of choices form elements in the template? <fieldset> β¦ -
Job hunting advice for a self-taught dev feeling stuck
I'm a self-taught full-stack web developer. I've been learning and building projects for about a year now using technologies like Python (Django) and React.js. Now that I feel somewhat confident with my skills, I think it's time to start looking for a job. But here's my problem, I genuinely don't know how to start the job hunting process. It feels overwhelming, and to be honest, I'm a bit frightened to take that first step. Iβve been procrastinating because I feel uncertain, and when I spoke with a friend whoβs also learning, he said he feels the same way. I'm not sure what I should be doing right now: Should I be applying to junior roles directly? Do I need to work more on open source? How do I know when Iβm βreadyβ? Whatβs the best way to approach recruiters or companies? If any of you have gone through this stage or have tips on how to get started with the job huntβespecially as a self-taught developer, Iβd really appreciate your advice.