Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin ForeignKey issue,
The following are my models in Django. class Authors(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) total_books = models.IntegerField(default =0) class Book(models.Model): title = models.CharField(max_length=200) topic = models.CharField(max_length=200) author = models.ForeignKey(Authors, on_delete = models.CASCADE)` I want to use Admin platform to achieve: when I add a new Book, the total_books in related author add 1. Is there any way to solve it? I would appropriate it if someone help me. Can anyone give me some ideas? -
openai.error.InvalidRequestError: This is a chat model and not supported in the v1/completions endpoint. Did you mean to use v1/chat/completions?
Hi im new to chat gpt api and im trying to make a chatbot with it. I keep getting this error when i run my code: Internal Server Error: / Traceback (most recent call last): File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot\chatbot\views.py", line 23, in chatbot response = ask_openai(message) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot\chatbot\views.py", line 9, in ask_openai response = openai.Completion.create( ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\api_resources\completion.py", line 25, in create return super().create(*args, **kwargs) PS C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 02, 2023 - 21:17:40 Django version 4.2.2, using settings 'django_chatbot.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [02/Aug/2023 21:17:42] "GET / HTTP/1.1" 200 4265 Internal Server Error: / Traceback (most recent call last): File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot\chatbot\views.py", line 23, in chatbot response = ask_openai(message) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot\chatbot\views.py", line 9, in ask_openai response = openai.Completion.create( ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\api_resources\completion.py", line … -
How to handle NULL for Django DB Function Concat?
I want the query set to return concatenated string for address. I'm currently writing code like this: queryset = Place.objects.annotate( place_address= Concat('address__city', Value(', '),'address__state__name')) ) It return fine when city and state field is not empty. But it does not handle null value with this solution where the result could ended up: "Kuala Lumpur, " OR ", Selangor" OR ", " Is there a way to skip adding delimiter when the field in front is null? Thanks. -
Hide HTMX search results after option is selected
I have a search bar I created using HTMX and django forms that displays results correctly. I have a javascript selectOption() function filling the search bar with whatever the selected option is, but I am having trouble with the search results not going away after I select an option. Can this be handled through javascipt? Additionally, the search bar returns random results once I type something and then delete it, leaving it blank. Is there something I could fill into hx-trigger to fix this issue? See htmx tags below widget_attrs_nha_autosearch = { 'class': 'form-control', 'data-user-entry': 1, 'disabled': value.get('read_only'), 'hx-post': reverse('ng_django_pmp:nha-autosearch'), 'hx-target': '#results', 'hx-trigger': "keyup changed delay:500ms, search" } See search-results html below {% if results %} <ul class="list-group col-xs-12"> {% for part in results %} <li class="list-group-item d-flex justify-content-between align-items-center" onclick="selectOption('{{ part.manufacturer_part_number }}')">{{ part.manufacturer_part_number }}</li> {% endfor %} </ul> {% else %} <p>No search results</p> {% endif %} <script defer> function selectOption (partNumber) { const input = document.querySelector('#id_nha_override'); input.value = partNumber; } -
Django LIKE operation
I'm trying to send a query through Django python I also try to block any sql injection exploits Can someone explain to me how messaging is done LIKE Query for example "SELECT * FROM admin WHERE name LIKE '%myTitle%' It's easy to configure Query like this cursor.execute("SELECT * FROM admin WHERE name= %s", (_id, )); But when inserting %s Many errors are made when canceling %% From the text, for example SELECT * FROM admin WHERE name LIKE %s When Query Done it be like SELECT * FROM admin WHERE name 'MyTitle' It is being implemented correctly, but I want it to be set %% among %s LIKE SELECT * FROM admin WHERE name '%MyTitle%' Can someone explain to me how to solve this problem my Simple Script from django.db import connection title = "myTitle" query = "SELECT * FROM admin WHERE name LIKE %s" with connection.cursor() as cursor: cursor.execute(query, (title,)) -
How to Deploy a Django App to AWS Amplify using GitHub
I am trying to find a step-by-step guide that would detail the deployment of a django application using aws amplify. Although options like AWS ec2 are available, I would also like to see if a django web app deployment is possible on AWS Amplify. I have found numerous videos and posts on NextJS developers switching over to AWS Amplify as usage fees on Vercel are getting astronomically higher after a certain amount. Would like to ask for any leads to a guide that would deploy a django app on AWS Amplify. Thank you! <3 -
Nginx throws 403 Forbidden eror whenserving js and css files
I am trying to deploy a django project on an ec2 instance wuth gunicron and nginx and keep getting 403 errors when trying to setup with nginx. When I run the server using python3 manage.py runserver 0.0.0.0:8000 everything is served correctly and my static files are served but when I use nginx it stops serving my static files and throws a 403 error. /etc/nginx/sites-available/djangoproj server { listen 80; server_name X.XXX.XXX.XXX; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/djangoproj; } location / { include /etc/nginx/mime.types; include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Also when I make changes I then restart with sudo systemctl daemon-reload and sudo systemctl restart gunicorn. This is my first attempt at deploying a website so Im still a bit new when it comes to working with a linux server. I double checked the owner of the public directory and its set to www-data and all the static directories have read and write permissions (-rw-r--r-- 1 ubuntu ubuntu 2358255 Aug 2 18:16 main.js) so I dont think it has to do with permissions. Also I included my nginx for extra context. /etc/nginx/nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections … -
Django Mail isnt sending anymore
I used to have a working system where all mails got delivered and everything worked. I didnt change nothing but now the Mails arent sending anymore. I checked the mail connection on another server and the same data still works and gets send. Do I have an outdated version or something? How can I fix this? This is my settings.py DEFAULT_FROM_EMAIL='email@here.com' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.myemailprovider.com' EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_USE_TLS = False EMAIL_HOST_USER = 'mymail@mail.com' EMAIL_HOST_PASSWORD = 'MyPassword124' views.py send_mail( 'Test title', 'Test Email.', '', ['my@mail.com'], fail_silently=False, ) I am currently running a gunicorn server on nginx. -
Docker Compose: How to prevent db volume being cleared every time a container is build
I have dockerfile and compose file set up that works perfectly fine, that runs multiple service. But my problem is every time I do file changes deploy and re-build the containers to apply new changes; my postgres db volume is being recreated hence re-running migrations loosing existing data. Dockerfile # pull official base image FROM python:3.9.6-alpine as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV CRYPTOGRAPHY_DONT_BUILD_RUST=1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev RUN apk add --no-cache \ libressl-dev \ musl-dev \ libffi-dev RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add jpeg-dev zlib-dev make libjpeg \ && apk del build-deps # lint RUN pip install --upgrade pip # install dependencies COPY requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt RUN apk del \ libressl-dev \ musl-dev \ libffi-dev ######### # FINAL # ######### # pull official base image FROM python:3.9.6-alpine as runner # create the app user RUN addgroup -S app && adduser -S app -G app # create the appropriate directories ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME RUN mkdir … -
In Django, how to multiply-aggregate a field?
I want to aggregate a field using multiplication, but apparently Django doesn't have a Product function among its aggregation function. Example of what I want to do # models.py class MyModel(models.Model): ratio = models.DecimalField(...) # views.py mys = MyModel.objects.filter(...).aggregate(cum_ratio=Product(ratio)) How to achieve this? I feel like since Django didn't include a Product function like they did with Sum suggests that it's trivial but I can't put my finger on it. -
OperationalError at /admin/ no such table: django_session
I encountered a problem in my Django project, which I thought was from the database, but when I deleted it and entered the command python.exe .\manage.py makemigrations and python manage.py migrate, but when the command python manage.py migrate, everything went well except for one thing the problem: Operations to perform: Apply all migrations: account, admin, auth, blog, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying account.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying auth.0012_alter_user_first_name_max_length... OK Applying auth.0013_remove_user_id_alter_user_username...Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 87, in _execute return self.cursor.execute(sql) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\sqlite3\base.py", line 324, in execute return super().execute(query) ^^^^^^^^^^^^^^^^^^^^^^ sqlite3.OperationalError: foreign key mismatch - "auth_user_groups" referencing "auth_user" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\user\Desktop\shop\manage.py", line 22, in <module> main() File "C:\Users\user\Desktop\shop\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File … -
Django: How to create custom ModelSerializer from multiple models/tables in mySQL database?
I'm working on a Django project with an already existing mySQL database. I've quickly learned that mySQL lacks the explicit relationships found in postgresSQL databases where you can establish one to one, one to many, many to many relationships. Instead, you typically need to create a whole other table just for relationships. So currently, I have three tables: userpie_users, radar_sites, and userpie_users2radars (table describing the relationships). Table: userpie_users Table: radar_sites Table: userpie_users2radars Just to clarify, let's examine the first row of userpie_users2radars: id: 2, user_id: 78, radar_id: 17 The id: 2 can be ignored but this row specifies that user_id (78) from userpie_users is attached to radar_id(17) from radar_sites. The next row reveals that the same user also is attached to radar_id(4). For my API "GET" endpoint (http://127.0.0.1:8000/api/map/user_id), I want my final JSON body response to be something like this: { "user_id":"123", "last_name":"smith", "first_name":"john", "last_radar":"28", "radars":[["19","Coal Point Reserve UCSB"],["39","Harvey"],["33","Hawaii"]] } The first four fields are in the userpie_users table so this can be easily serialized with ModelSerializer. "last_radar" is cut off in the screenshot but it's there. "radars" however is an array I need to make by grabbing the user_id from the url parameters, looking through each row in userpie_users2radars … -
Django website not working as expected on home url, but eventually works upon consistent retry
so I have this single page application that runs django backend here. It actually has 4 header option: Jobs (the default), competitions, learn, about. When you visit the application, sometimes it fails to load the jobs section. The spinner just keeps spinning, and when you check the console, you will see an error that says VM96:2 Uncaught (in promise) SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON Now this is very confusing to me because if you keep clicking the Jobs link, it will eventually load the jobs page correctly (or you can keep trying a complete reload of the url, it will eventually load properly). However, the other hyperlinks work. This problem only happens on the job page, which is the homepage nginx configuration server { server_name pythonyard.com www.pythonyard.com *.pythonyard.com; location /static/ { alias /home/kenechukwu_webapp/allpython/backend/static/; } location / { try_files $uri @node; } location @node { proxy_pass http://127.0.0.1:8000; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/pythonyard.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/pythonyard.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.pythonyard.com) { return 301 https://$host$request_uri; } # managed by Certbot if … -
django-filter using filter class in another filter class
I use django-filter I have two models named Person and Member. Person has been defined as foreign key in Member. As an example here, I added less fields, normally the PersonModel model has a lot more fields. What I want to do here is to use all the filter fields I created for person in the filter class I created for Member. models.py class PersonModel(models.Model): name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class MemberModel(models.Model) register_no = models.CharField(max_length=20, unique=True) person = filters.ForeignKey(PersonModel, on_delete=models.PROTECT, related_name='members') filters.py class PersonFilter(filters.FilterSet): name= filters.CharFilter(field_name='name') last_name= filters.CharFilter(field_name='last_name') class MemberFilter(filters.FilterSet): register_no = filters.CharFilter(field_name='register_no') # # I want to use PersonFilter here # for example: person = PersonFilter(lookup_expr="person") or how? # # I don't want to do it this way: # person_name = filters.CharFilter(field_name='person__name') # person_last_name = filters.CharFilter(field_name='person__last_name') -
How to convert Figma design to Django?
I am making an app using Django and Python and I want to integrate some Figma designs with my web application. Does anyone know how to do this? -
Deploying Django on Heroku smart-open Causing Failure
Trying to deploy Django project to Heroku I get the following error: python setup.py egg_info did not run successfully. exit code: 1 error in smart_open setup command: 'python_requires' must be a string containing valid version specifiers; Invalid specifier: '>=3.6.*' note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed Tried multiple versions of smart-open and tried removing it from requirements.txt, the invalid specifier is NOT in my requirements.txt (this is: smart-open==4.1.0) or I have tried multiple other versions, all break the build. I’ve tried changing setup tools on Heroku to eg setuptools==40.3.0, no dice (same errors). -
Django app not loading with DisallowedHost error even after adding IP to ALLOWED_HOSTS
I'm facing an issue with my Django web application deployment on an Amazon EC2 instance. The app is running using Gunicorn and Nginx as a reverse proxy. However, when I try to access the app using the public IP address (ipaddress:8000), it's not loading, and I keep getting a "DisallowedHost" error. Here are the steps I've taken so far: In my Django settings.py, I've added the public IP address to the ALLOWED_HOSTS setting: python Copy code ALLOWED_HOSTS = ['ipaddress:8000'] I've confirmed that Gunicorn is running and bound to ipaddress:8000 . Nginx is configured as a reverse proxy with the following settings: nginx Copy code server { listen 80; server_name ipaddress:8000 location / { proxy_pass http://ipaddress:8000 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } Despite these configurations, the app still does not load, and I receive the following error in my Django logs: css Copy code [2023-08-02 17:28:00 +0000] [#] [INFO] Starting gunicorn 21.2.0 [2023-08-02 17:28:00 +0000] [#] [INFO] Listening at: http://ipaddress:8000 (#) ... DisallowedHost at / Invalid HTTP_HOST header: 'ip address'. You may need to add 'ipaddress' to ALLOWED_HOSTS. It seems like Django is still considering the request host as 'ipaddress', even though I've explicitly added it to ALLOWED_HOSTS. Any … -
Prevent custom django admin url from redirecting to change view
I have defined a custom django admin url that I am using as a custom action link in the changelist view and will also be used by the form posted in that custom view. # used in the overridden changelist.html <a href="{% url 'admin:get_monthly_report' %}">Get Monthly Report</a> # in the model admin def get_urls(self): urls = super().get_urls() urls += [ path( 'get_monthly_report/', self.admin_site.admin_view(self.get_monthly_report), name='get_monthly_report' ), ] return urls Problem is clicking on the link keeps trying to redirect the change view (doesn't make sense why Django is trying to guess instead of using the actual view defined for the URL). Given that what am doing is close enough to what is suggested in the documentation, either the documentation left this problem out or am doing something wrong -
Error when changing project server from Django to Azure
When I converted the website I have from Django storage to Azure, I got some errors I cant seem to fix. This was setup by a coworker of mine, and everything worked fine there, but on my computer, both at work and at my other computer home the same error occurs. django.core.exceptions.ImproperlyConfigured: 'mssql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' I have tried the following commands pip install req.txt pip install django pip install mssql django-mssql pip install django-mssql-backend pip install pyodbc python manage.py makemigrations python manage.py migrate python manage.py runserver Below is the ouput from my pip freeze command. Perhaps there are some missmatched versions that is causing some conflicts. aiohttp==3.7.4.post0 anyio==3.7.1 api-display-purposes==0.0.3 appdirs==1.4.4 APScheduler==3.10.1 arabic-reshaper==3.0.0 asgiref==3.6.0 asn1crypto==1.5.1 astroid==2.15.6 async-timeout==3.0.1 attrs==21.2.0 autobahn==23.6.2 Automat==22.10.0 autopep8==2.0.2 bcrypt==4.0.0 beautifulsoup4==4.12.2 blinker==1.6.2 cachetools==5.3.1 capstone==5.0.0rc2 certifi==2022.9.24 cffi==1.15.1 chardet==3.0.4 charset-normalizer==2.1.1 clarifai==9.6.3 clarifai-grpc==9.6.1 click==8.1.3 colorama==0.4.6 colored-traceback==0.3.0 configparser==3.8.1 constantly==15.1.0 cryptography==38.0.1 cssselect2==0.7.0 defusedxml==0.7.1 dill==0.3.7 discord==1.0.1 discord.py==1.6.0 distlib==0.3.7 Django==2.1.15 django-allauth==0.54.0 django-colorfield==0.9.0 django-countries==7.5.1 django-crispy-forms==2.0 django-jsonview==2.0.0 django-mssql==1.8 django-mssql-backend==2.8.1 django-multiselectfield==0.1.12 django-tinymce4-lite==1.8.0 djangorestframework==3.14.0 EasyProcess==1.1 emoji==2.7.0 exceptiongroup==1.1.2 filelock==3.12.2 Flask==2.3.1 future==0.18.3 googleapis-common-protos==1.60.0 greenlet==2.0.2 grpcio==1.56.2 h11==0.14.0 html5lib==1.1 httpcore==0.17.3 httpx==0.24.1 hyperlink==21.0.0 idna==2.10 importlib-metadata==6.6.0 instapy==0.6.16 … -
Problem with picture tags in Django templates
I'm getting some issues with a picture tag in a Django template. The goal is easy, I'm just trying to add to my website an image which may be in Avif, Webp or JPG/PNG format. I've written my HTML as I've done several times before, but somehow it's not working as expected. So the problem is as follows: in a first try, the AVIF version (which corresponds to the first source tag) is well loaded 👌🏻, but if I delete it from the server (or change its name), I was expecting WebP version to be loaded, though the alt message is shown. This is my code: <picture> <source srcset="{% static 'my_app/img/' %}{{ topic.image|avif_image }}" type="image/avif"> <source srcset="{% static 'my_app/img/' %}{{ topic.image|webp_image }}" type="image/webp"> <img src="{% static 'my_app/img/' %}{{ topic.image|original_image }}" alt="{{ topic.name }} image" loading="lazy"> </picture> Note: avif_image, webp_image and original_image are just some custom filters I've created to return each image's name, while topic is the field sent from the view to the template. I realized that the browser is always trying to load the first source tag, I mean, if I reorder the code and set WebP as the first one, I get the same problem but the … -
How to sort by letter in Django
On my website, there are different listings arranged as (a-e), (e-j), (j-o), (o-t), and all. When a user clicks on any of these listings, I want the website to retrieve data from the database starting with titles that fall within the selected letter range. However, I'm not very familiar with how to implement this functionality. Can anyone help me with this? index.html <div class="widget-content"> <h4>Sort by letter</h4> <ul class="widget-links"> {% for letter_range in letter_ranges %} {% if selected_range == letter_range %} <li><strong>{{ letter_range }}</strong></li> {% else %} <li><a href="?range={{ letter_range }}">{{letter_range}}</a></li> {% endif %} {% endfor %} </ul> views.py def index(request): letter_ranges = ['All', 'a-e', 'e-j', 'j-o', 'o-t', 't-z'] selected_range = request.GET.get('range', 'All') if selected_range == 'All': queryset = tabir.objects.filter(is_active=True) else: start_letter, end_letter = selected_range.split('-') queryset = tabir.objects.filter(title__istartswith__range=(start_letter, end_letter), is_active=True) context = { "tabirs": queryset, "current_date": datetime.now(), "selected_range": selected_range, "letter_ranges": letter_ranges, } return render(request, "ruya/index.html", context) models.py class tabir(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=200) description = RichTextField() is_active = models.BooleanField(default=False) is_home = models.BooleanField(default=False) release_date = models.DateTimeField(null=False,blank=True) #default=datetime.date.today create_date = models.DateTimeField(editable = False, auto_now_add=True)#default=datetime.date.today slug = models.SlugField(null= False, blank=True,unique=True, db_index=True, editable=False) -
HTML Django conditional statement dependent on radio button choices
I am working on an attendance system where teachers can mark a student as Present, Absent, or Late, but they can only enter a comment if a student is marked Absent or Late. I would like to make the Comment text input disabled when Present is selected. I tried different if statements with <input type="text" name='{{student.ssystudentid}}_comment' id="comment" maxlength="100">, but none seemed to work. Below is my code and a screenshot of the page. <form action="{% url 'attendance:submitAttendance' %}" method="post" name="fullForm"> {% csrf_token %} <table> <tr> <th>Student Name</th> <th>P/A/L</th> <th>Comment</th> </tr> {% for student in list_of_students %} <tr> <td>{{student}}</td> <td> <div class="radio-button"> {% for attendanceType in list_of_attendanceTypes %} {% if attendanceType.attendancetype == "Present" %} <input type="radio" name='{{student.ssystudentid}}_attendancetype' id='{{student.ssystudentid}}{{attendanceType}}' value={{attendanceType.attendancetypeid}} checked="checked"> <label for='{{student.ssystudentid}}{{attendanceType}}'> {{attendanceType}}</label> {% else %} <input type="radio" name='{{student.ssystudentid}}_attendancetype' id='{{student.ssystudentid}}{{attendanceType}}' value={{attendanceType.attendancetypeid}}> <label for='{{student.ssystudentid}}{{attendanceType}}'> {{attendanceType}}</label> {% endif %} {% endfor %} </div> </td> <td> <input type="text" name='{{student.ssystudentid}}_comment' id="comment" maxlength="100"> </td> </tr> {% endfor %} </table> <input type = "submit" value = "Save Attendance"/> </form>[![enter image description here][1]][1] Please note that I am not using Django forms. Any help will be appreciated. -
how do I access a previously created from a page on a different page
I am trying to open a modal i created that shows a team member's info. I want this same modal to be linked to the team members' names on a differnt page so that the same info pops up when the name is clicked. the modal works fine in the team page, but I just can't seem to figure out how to have the same modal pop up on the other page. I asked ChatGPT, and it gave me a bunch of code which did not work and I think I messed up even my previously written code. PLS HELP (sidenote: this is my first time building a website so I am very new at this). I am using django to build the website. team.html (original modal) {% extends 'base.html' %} {% block title %}Green Team - Our Team{% endblock %} {% block heading %}Our Team{% endblock %} {% block content %} <div class="container"> <div class="row justify-content-center"> {% for team_member in team_members %} <div class="col-md-4"> <div class="team-member-card team-card-center" data-toggle="modal" data-target="#teamMemberModal{{ team_member.id }}"> <div class="profile-picture profile-picture center"> <img src="{{ team_member.image.url }}" alt="{{ team_member.name }}"> </div> <div class="team-member-info"> <h3 class="name"> {% if team_member.id in team_member_pks %} <a href="#" class="author-link" data-toggle="modal" data-target="#teamMemberModal{{ team_member.id … -
how can i customize google signup template in django
before i finish signup this template apper and i want to customize it urls.py path('accounts/', include('allauth.urls')), path('users/', include('users.urls', namespace='users')), setting.py INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'grappelli', 'captcha', 'users', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google',] SOCIALACCOUNT_LOGIN_ON_GET=True SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS':{'access_type':'online'} } } LOGIN_REDIRECT_URL = 'home:home' LOGIN_URL = 'users:login' AUTHENTICATION_BACKEND=( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) i make templates>account>sinup.html but it did not work -
Handle UploadedFile in csv.reader
I am trying to read an uploaded file without saving it: def import_file(request): if request.method != 'POST': form = UploadForm() else: form = UploadForm(request.POST, request.FILES) if form.is_valid(): rdr = csv.reader(request.FILES["file"], delimiter=',') for row in rdr: print(row) ... But I get iterator should return strings, not bytes (the file should be opened in text mode) If i was reading a file with open function, I could have opened it with 'rt'. But in this case I am dealing with InMemoryUploadedFile class if I'm not mistaken. So I can't re-open it. What is the correct aproach here? Based on simpilar topics I've tried using read() and decode("UTF-8") and decode("ISO-8859-1") on the InMemoryUploadedFile, but so far nothing worked.