Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why do filters affect the result of StringAgg?
I'm using StringAgg and order as follows: # Get order column & annotate with list of credits if request.POST.get('order[0][name]'): order = request.POST['order[0][name]'] if order == 'credits_primary': releases = releases.annotate(credits_primary=StringAgg( 'credits__entity__name', delimiter=', ', filter=Q(credits__type='primary'), ordering='credits__id' )) elif order == 'credits_secondary': releases = releases.annotate(credits_secondary=StringAgg( 'credits__entity__name', delimiter=', ', filter=Q(credits__type='secondary'), ordering='credits__id' )) else: order = 'title' # Order releases if request.POST.get('order[0][dir]') == 'desc': releases = releases.order_by(F(order).desc(nulls_last=True), 'title') else: releases = releases.order_by(F(order).asc(nulls_last=True), 'title') for release in releases: try: print(release.credits_primary) except: pass try: print(release.credits_secondary) except: pass This in itself works exactly as expected: the ordering is what I expect, and print returns the values I expect. However, when I apply filters before this, it starts behaving strangely. Namely, sometimes it's fine and still works as expected, sometimes each credits__entity__name is repeated a random number of times, sometimes the annotation just returns None even though there are values. I can't figure out a pattern here. Below are the filters I'm applying, note that exclude as far as I can tell does not cause this problem: if request.POST.get('entity'): releases = Release.objects.filter(credits__entity=request.POST['entity']) else: releases = Release.objects.all() records_total = releases.count() # Filter by type if request.POST.get('type'): query = Q() for type in loads(request.POST['type']): if type in Release.TYPES_P_TO_S: query.add(Q(type=Release.TYPES_P_TO_S[type]), Q.OR) releases … -
Why is the data-tags attribute not preserved in my Django form widget? autoComplete DAL Select2
I'm using a CharField with a custom widget (ListSelect2) from the django-autocomplete-light library. I have a set of data-* attributes, including data-tags, that I want to be passed to the HTML output, but it doesn't seem like the data-tags attribute is being preserved or rendered correctly in the final after form is saved. industry_type = forms.CharField( widget=autocomplete.ListSelect2( url='/career-listings/industry-autocomplete/', attrs={ 'class': 'w-full px-4 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition duration-200', 'data-placeholder': 'Industry', 'data-minimum-input-length': 1, 'data-theme': 'tailwindcss-3', 'data-tags': 'true', # The attribute I'm trying to preserve 'id': 'id_industry_type', }, forward=['name'], ), required=True, ) What happens instead: The data-tags attribute does not appear in the HTML after form is saved. The field Things I've tried: I added data-tags to the attrs dictionary of the widget. I ensured that the widget is being properly rendered in the template. The data only data-tags is not preserved on form is submitted. -
Getting list of distinct ManyToManyField objects
Given these models: class Format(models.Model): name = models.CharField(unique=True) # More fields... class Release(models.Model): formats = models.ManyToManyField(Format, blank=True) # More fields... When I have a queryset of Releases (e.g. through releases = Release.objects.filter(foo='bar')), how do I get a list of the formats in that queryset, as objects and distinct? Neither of the following achieve this: # produces a list of dicts with IDs, not distinct e.g. [ { 'formats': 1 }, { 'formats': 2 }, { 'formats': 1 } ]: formats = releases.values('formats') # produces a list of IDs, not distinct, e.g. [ 1, 2, 1 ]: formats = releases.aggregate(arr=ArrayAgg('platforms'))['arr'] The only way I can think of is manually creating a list by looping through the IDs, checking if it already exists in the list, and if not adding it with formats.append(Format.objects.get(id=the_id)), but I would really like to avoid doing that, if possible. -
(fields.E331) Field specifies a many-to-many relation through model, which has not been installed
When I run makemigrations I get the error teams.Team.members: (fields.E331) Field specifies a many-to-many relation through model 'TeamMember', which has not been installed. from django.db import models from django.conf import settings from common import TimestampMixin from users.models import User class Team(models.Model, TimestampMixin): name = models.CharField(max_length=100) owner = models.ForeignKey( User, related_name='owned_teams', on_delete=models.CASCADE ) members = models.ManyToManyField( User, through='TeamMember', related_name='teams' ) def __str__(self): return self.name class TeamMember(models.Model, TimestampMixin): user = models.ForeignKey( User, on_delete=models.CASCADE ) team = models.ForeignKey( Team, on_delete=models.CASCADE ) def __str__(self): return f"{self.user} in {self.team}" I don't get why it's happening because the 'teams' app is installed and both Team and TeamMember is in the same file. Any ideas? -
Getting error message running Django server
I’m not able to run python manage.py runserver. I was able to run python manage.py migrate successfully. I even changed ASGI_APPLICATION = "MyProject.asgi.application" to ASGI_APPLICATION = "routing.application" which didn’t work. Here is the error I get show_sunset_warning() System check identified no issues (0 silenced). March 28, 2025 - 17:51:56 Django version 5.1.7, using settings 'MyProject.settings' Starting ASGI/Daphne version 4.1.2 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Exception in thread django-main-thread: Traceback (most recent call last): File "/home/corey-james/Arborhub/MyProject/venv/lib/python3.12/site-packages/daphne/management/commands/runserver.py", line 29, in get_default_application module = importlib.import_module(path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 995, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "/home/corey-james/Arborhub/MyProject/MyProject/asgi.py", line 12, in <module> import arborchat.routing File "/home/corey-james/Arborhub/MyProject/arborchat/routing.py", line 3, in <module> from . import consumers File "/home/corey-james/Arborhub/MyProject/arborchat/consumers.py", line 2, in <module> from channels.exceptions import StopConsumer ImportError: cannot import name 'StopConsumer' from 'channels.exceptions' (/home/corey-james/Arborhub/MyProject/venv/lib/python3.12/site-packages/channels/exceptions.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.12/threading.py", line 1075, in _bootstrap_inner self.run() File "/usr/lib/python3.12/threading.py", line … -
why does the terminal say PATCH but no change in database
in my webpage, i update the request details to approve or reject. but it does not change in the status and still shows pending. the problem is, in my terminal it says PATCH so I though that means change and the database has been changed. but when I run my SQL shell, it still shows pending . what would the problem be? this is my handlestatusupdate code in the frontend: **const handleStatusUpdate = async (newStatus: 'approved' | 'rejected') => { if (!selectedRequest?.id) return; try { const response = await fetch(`${API_URL}/requests/${selectedRequest.id}/`, { method: 'PATCH', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ status: newStatus }), }); if (!response.ok) { throw new Error('Failed to update request status'); } const updatedRequest = await response.json(); setRequests(requests.map(req => req.id === selectedRequest.id ? updatedRequest : req )); setShowModal(false); } catch (err: any) { setError(err.message || 'Failed to update status'); } }; ** what other code would i need to share? the backend? -
How to create django site variables (NOT constants)?
I need to add a variable to Django. Important detail: I need a variable, not a constant, so simply adding it to settings.py is not an option. It is highly desirable to be able to change its value from the site admin panel. What is the most Django way to do this? -
How to run Django migrations in Visual Studio 2022
I have created a Django project in my Visual Studio solution. The db.sqlite3 file was also created. There are a few classes in models.py. class Question(models.Model): q_id = models.IntegerField() text = models.CharField(max_length=500) class Option(): option_num = models.IntegerField() text = models.CharField(max_length=1000) When I right click on the project, there are these options - Make Migrations, Migrate & Create Superuser. When I execute Django Make Migrations, in the terminal it says Executing manage.py makemigrations, but nothing happens. Then I execute Migrate. It says, a command is already running. The __init__.py isn't updated. I also tried, executing this command in VS Terminal, but there is no response. python manage.py makemigrations -
How can I implement jaeger with django project to view traces in grafana?
I have a legacy django project in python 2 where I needed to implement jaeger in it. How can I do that, Can anyone guide me on the same? python 2.7 django-1.11.1 -
Is it possible to use python-social-auth's EmailAuth with drf-social-oauth2 for registration
I have a facebook authentication in my project, and I've set up some pipelines. So It would be nice for non-social email registration to also utilize these pipelines. I tried adding EmailAuth to the authentication backends list, but I don't know what view to use now for registratioin. So, is it possible (or reasonable) to use EmailAuth with drf-social-oauth2 for non-social registration, and if so, how do I do it? -
Django Search Query Vulnerable to XSS - How to Prevent It?
I am working on a Django search functionality, and I noticed that when I pass JavaScript code in the URL query parameter, it executes on the page. Problem When I enter the following URL in my browser: http://127.0.0.1:8000/search/?q=%3Cscript%3Ealert(%27Hacked!%27)%3C/script%3E it shows an alert box with "Hacked!". I suspect my site is vulnerable to Reflected XSS. views.py from django.shortcuts import render def search_view(request): q = request.GET.get("q", "") # Get query parameter return render(request, "search.html", {"q": q}) search.html <h1>Search Results for: {{ q }}</h1> <!-- Displays the search query --> If I enter <script>alert('Hacked!')</script> in the search box, the JavaScript executes on the page instead of being displayed as plain text. What I Need Help With Why is this happening? What is the correct way to prevent XSS in this case? Does Django provide a built-in security mechanism for this? I appreciate any guidance on securing my search functionality. -
here i have some models and its linked with other models. each model is dependant with other model but now its not depending
[enter image description here][1][here before selecting sub department i have to select main department and sub comes under main department.][2] [1]: https://i.sstatic.net/3GSQjtkl.png [2]: https://i.sstatic.net/Tp9kg2uJ.png these are the models. models.py class Department(models.Model): department_name = models.CharField(max_length=255) # ✅ Correct field company_name = models.ForeignKey(CompanyName, on_delete=models.CASCADE) status = models.CharField(max_length=20, choices=[('active', 'Active'), ('inactive', 'Inactive')]) def __str__(self): return self.department_name class SubDepartment(models.Model): sub_department_name=models.CharField(max_length=100,null=False,blank=False) department_name=models.ForeignKey(Department,on_delete=models.CASCADE) company_name=models.ForeignKey(CompanyName,on_delete=models.CASCADE) status=models.CharField(max_length=20, choices=[('active','Active'),('inactive','Inactive')]) def __str__(self): should i make any change in forms or views? forms.py class DepartmentForm(forms.ModelForm): class Meta: model = Department fields = ['department_name', 'company_name', 'status'] class SubDepartmentForm(forms.ModelForm): class Meta: model = SubDepartment fields = ['sub_department_name', 'department_name', 'company_name', 'status'] i already give one to many into the fields but its not working as dependant. here when i select the department the corresponding sub department only should come but without selecting the dept the sub department is listing. **views.py** def dept_view(request): if request.method == "POST": form = DepartmentForm(request.POST) if form.is_valid(): form.save() return redirect('department-view') else: form = DepartmentForm() depts = Department.objects.all() return render(request, "dept.html", {"form": form, "depts": depts}) # @login_required(login_url="signin") def delete_department(request, department_id): if request.method == "POST": department = get_object_or_404(Department, id=department_id) department.delete() return JsonResponse({"success": True}) return JsonResponse({"success": False}) def sub_dept_view(request): if request.method == "POST": form = SubDepartmentForm(request.POST) if form.is_valid(): form.save() return redirect("sub-department") # Redirect … -
fieldsets(legend) in modelform django
I have a model form forms.py class (forms.ModelForm): class Meta: model = InfoPersonal fields = [ 'name', 'phone_number' ] models.py class InfoPersonal(models.Model): name = models.CharField(_('Имя'), max_length=50) phone_number = PhoneNumberField( _('Номер телефона'), max_length=20, unique=True, blank=True, null=True, personal_info-add.html <form enctype="multipart/form-data" action="{% url 'workflows:personal_info-add' user.pk %}" method="post"> {% include "_parts/form.html" with form=form %} </form> I want to get the result as shown in the picture( email -> name passord -> tel). Is it possible to add a tag in the module itself? I need the <name> and <phone_number> fields to be inside the tag <fieldset> (legend)enter image description here how to implement it help please!!! -
Google Calendar API on EC2 (AWS) - webbrowser.Error: could not locate runnable browser
I am developing a Django App where a user can access his Google Calendar using this script credentials = None token = os.path.join(folder, "token.pickle") if os.path.exists(token): with open(token, 'rb') as tk: credentials = pickle.load(tk) if not credentials or not credentials.valid: if credentials and credentials.expired and credentials.refresh_token: credentials.refresh(Request()) else: credentials = os.path.join(folder, "credentials.json") flow = InstalledAppFlow.from_client_secrets_file( credentials, scopes=['openid', 'https://www.googleapis.com/auth/calendar'] ) flow.authorization_url( # Recommended, enable offline access so that you can refresh an access token without # re-prompting the user for permission. Recommended for web server apps. access_type='offline', # Optional, enable incremental authorization. Recommended as a best practice. include_granted_scopes='true', # # Optional, if your application knows which user is trying to authenticate, it can use this # # parameter to provide a hint to the Google Authentication Server. login_hint=useremail, # Optional, set prompt to 'consent' will prompt the user for consent prompt='consent') flow.run_local_server() credentials = flow.credentials with open(token, 'wb') as tk: pickle.dump(credentials, tk) service = build('calendar', 'v3', credentials = credentials) When I test it on my local machine everything works fine. However, I run it on a EC2 instance on AWS I get this error: flow.run_local_server() File "/home/ubuntu/webapp/lib/python3.12/site-packages/google_auth_oauthlib/flow.py", line 447, in run_local_server webbrowser.get(browser).open(auth_url, new=1, autoraise=True) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.12/webbrowser.py", line 66, in get … -
Can I create foreign key with specific value match from parent table
Suppose Parent table is CREATE TABLE departments ( department_id SERIAL PRIMARY KEY, department_name VARCHAR(100) NOT NULL, department_type VARCHAR(100) NOT NULL ); Suppose department_type is Type A and Type B. I want to create Table Employee with foreign key department_id, but department type is always Type A. CREATE TABLE employees ( employee_id SERIAL PRIMARY KEY, employee_name VARCHAR(100) NOT NULL, department_id INT, CONSTRAINT fk_department FOREIGN KEY (department_id, **department_type ='Type A'** ) REFERENCES departments(department_id) ); Is it Possible? -
How can i edit external link format converter rule in wagtail cms draftail editor
When someone adds an external link in Wagtail CMS, they should have the option to choose whether to make the link 'nofollow' or 'noreferrer.' To achieve this, I have inherited the existing link form, and the code is provided here class CustomExternalLinkChooserForm(ExternalLinkChooserForm): rel = forms.ChoiceField( choices=[ ("noreferrer", "Noreferrer"), ("nofollow", "Nofollow"), ], required=False, label=_("Rel Attribute"), ) i have also inherited view class CustomExternalLinkView(ExternalLinkView): form_class = CustomExternalLinkChooserForm i registered this in wagtail hooks so admin take this override core view @hooks.register("register_admin_urls") def register_custom_external_link_view(): return [ path( "admin/choose-external-link/", CustomExternalLinkView.as_view(), name="wagtailadmin_choose_page_external_link", ) ] By using the above, it gives me an output like this, but the main issue is that when the Draftail rich text editor saves the link in the database, it does not add the rel attribute in href url. How can I solve this issue? -
Issue with Loading Static Files and Images from Amazon S3 in Django
# Amazon S3 Configuration AWS_ACCESS_KEY_ID = "<your-access-key-id>" AWS_SECRET_ACCESS_KEY = "<your-secret-access-key>" AWS_STORAGE_BUCKET_NAME = "<your-bucket-name>" AWS_S3_REGION_NAME = "us-east-2" AWS_S3_CUSTOM_DOMAIN = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"} AWS_S3_QUERYSTRING_AUTH = False # STORAGES Configuration STORAGES = { "default": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage", "OPTIONS": { "location": "media", # Directory for media files "file_overwrite": False, # Prevent overwriting files }, }, "staticfiles": { "BACKEND": "storages.backends.s3boto3.S3StaticStorage", "OPTIONS": { "location": "static", # Directory for static files }, }, } # Configuration during development STATIC_URL = "/static/" # URL for static files STATICFILES_DIRS = [BASE_DIR / "config" / "static"] # Directories for static files STATIC_ROOT = BASE_DIR / "staticfiles" # Root directory for collected static files MEDIA_URL = "/media/" # URL for media files MEDIA_ROOT = os.path.join(BASE_DIR, "media") # Root directory for media files # S3 Configuration for production if not DEBUG: STATIC_URL = f"{AWS_S3_CUSTOM_DOMAIN}/static/" MEDIA_URL = f"{AWS_S3_CUSTOM_DOMAIN}/media/" The documentation used was from https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html. I am using Django version 5.1.4. Although the static files (CSS, JS, assets) are being collected correctly, when accessing the application, the layout is broken, with no styles applied or images loaded from the static/assets folder. Could anyone help me resolve this issue and ensure that the static files are loaded correctly in the production environment? The … -
Update datetime field in bulk save json object Python Django
i am very bad in django fw. I make simple django resp api. I want to save multiple json object to db. If one of objects is already exist in db(has the same uniq fields) i need just to update filed with datetime. My Model Like: class CheckPort(models.Model): created = models.DateTimeField(auto_now_add=True) ip = models.CharField(max_length=15, blank= False) port = models.PositiveIntegerField(default=0) type = models.CharField(max_length=5 ,default='tcp') class Meta: ordering = ['created'] unique_together = ('ip', 'port','type') My view: @api_view(['GET', 'POST']) def port_list(request): if request.method == 'GET': offers = CheckPort.objects.all() serializer = OfferSerializer(offers, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = OfferSerializer(data=request.data,many=isinstance(request.data, list)) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) So how to validate this? -
Problema no Carregamento de Arquivos Estáticos e Imagens com Amazon S3 em Django [closed]
# Configuração do Amazon S3 AWS_ACCESS_KEY_ID = "<your-access-key-id>" AWS_SECRET_ACCESS_KEY = "<your-secret-access-key>" AWS_STORAGE_BUCKET_NAME = "<your-bucket-name>" AWS_S3_REGION_NAME = "us-east-2" AWS_S3_CUSTOM_DOMAIN = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"} AWS_S3_QUERYSTRING_AUTH = False # Configuração de STORAGES STORAGES = { "default": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage", "OPTIONS": { "location": "media", "file_overwrite": False, }, }, "staticfiles": { "BACKEND": "storages.backends.s3boto3.S3StaticStorage", "OPTIONS": { "location": "static", }, }, } # Configuração durante o desenvolvimento STATIC_URL = "/static/" STATICFILES_DIRS = [BASE_DIR / "config" / "static"] STATIC_ROOT = BASE_DIR / "staticfiles" MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") # Configuração S3 para produção if not DEBUG: STATIC_URL = f"{AWS_S3_CUSTOM_DOMAIN}/static/" MEDIA_URL = f"{AWS_S3_CUSTOM_DOMAIN}/media/" A documentação utilizada foi a do https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html Embora os arquivos estáticos (CSS, JS, assets) sejam coletados corretamente, ao acessar a aplicação, o layout está quebrado, sem a aplicação dos estilos ou o carregamento das imagens da pasta static/assets. Alguém poderia me ajudar a resolver esse problema e garantir que os arquivos estáticos sejam carregados corretamente no ambiente de produção? -
Django Datetime TypeError: fromisoformat: argument must be str
I am having this error while using django. I try to get the date that one transaction happened but i get this error: File "/usr/local/lib/python3.11/site-packages/django/utils/dateparse.py", line 114, in parse_datetime return datetime.datetime.fromisoformat(value) TypeError: fromisoformat: argument must be str code error code snippet ` next_due_date = models.DateField(blank=True, null=True) # The next date when this transaction will be added transaction_date = models.DateTimeField(default=timezone.now) def __str__(self): # Check if transaction_date is set and valid before formatting if self.transaction_date: return f"{self.transaction_type} of {self.amount} on {self.transaction_date}" else: return f"{self.transaction_type} of {self.amount}"` Here is also my already made transactions.: [{"id":1,"user":1,"transaction_type":"expense","amount":"33.00","description":"Cosmote","category":null,"recurrence":null,"next_due_date":null,"transaction_date":"2025-03-26T14:03:02.430961Z"},{"id":2,"user":1,"transaction_type":"income","amount":"1000.00","description":".","category":"Salary","recurrence":"monthly","next_due_date":"2025-03-03","transaction_date":"2025-03-26T14:03:02.430961Z"},{"id":3,"user":1,"transaction_type":"income","amount":"1000.00","description":".","category":"Salary","recurrence":"monthly","next_due_date":"2025-03-03","transaction_date":"2025-03-26T14:03:02.430961Z"},{"id":4,"user":1,"transaction_type":"income","amount":"450.00","description":"Rent","category":"Rent","recurrence":"biweekly","next_due_date":"2025-03-01","transaction_date":"2025-03-26T14:03:02.430961Z"}] i can't understand the reason why is this happening i tried using directly timezone.now(): transaction_date = timezone.now() instead of transaction_date = models.DateTimeField(default=timezone.now) but it got the same error, also tries using if else statement to check in the str function but nothing last i tried using this format in str return f"{self.transaction_type} of {self.amount} on {self.transaction_date}" return f"{self.transaction_type} of {self.amount} on {self.transaction_date.strftime('%B %d, %Y')}" any idea why may this is happening? -
Labels in the form is not showing
This is my model.py file code: class Review(models.Model): VOTE_TYPE = ( ('up','Up Vote'), ('down','Down Vote'), ) owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null = True) project = models.ForeignKey(Project, on_delete=models.CASCADE) # when the model is deleted, all the reviews should also be deleted. body = models.TextField(null = True, blank=True) value = models.CharField(max_length=200, choices = VOTE_TYPE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) This is my forms.py code: class ReviewForm(ModelForm): class Meta: model = Review fields = ['value', 'body'] labels = { 'value': 'Place your vote', 'body': 'Add a comment with your code' } def __init__(self,*args,**kwargs): super(ReviewForm, self).__init__(*args, **kwargs) for name,field in self.fields.items(): field.widget.attrs.update({'class':'input'}) This my html file code <form class="form" action="{% url 'project' project.id %}" method="POST"> {% for field in form %} <!-- 'form' IS THE WORLD WE PUT IN CONTEXT DICT IN PROJECTS VIEW. --> <div class="form__field"> <label for="formInput#textarea">{{ field.label }}</label> {{ field }} </div> {% endfor %} <input class="btn btn--sub btn--lg" type="submit" value="Add Review" /> </form> The label's CSS is here: .comments { margin-top: 4rem; padding-top: 3rem; border-top: 2px solid var(--color-light); } .comments .form label { position: absolute; margin: -9999px; } .commentList { margin: 3rem 0; } .comment { display: flex; gap: 2rem; } the problem is that Labels … -
Tailwind CSS does not generate CSS for all classes
I'm new to Tailwind CSS and I'm looking to include it in my Django/FastAPI project. I'm using Tailwind version 4.0.17. The problem I'm having is that Tailwind doesn't recognize the HTML tags I have in my template files... I run the following command : npx tailwindcss -i ./static/css/input.css -o ./static/css/output.css This generates a CSS file for me, but it doesn't have all the classes in it... On the other hand, when I test with this command : npx tailwindcss --content ./templates/test_endpoint.html --dry-run > output.css This time, all the CSS classes of the HTML template are present in the output file, but not the others (those of the other HTML templates). Here is the code for the tailwind.config.js file: /** @type {import('tailwindcss').Config} */ module.exports = { content: [ "./templates/**/*.html", "./templates/*.html", "templates/main/index.html", "templates/base.html", "./**/templates/**/*.html", "./static/**/*.css", "./fastapi_app/**/*.html", "./main/**/*.html" ], theme: { extend: {}, }, plugins: [], } I've tried reinstalling Tailwind several times, changing the paths, trying other commands, and the result is always the same. If you have any ideas on how to solve this problem, that would be great! Thanks -
Most efficient way to write a "Many to Occasional" field in Django
So I read that ManytoMany fields in Django were slower than ForeignKey lookups (as they make use of a helper table). I am creating an application that allows performers to catalog their acts. Each act they have in their catalog can have multiple images. However, I also want to specify one "Hero Image" of the Act which will be used for preview when they search through their catalog. each act can have many images, but only one of those could be a header image. I came up with three options but I want to hear what the hive has to think. ManytoManyField from django.db import models from django.contrib.auth.models import User # Create your models here. class Act(models.Model): title = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() hero_image = models.ForeignKey('Image', on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Image(models.Model): act = models.ManyToManyField(Act) image = models.ImageField(upload_to='images/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Two Foreign Keys from django.db import models from django.contrib.auth.models import User # Create your models here. class Act(models.Model): title = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() hero_image = models.ForeignKey('Image', on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Image(models.Model): act = models.ForeignKey(Act, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/') … -
not able to connect to postgresql server
So I'm having trouble connecting my postgresql db server. I'm relatively new to Ubuntu, this is a brand new computer. My db name, username and password are all correct as per my Django settings. I hope I don't have to edit my pg_hba.conf file. I had similar issues regarding this with Fedora, but I didn't think I would have this problem with Ubuntu. I did in fact create a new database via the linux terminal. I'm also in my virtual environment. I even tried opening the psql shell and got more warnings. Here is the complete trackeback error after running python manage.py makemigrations and psql. FYI the name for my Ubuntu system is corey-james show_sunset_warning() /home/corey-james/Arborhub/arborhubenv/lib/python3.12/site-packages/django/core/management/commands/makemigrations.py:160: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "cortec" connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "cortec" warnings.warn( No changes detected (arborhubenv) corey-james@corey-james-HP-Laptop-14-dq0xxx:~/Arborhub/MyProject$ psql psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: role "corey-james" does not exist (arborhubenv) corey-james@corey-james-HP-Laptop-14-dq0xxx:~/Arborhub/MyProject$ -
Django + HTMX: how to have a CreateView that looks up information via HTMX and updates the form dynamically?
I'm a python and Django newbie. Also a newbie in StackOverflow... I'm trying to build a CreateView with a form that contains a button to lookup information via a GET request using HTMX. A user would encounter the form completely blank at first. Once they input a specific field (in this case a serial number), they can click the button that initiates the lookup/GET request. After the information is retrieved via the GET, I would like to update specific fields in the form with some of the information from the GET (essentially like an auto-complete). So far I have been able to build the initial CreateView (which is straightforward) and have been able to setup the button that does the HTMX GET request; I have also been able to retrieve the information needed but where I'm stuck is on being able to update/inject the values retrieved into specific fields from the form after the GET request. What are the steps I should take to handle that specific part? I have tried adding the form into the view that manages the HTMX get request and assigning some of the "initial" values, later having the form with the values defined as "initial" …