Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Switch to backend development
As a full-stack developer experienced with the MERN stack I'm looking to transition to focusing on backend development I'm considering learning Java with frameworks like Spring Boot or exploring Django or sticking with Express js My goal is to choose a technology that can effectively handle small and large projects like fintech applications Any advice on which path would be best suited for this transition? -
Django project structure: should my register, login templates go into an accounts app or in project templates
This is the project structure I have currently: project/ manage.py forum_app/ ecommerce_app/. # tbd accounts/ project/ settings.py urls.py templates/ base.html home.html registration/ login.html signup.html profile.html change_password.html ... Should I instead have something like this: project/ manage.py forum_app/ ecommerce_app/ # tbd accounts/ templates/ accounts/ login.html signup.html profile.html change_password.html project/ settings.py urls.py templates/ base.html home.html My confusion comes with the idea that since authentication is a specific set of tasks it should be a seperate app, so the relevant templates should go in the accounts app. However, the login, signup etc. templates are intended for the website as a whole, so maybe they should go in the root templates folder as in first example. I'd appreciate some guidance on what is the best way to do this? Also, if I were to create a Profile model for forum users (profile icon, bio) mapping to auth User, should that live in the accounts/models.py or forum_app/models.py? -
What is the best way to make sure the "django-timezone" session variable is set based on a user's profile preference each time they log in
Background I read this section in Django's documentation titled "Selecting the current time zone,", and it's clear to me how a user can select their preferred timezone for their session (and then the middleware makes sure it is used throughout their session): developer prepares a dictionary of timezones for users to select from developer makes this list available to user in a form within a template that is served by a GET request to a view called set_timezone user selects timezone using this form and makes a POST request set_timezone view uses a simple one-liner to set session "django-timezone" variable: request.session["django_timezone"] = request.POST["timezone"] Finally, the custom TimezoneMiddleware class referenced in the documentation will then activate the timezone for all view requests in the session from that point on Question If I store a user's timezone preference in a User model or User profile model, what is the best way to make sure the "django-timezone" session variable is always set for all their sessions (each time they log in)? Thoughts/guesses Would I need to modify a built-in Django authentication middleware class of some sort? Would it be best to extend the Django-standard LoginView class from django.contrib.auth.views? Or will the aforementioned LoginView … -
Bad Request and Invalid HTTP_HOST header in deployment NGINX + Gunicorn + Django?
Could you, please, help me with some suggestion where or how to find a resolution of my DisallowedHost exception? I have deployed my Django project to the DigitalOcean Ubuntu server with Nginx + Gunicorn according to instructions from DjangoProject and DigitalOcean as well as answers from related questions from DjangoForum, StackOverflow and others. I believe I tried all the advice I could find but still have 400 BadRequest responses, and Invalid HTTP_HOST header Error. likarnet is my project name, and likarnet.com is my domain. I have connected domain likarnet.com to my public IP and SSL certificate to my domain. Versions python 3.12, django 5.0.6 Please, excuse me if I ask some obvious things. This is my first project. File /etc/nginx/sites-available/likarnet server { listen 80 default_server; listen [::]:80 default_server; server_name likarnet www.likarnet; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/likarnet/website/likarnet; } location /media/ { root /home/likarnet/website/likarnet; } location / { proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Real-IP $remote_addr; proxy_redirect off; proxy_pass http://unix:/run/gunicorn.sock; } } I have just tried to use default include proxy_params; File /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=likarnet Group=sudo WorkingDirectory=/home/likarnet/website/likarnet … -
Django User-roles permission
I’m trying to create a school management webapp using Django. I’m using PostgreSQL for database. The webapp will be used by many schools that’s why am trying django_tenant. Kindly advise on how I should go about the account app that should handle login and signup from main homepage. Users are to be link to their respective schools so as other data for security purposes. I have several users like student, parent, teacher, treasurer, manager, and secretary for each school. I want to end up assigning roles for each user that is different from other users something that I need to be handled by using user_type while signing up. But also I want to have other fields in the signup form specific to the user like parent for student. Kindly advise. I try using AbstractUser but since I also want added fields per user am trying customuserform. The two don’t seem to work well together. -
Passing date value to HTML form in django framework
I am building my first application with Django. I am trying to make a template form to update values in a row in a table in a database. I want to populate all the forms fields with the existing values from the database. I can pass dates in as text just fine: This displays my date: <input type="text" class="form-control" value="{{ table.date }}"> but when I try the same value into a date field, it remains blank with I render This displays a blank date field: <input type="date" class="form-control" value="{{ table.date }}"> I assume this has to do with handling date formatting. Is there an easy way to handle this in the html? or does it require backend work? Any python code I tried to write into the template resulted in a 404. Still learning what the capabilities are. From what I have read I am guessing correct way to do this is with a function in my model, but I was hoping I could write something to convert the date in my template. My view is basic: def update(request, id): table = table.objects.get(pk=id) return render(request, 'app/tempate.html', {'table' : table}) -
DataTable table ordering fails when used in HTMX responsive table
I have played around with a few ways to create responsive tables and I like the htmx approach. The issue I run into is I loose some of the DataTables functions I have relied upon, mainly the ability for the user to sort by clicking on the header. Views.py: class HomePageView(TemplateView): template_name = 'wwdb/home_tabletest.html' class WinchOperatorForm(forms.ModelForm): class Meta: model = WinchOperator exclude = [] def get_winchoperator_list(request): context = {} context['winchoperator'] = WinchOperator.objects.all() return render(request, 'wwdb/winchoperator_list.html', context) def add_winchoperator(request): context = {'form': WinchOperatorForm()} return render(request, 'wwdb/add_winchoperator.html', context) def add_winchoperator_submit(request): context = {} form = WinchOperatorForm(request.POST) context['form'] = form if form.is_valid(): context['winchoperator'] = form.save() else: return render(request, 'wwdb/add_winchoperator.html', context) return render(request, 'wwdb/winchoperator_row.html', context) def add_winchoperator_cancel(request): return HttpResponse() def delete_winchoperator(request, winchoperator_pk): winchoperator = WinchOperator.objects.get(pk=winchoperator_pk) winchoperator.delete() return HttpResponse() def edit_winchoperator(request, winchoperator_pk): winchoperator = WinchOperator.objects.get(pk=winchoperator_pk) context = {} context['winchoperator'] = winchoperator context['form'] = WinchOperatorForm(initial={ 'firstname':winchoperator.firstname, 'lastname': winchoperator.lastname, 'status': winchoperator.status, 'username': winchoperator.username, }) return render(request, 'wwdb/edit_winchoperator.html', context) def edit_winchoperator_submit(request, winchoperator_pk): context = {} winchoperator = WinchOperator.objects.get(pk=winchoperator_pk) context['winchoperator'] = winchoperator if request.method == 'POST': form = WinchOperatorForm(request.POST, instance=winchoperator) if form.is_valid(): form.save() else: return render(request, 'wwdb/edit_winchoperator.html', context) return render(request, 'wwdb/winchoperator_row.html', context) I can post more templates if requested, but the template defining the tables are: <div> <table class="table … -
ModelForm with field depending on user permission?
I have a model Address with a field and a ModelForm. class Address(Model): number = PositiveSmallIntegerField(default=1) class AddressForm(ModelForm): class Meta: model = Address fields = "__all__" How do I add a validator to it, when the form is shown to a user with a specific permission? The form should behave as if the model itself would have a number field like this: number = PositiveSmallIntegerField(default=1, validators=[MaxValueValidator(100)]) By that I mean that the form should only allow values from 0 to 100, and the backend should validate that the value is inbetween 0 and 100. The view could pass whether or not to use the limited field like so: form = AddressForm(enable_limit=True) And I could do something like this: class AddressForm(ModelForm): class Meta: model = Address fields = "__all__" def __init__(self, *args, enable_limit=False, **kwargs): if enable_limit: self.base_fields["number"].widget.attrs["max"] = 100 However, this only updates the widget. The form does complain about values > 100, but that's only the HTML forms client-side validation and by changing the value in the request, I can go around that, which is not what I want. Basically, I want to tell the ModelForm to use the Adresse.number field as the foundation, but with an additional MaxValueValidator(100). How … -
Error when reading excel table for autocomplete database
I'm trying to fill the database in Django project automatically (through migration) by reading excel table. Migration file code: # Generated by Django 5.0.6 on 2024-06-21 15:04 import random import openpyxl from django.db import migrations from users import models DEFAULT_TABLE = 'default_articles_data.xlsx' users = [] def fill_articles(apps, schema_editor): wb = openpyxl.load_workbook(DEFAULT_TABLE, data_only=True) active_sheet = wb['Лист1'] blog_users = apps.get_model('users', 'UserProfile') Article = apps.get_model('articles', 'Article') for user in blog_users.objects.all(): users.append(user) for row in range(1, active_sheet.max_row + 1): article_image_source = active_sheet.cell(row=row, column=1).value print(article_image_source) article_title = active_sheet.cell(row=row, column=2).value print(article_title) article_author = random.choice(users) print(article_author) article_short_description = active_sheet.cell(row=row, column=3).value print(article_short_description) article_content = active_sheet.cell(row=row, column=4).value print(article_content) article = Article(title=article_title, author=article_author, short_description=article_short_description, content=article_content, image=article_image_source) article.save() class Migration(migrations.Migration): dependencies = [ ('articles', '0006_comment_article'), ] operations = [migrations.RunPython(fill_articles)] This is what the Article model itself looks like: class Article(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(unique=True, blank=True, null=True) short_description = models.TextField(max_length=100) content = models.TextField() pub_date = models.DateField(auto_now_add=True) image = models.ImageField() author = models.ForeignKey(users_models.UserProfile, on_delete=models.CASCADE) tags = models.ManyToManyField(Tag, blank=True) def __str__(self): return self.title Here is a sample row from the target table (used only A-D columns): On output I get an error: django.db.utils.IntegrityError: NOT NULL constraint failed: articles_article.title The above exception was the direct cause of the following exception: Traceback (most recent … -
Why does csv.reader with TextIOWrapper include new line characters?
I have two functions, one downloads individual csv files and the other downloads a zip with multiple csv files. The download_and_process_csv function works correctly and seems to replace new line characters with a space. 'Chicken, water, cornmeal, salt, dextrose, sugar, sodium phosphate, sodium erythorbate, sodium nitrite. Produced in a facility where allergens are present such as eggs, milk, soy, wheat, mustard, gluten, oats, dairy.' The download_and_process_zip function seems to include new line characters for some reason (\n\n). I've tried newline='' in io.TextIOWrapper however it just replaces it with \r\n. 'Chicken, water, cornmeal, salt, dextrose, sugar, sodium phosphate, sodium erythorbate, sodium nitrite. \n\nProduced in a facility where allergens are present such as eggs, milk, soy, wheat, mustard, gluten, oats, dairy.' Is there a way to modify download_and_process_zip so that new line characters are excluded/replaced or do I have to iterate over all the rows and manually replace the characters? @request_exceptions def download_and_process_csv(client, url, model_class): with closing(client.get(url, stream=True)) as response: response.raise_for_status() response.encoding = 'utf-8' reader = csv.reader(response.iter_lines(decode_unicode=True)) process_copy_from_csv(model_class, reader) @request_exceptions def download_and_process_zip(client, url): with closing(client.get(url, stream=True)) as response: response.raise_for_status() with io.BytesIO(response.content) as buffer: with zipfile.ZipFile(buffer, 'r') as z: for filename in z.namelist(): base_filename, file_extension = os.path.splitext(filename) model_class = apps.get_model(base_filename) if file_extension == … -
django runserver suddenly gives error "double free detected in tcache 2"
I have a django app which suddenly started giving me this error. I have not made changes to the code in the app, and the app runs fine on other servers. So it must be some configuration on my computer. But I have absolutely no idea how to troubleshoot it, and I cannot find any relevant answers when googling the error. Help? $ python manage.py runserver 127.0.0.1:8000 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). free(): double free detected in tcache 2 I'm running Ubuntu 20.04. Django 4.1.4. -
Append an entry per view to the DEFAULT_FILTER_BACKENDS
In a Django (and DRF) project with a large number of views we have set a list of filter backends in settings.py: REST_FRAMEWORK = { "DEFAULT_FILTER_BACKENDS": [ # filter backend classes ], # other settings } Some of the view classes need additional filter backends. We can specify the attribute filter_backends per view class: FooViewSet(viewsets.ModelViewSet): filter_backends = [DefaultFilterOne, DefaultFilterTwo, DefaultFilterThree, AdditionalFilter] However, this is not DRY. Here in this example three (3) filter backends are default and have to be repeated in the viewset class. If there's a change in settings.py it has to be reflected in the view class. What is best practice to append an additional filter backend per class, while keeping the default filter backends from settings.py? -
How do I fix error "TypeError at / ‘dict’ object is not callable" located in exception.py?
Adding django CMS to an existing Django project, I'm getting the error: "TypeError at / ‘dict’ object is not callable". This is the output: TypeError at / 'dict' object is not callable Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.2.13 Exception Type: TypeError Exception Value: 'dict' object is not callable Exception Location: C:\Users\USER\.virtualenvs\AnalyticsScout_V_1_1-2IRLUV3q\lib\site-packages\django\core\handlers\exception.py, line 55, in inner Python Executable: C:\Users\USER\.virtualenvs\AnalyticsScout_V_1_1-2IRLUV3q\Scripts\python.exe Python Version: 3.9.16 Python Path: ['C:\\Users\\USER\\OneDrive\\Bureau\\AnalyticsScout_V_1_1', 'C:\\Users\\USER\\miniconda3\\python39.zip', 'C:\\Users\\USER\\miniconda3\\DLLs', 'C:\\Users\\USER\\miniconda3\\lib', 'C:\\Users\\USER\\miniconda3', 'C:\\Users\\USER\\.virtualenvs\\AnalyticsScout_V_1_1-2IRLUV3q', 'C:\\Users\\USER\\.virtualenvs\\AnalyticsScout_V_1_1-2IRLUV3q\\lib\\site-packages'] Server time: Fri, 21 Jun 2024 09:26:19 +0000 In my local project I have the ‘exception.py’ file as the one in: Exception.py Whenever I run Django, I’m getting the following output in the terminal : Microsoft Windows [Version 10.0.22000.2538] (c) Microsoft Corporation. All rights reserved. (AnalyticsScout_V_1_1-2IRLUV3q) (base) C:\Users\USER\OneDrive\Bureau\AnalyticsScout_V_1_1>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). June 21, 2024 - 05:26:05 Django version 4.2.13, using settings 'analyticsscout.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: / Traceback (most recent call last): File "C:\Users\USER\.virtualenvs\AnalyticsScout_V_1_1-2IRLUV3q\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) TypeError: 'dict' object is not callable [21/Jun/2024 05:26:20] "GET / HTTP/1.1" 500 74922 [21/Jun/2024 05:26:20] "GET /static/debug_toolbar/css/toolbar.css HTTP/1.1" 304 0 [21/Jun/2024 05:26:20] … -
Django Annotation F() value
I have a question regarding Django Annotations: tickers = { "BCO": 10.0, "AIR": 50.0, } assets = Asset.objects.annotate( price=(tickers[F("fk_security__ticker_symbol")])) I would like to annotate the value from the dictionary to the asset but always getting a key error: F(fk_security__ticker_symbol) What am I doing wrong here? Is it even possible to do this? Thanks a lot in advance! If it helps, here is my model: class Asset(models.Model): fk_security = models.ForeignKey(Security, on_delete=models.CASCADE, blank=False, verbose_name="Security",related_name="security", ) class Security(models.Model): ticker_symbol = models.CharField( max_length=5, verbose_name="Ticker Symbol", default="", ) -
OAuth2 code_verifier missing
I wanted to create my Oauth2 provider for authentication in my django applications. For the test I used Django OAuth Toolkit and created 2 separate projects on different ports: http://127.0.0.1:8001 - client http://127.0.0.1:8000 - provider Here are all the endpoints for the provider that are redirected to for login and access confirmation: from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views path('admin/', admin.site.urls), path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')), path('accounts/login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'), path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'), The code for the login page: <!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> </body> </html> On the provider's side everything goes normally and I get to the page where I confirm the user and I am redirected to a special page of the callback client. Client endpoints: from django.contrib import admin from django.urls import path from client import views urlpatterns = [ path('admin/', admin.site.urls), path('client/login/', views.login, name='login'), path('client/callback/', views.callback, name='callback'), ] Client Views: import os import string import random import base64 import hashlib from django.http import HttpResponse from django.shortcuts import redirect, render from requests_oauthlib import OAuth2Session os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' CLIENT_ID = 'hR0E2tAkf8mLqOwNpPPun0dTBDU44JF8z8SgJfnJ' CLIENT_SECRET = 'hNi3IugtuqtEFa5GonCW4ilQTnsjz2nUE1jf2WeoxaMQNZHt1pzszLGeGtpYsNXV7VHouFF79C7XMOmSJRcXrY4OEPoJuTQyIng6ONjjt4tPvJfpPJpKMFPX9MPgUpps' REDIRECT_URI = 'http://127.0.0.1:8001/client/callback/' AUTHORIZATION_URL = … -
Why FormView wont save the object while CreateView does?
I am still new in django, i searched in FormView and CreateView source code and i found they both inheritate form same things this is my simple view which has inherited from FormView class MyFormView(FormView): form_class = MyForm template_name = 'form.html' success_url = "/thanks/" def form_valid(self, form): form.save() return super().form_valid(form) i overwrote the form_valid method to try save my object but in my CreateView class PersonCreateView(CreateView): model = Person fields = '__all__' template_name = 'form.html' it saves my object automatically -
Liking songs in my music website not working Django app
I'm making a music stereaming website with Django and i'm struggling with adding a song to liked songs. I have a {% for % } that cycle all the songs and when i click the hearth button i want the song to be added to liked songs. How can i fix it? models.py (for songs and songs being liked): class Song(models.Model): song_id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) artist = models.CharField(max_length=50) album = models.CharField(max_length=50, blank=True) genre = models.CharField(max_length=20, blank=True, default='genre') song = models.FileField(upload_to="songs/", validators=[FileExtensionValidator(allowed_extensions=['mp3', 'wav'])], default="name") image = models.ImageField(upload_to="songimage/", validators=[FileExtensionValidator(allowed_extensions=['jpeg', 'jpg', 'png'])]) data = models.DateTimeField(auto_now=False, auto_now_add=True) slug = models.SlugField() class LikedSong(models.Model): liked_id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) music_id = models.ForeignKey(Song, on_delete=models.CASCADE) views.py (to like a song): def likesong(request): user = request.user if user.is_authenticated: if request.method == "POST": song_id = request.POST.get('song_id') state = request.POST.get('state') favourites = LikedSong.objects.filter(user=user) song = Song.objects.get(song_id=song_id) if state == 'liked': if song in favourites.songs.all(): favourites.delete(song) else: if song not in favourites.songs.all(): favourites.add(song) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) HTML: {% for i in allsongs %} <div class="sameMovieCard"> <div class="container_songpost"> <img src="{{i.image.url}}" id="A_{{i.song_id}}"/> <div class="overlay_songpost"></div> <div class="play-btn_songpost"> <a class="play-btn" data-song-url="{{i.song.url}}" id="{{i.song_id}}" onclick="playSong(this)"><i class="fa-solid fa-circle-play"></i></a> </div> </div> <div class="songpost_data"> <h5 class="song-name" id="B_{{i.song_id}}"><a data-song-url="{{i.song.url}}" id="{{i.song_id}}" onclick="playSong(this)">{{i.name}}</a></h5> <p class="singer-name" id="C_{{i.song_id}}">{{i.artist}}</p> {% if user.is_authenticated %} <form … -
in django class base view whenever i logged in ,my user log in successfully but get this error page:Page not found (404)
i tried class base view in my blog website authorlogin.every time i logged in though my author get logged,but get a page of error.i have just converst login into classbased view but my authorprofile is function based view the error message: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/profile/ Using the URLconf defined in blog.urls, Django tried these URL patterns, in this order: admin/ author/ catagory/ post/ [name='base'] The current path, accounts/profile/, didn’t match any of these. main urls.py urlpatterns = [ path('author/',include('author.urls')), ] authorlogin url urlpatterns = [ path('author.login/',views.authorlogin.as_view(),name='login'), path('profile',views.authorprofile,name='profile') ] views.py class authorlogin(LoginView): template_name='login.html' def form_valid(self, form): messages.success(self.request,'Welcome mr.{name}') return super().form_valid(form) def form_invalid(self, form): messages.success(self.request,'Logged in information incorrect') return super().form_invalid(form) def get_context_data(self, **kwargs) : context=super().get_context_data(**kwargs) context['type']='login' return context @login_required def authorprofile(request): if request.user.is_authenticated: data=Post.objects.filter(author=request.user) return render (request,'profile.html',{'data':data}) else: return redirect('login') i tried that after get login it take me directly to profile page not an error page -
Breakpoints not triggering in PyCharm while debugging Django application
I'm facing an issue with PyCharm where breakpoints in my Django application are not getting triggered during debugging sessions. I've tried setting breakpoints in various parts of my codebase, but none of them seem to work. I run the project in debug mode. Could someone please advise on what might be causing this issue and how to resolve it? I'm specifically looking for tips or troubleshooting steps related to PyCharm's debugger in the context of Django development. Any insights would be highly appreciated! -
Django adding leading slash when saving the path
I'm creating a route to save some photos and, for now, they're being saved on my desktop. This can be easily changed on my .env file: MEDIA_URL=C://Users/User/Desktop/ Django saves the file correctly and it can be seen on its location as expected. However, on the database, the file is saved with an extra leading slash /C:/Users/User/Desktop/photo.png I know this is kinda a silly question, since this slash may be removed on the application, by manually editing before saving it, etc. But I'd like to know if there's a built-in solution in Django for this My settings.py variables are the following: MEDIA_URL = os.environ.get('MEDIA_URL') MEDIA_ROOT = os.environ.get('MEDIA_URL') If you need my view, here it is: @api_view(['PATCH']) def updatePhoto(request): user= request.user if 'photo' not in request.FILES: return Response({'message': 'Error', 'error': 'No photo uploaded'}, status=400) try: photo = request.FILES['photo'] fs = FileSystemStorage() filename = fs.save(name=photo .name, content=photo ) uploaded_file_url = fs.url(filename) user.foto_url = uploaded_file_url user.save() return Response({'message': 'Updated'}, status=200) except Exception as e: return Response({'message': 'Error', 'error': str(e)}, status=500) -
Ambiguous behaviour of django context variable while creating url in template using url tag
I am passing a context variable review_id in the below view function to the template. The context variable is supposed to be used in constructing a url using the template tag url. views.py def report_pdf(request, review_id): return render(request, 'mtsAuthor/report.html', { 'review_id': review_id }) report.html <a href='{% url "mtsAuthor:Review" review_id %}'>Link</a> The report.html page is rendered properly and the url is also generated fine. In my case, the url would be like /report/report_pdf/8fd9caac-1bae-45eb-af9d-b9673c17c0f8/. The related url path is path('report/report_pdf/<uuid:review_id>/', views.report_pdf, name='report_pdf') But when the link is clicked, the following error is encountered: Reverse for 'download_review_report_pdf' with arguments '('',)' not found. -
Geojason serializer is giving null geometry
I'm having the same issue found in this question, though it was supposedly fixed in Django 1.9, so I thought maybe I'm doing something wrong. I'm trying to serialize my geodjango data: homes = serialize( "geojson", Home.objects.all(), geometry_field="point", fields=["address_point"], ) I then go to print it out, and it shows that the geometry is null as follows: { "type":"FeatureCollection", "crs":{ "type":"name", "properties":{ "name":"EPSG:4326" } }, "features":[ { "type":"Feature", "id":1, "properties":{ "address_point":"SRID=4326;POINT (15.57385209377286 7.776164310995906)" }, "geometry":null } ] } Further, when I try to access the data in my javascript (using django-geojson) and then log it to the console, the result is null. I believe the two issues are related. {% load geojson_tags %} var homes = {{ homes|geojsonfeature|safe }}; console.log(homes) Would appreciate any insight into fixing this, thank you! P.S. Results of pip freeze asgiref==3.8.1 black==24.4.2 certifi==2024.6.2 charset-normalizer==3.3.2 click==8.1.7 Django==5.0.6 django-countries-plus==2.2.0 django-environ==0.11.2 django-geojson==4.1.0 django-languages-plus==2.1.1 django-safedelete==1.4.0 idna==3.7 isort==5.13.2 mypy-extensions==1.0.0 packaging==24.1 pathspec==0.12.1 pillow==10.3.0 platformdirs==4.2.2 psycopg2-binary==2.9.9 requests==2.32.3 setuptools==69.5.1 sqlparse==0.5.0 urllib3==2.2.2 wheel==0.43.0 -
Django audio file not playing
Issue with Django and HTML5 Tag: Unable to Play Uploaded Audio Files I'm encountering an issue with playing audio files uploaded through my Django application using HTML5's tag. Here's the setup: Problem Description: I have a Django model (AudioFile) with a FileField (audio_file) to upload audio files. In my template, I'm iterating over a queryset (audio) of AudioFile objects to display audio details and provide a playback option using the tag. Template Code Snippet: {% for file in audio %} <li> <h4>{{ file.title }}</h4> <div id="name"><a href="{{ file.audio_file }}" target="_blank">{{ file.name }}</a></div> <div id="play"> <audio src="{{ file.audio_file }}" controls="controls"> Your browser does not support the audio element. </audio> </div> </li> {% endfor %} Expected Behavior: Clicking the play button for each audio file should initiate playback directly within the browser using HTML5 audio capabilities. Steps Taken: Verified MEDIA_URL and MEDIA_ROOT settings in settings.py to ensure media files are correctly served. Checked Django model setup (models.py) to confirm upload_to path for FileField. Question: How can I correctly configure Django and the tag in HTML5 to play uploaded audio files? What adjustments are needed in the template and model definitions to ensure proper playback functionality? Any insights or suggestions would be greatly … -
How to Hide Password in Admin Panel When Creating a New User?
I have encountered an issue in the admin panel of my application. When creating a new user and setting the password, the password is displayed in plain text. Here is a brief description of the problem: Navigate to the admin panel. Select the option to create a new user. Enter a password for the new user. Expected behavior: The password should be hidden and displayed as dots or asterisks (e.g., ********). Actual behavior: The password is displayed in plain text, which poses a security risk. Could someone guide me on how to modify the admin panel so that the password is not displayed in plain text? That didn't help either Link admin.py from django.contrib import admin from django.contrib.auth.hashers import make_password from user import models class UserAdmin(admin.ModelAdmin): """Define the admin pages for users.""" ordering = ['id'] list_display = ['id', 'email', 'name'] search_fields = ['id', 'name', 'email'] readonly_fields = ['last_login'] def save_model(self, request, obj, form, change): obj.password = make_password(obj.password) obj.user = request.user obj.save() # Register your models here. admin.site.register(models.User, UserAdmin) -
How to add a Tabular Inline to Django's default user's page When The other model has a many to many relation with user model
So I surfed the web for this problems solutions but I couldn't quite find the answer to this problem. Here are my models: class Website(models.Model): url = models.URLField() users = models.ManyToManyField(User) def __str__(self) -> str: return str(self.url) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(null=True, blank=True) nickname = models.CharField(blank=True, null=True, max_length=50) location = models.CharField(blank=True, null=True, max_length=50) weight = models.DecimalField(null=True, max_digits=5, decimal_places=2) def __str__(self) -> str: return str(self.user) So as you can see one field in the Website model has a "ManyToMany" relationship with django's default User model. So I was wondering How I could change or see the list of websites a user has in the User's page/section. I tried doing this and it didn't work: class WebsiteInline(admin.TabularInline): model = Website extra = 1 class UserAdmin(admin.ModelAdmin): inlines = [WebsiteInline] admin.site.unregister(User) admin.site.register(User, UserAdmin) and here is the error: <class 'accounts.admin.WebsiteInline'>: (admin.E202) 'accounts.Website' has no ForeignKey to 'auth.User'.