Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
There is an error of page not found ;Request method get method
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/signup Raised by: django.contrib.admin.sites.catch_all_view You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I tried on stackoverflow but it gives me the post method to solve the error -
In Django, after creating models.py, how to create a combobox and populate me with database?
In the app1/home.html page, i would like to create a combobox and display data from a database table (city names) inside. A simple combobox with city names. I created the models.py file and migrated the database. How can I create the combobox and display City_Name in it? Thank you models.py from django.db import models class Select_City(models.Model): City_Name= models.IntegerField() def __str__(self): return self.City_Name -
Azure App Service web app: Django + Microsoft login redirect HTTPS issue
Azure App registration web redirect URL (it's HTTPS) as below: Using Azure App Service deployed the Django web app successfully: the above deploying result shows http://, but in Azure web app web it shows https://, also could open the web app using https successfully with valid as below: But when the web app redirected to Microsoft site to login, it uses http:// again which doesn't match the https:// configured in App registration: The MS authentication and redirection is handled by package ms_identity_web, code provided from https://github.com/Azure-Samples/ms-identity-python-django-tutorial/tree/main/1-Authentication/sign-in In development environment there is no issue since I use http://localhost:8000/auth/redirect as web redirect url in App registration. My issue could be the same as this one: link, but it covered the URL details so not sure if it was the same http/https mismatching issue. -
postgresql ERROR: duplicate key value violates unique constraint "django_apscheduler_djangojob_pkey"
(https://i.stack.imgur.com/rPvSI.png) when i build django(+django-apscheduler),postgresql,nginx i got error above this. django=4.2.2 python=3.8.10 postgresql=14.5 django-apscheduler=0.6.2 apscheduler=3.10.1 so i try to solve this error, search on google : modify postgres db : because "django_apscheduler_djangojob_id_seq" doesnt exist, so i created table("django_apscheduler_djangojobexecution_id_seq" is exist) CREATE SEQUENCE django_apscheduler_djangojob_id_seq INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START 1 CACHE 1 NO CYCLE; CREATE SEQUENCE SELECT setval('django_apscheduler_djangojob_id_seq',(SELECT MAX(id) FROM django_apscheduler_djangojob)); But it doenst work... comment out "Djangojobstore" : it works but i want to use djangojobstore in my operator.py : logger = logging.getLogger(__name__) def delete_dormant_user(): dormant_user = User.objects.filter(is_active=False) dormant_user.delete() @util.close_old_connections def delete_old_job_executions(max_age=604_800): DjangoJobExecution.objects.delete_old_job_executions(max_age) class Command(BaseCommand): help = "Runs delete_dormant_user." def start(self, *args, **options): scheduler = BackgroundScheduler( timezone=settings.TIME_ZONE ) #scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( delete_dormant_user, trigger=CronTrigger(minute="*/3"), id="delete_dormant_user", max_instances=1, replace_existing=True, ) logger.info("Added job 'delete_dormant_user'.") scheduler.add_job( update_ingredient_links, trigger=CronTrigger(day_of_week="0-6", hour="04", minute="00"), id="update_ingredient_links", max_instances=1, replace_existing=True, ) logger.info("Added job 'update_ingredient_links'.") scheduler.add_job( delete_old_job_executions, trigger=CronTrigger( day_of_week="mon", hour="05", minute="00" ), id="delete_old_job_executions", max_instances=1, replace_existing=True, ) logger.info("Added weekly job: 'delete_old_job_executions'.") try: logger.info("Starting scheduler...") scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") scheduler.shutdown() logger.info("Scheduler shut down successfully!") in my apps.py : class UsersConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "users" def ready(self): if settings.SCHEDULER_DEFAULT: from .operator import Command Command.start(self) please give me some wisdoms!! ps. since Mar 6 2022, django-apscheduler hasn't been updated... it can … -
Not recognizing components when using django-split-settings
Never used this app; first time using it. I have a problem with recognizing the components from one of my settings files. Here is my directory structure: survey/settings/ ├── components │ ├── common.py │ ├── directory_manipulation.py │ ├── django_allauth.py │ ├── django_crispy_forms.py │ ├── django_tailwind.py │ └── __init__.py ├── enviroments │ └── __init__.py ├── __init__.py └── __pycache__ └── __init__.cpython-311.pyc Here is my settings/__init__.py file: """ This is a django-split-settings main file. For more information read this: https://github.com/sobolevn/django-split-settings Default environment is `developement`. To change settings file: `DJANGO_ENV=production python manage.py runserver` """ from split_settings.tools import optional, include base_settings = [ # You can even use glob: 'components/*.py' ] # Include settings: include(*base_settings) Here is my settings/django_allauth.py AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] from components.base import INSTALLED_APPS INSTALLED_APPS += ( 'allauth', 'allauth.account', 'allauth.socialaccount', 'django.contrib.sites', ) SITE_ID = 1 Here is my settings/common.py """ Django settings for survey project. Generated by 'django-admin startproject' using Django 4.1.9. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path # Build … -
Django : DoesNotExist Error raised in post_signal handler
Trying to delete a Task instance with its subtasks, I encounter DoesNotExist: Task matching query does not exist. The following is the error message: Traceback (most recent call last): File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/fields/related_descriptors.py", line 218, in __get__ rel_obj = self.field.get_cached_value(instance) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/fields/mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^ KeyError: 'supertask' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/crackers/views.py", line 73, in delete print(task.delete()) ^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/base.py", line 1132, in delete return collector.delete() ^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/deletion.py", line 512, in delete signals.post_delete.send( File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/dispatch/dispatcher.py", line 176, in send return [ ^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/dispatch/dispatcher.py", line 177, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/crackers/signals.py", line 10, in reassess_achievement if instance.supertask is not None and instance.supertask.completed == False: ^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/fields/related_descriptors.py", line 236, in __get__ rel_obj = self.get_object(instance) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/fields/related_descriptors.py", line 199, in get_object return qs.get(self.field.get_reverse_related_filter(instance)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/thebjko/dev/TrackCracker/venv/lib/python3.11/site-packages/django/db/models/query.py", line 637, in get raise self.model.DoesNotExist( crackers.models.Task.DoesNotExist: Task matching query does not exist. So far, I have figured out that the error is related to signal handler, since the same error does not … -
django channels app is blocking when handle many requests
i have a DRF project, using django channels, i have a endpoint that handles thousands requests for each 5seconds, sometimes this endpoint is blocking my app, what would be the best way to handle it? some posts adivises to use raise StopComsumer() in the disconect method, but not resolve this is my consumer class ChargerSessionConsumer(AsyncJsonWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.client_id = None self.group_name = None async def connect(self): self.group_name = 'room' self.client_id = self.scope["url_route"]["kwargs"]["client_id"] await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.channel_layer.group_add( self.client_id, self.channel_name ) await self.accept() async def websocket_disconnect(self, message): await self.channel_layer.group_discard( self.group_name, self.channel_name ) await self.channel_layer.group_discard( self.client_id, self.channel_name ) raise StopConsumer() -
Add Django super user token in http request
I use Django (as backend and frontend) for a website. I want to create http request with the condition (of use) to be Django super user. But I don't know how to add in the headers the token (or the proof that the user that uses the request is a super user). I tried this with the csrf token : First I use the {% csrf_token %} in the template. <form action="#" id="admin-add-event" method="POST"> {% csrf_token %} ... <button type="submit" id="admin-submit">Add event</button> </form> const url = `${window.BASE_URL}events/`; const form = document.getElementById('admin-add-event'); const data = { ... } let xhr = new XMLHttpRequest(); xhr.open('POST', url , true); xhr.setRequestHeader('X-CSRFToken', form.elements.csrfmiddlewaretoken.value); xhr.setRequestHeader("Content-Type", "application/json"); xhr.onload = function () { ... } xhr.send(JSON.stringify(data)); And in the Django view of the endpoint : @api_view(['GET', 'POST']) def all_events(request): if request.method == 'POST': if not request.user.is_superuser: return Response(status=status.HTTP_401_UNAUTHORIZED) # etc ... But the check of super user fails always I precise that I don't want to implemente a user system. I want to use the system of super user of Django. Thanks in advance ! -
How to use Django ImageField to upload to Google Cloud Storage instead of local
I want to use Django's ImageField on a model so people can upload a logo. I found the ImageField however reading from the docs it says Django stores files locally, using the MEDIAROOT***andMEDIAURL** settings.py I'm wondering how I can change the *upload_to= behavior to upload to a gcp bucket instead? If it's possible when I call .save what is saved to the database, the gcp bucket url? From reading the docs it doesn't say one way or the other if this is possible or if all images should be stored locally where the service is being ran. I have thought of saving the binary images directly to the db but that seems inefficient. -
How to add prefix before token in request using drf-yasg or drf-spectacular
I need add prefix "Token" before token in request header when using drf-yasg or drf-spectacular to create django drf API doc. I have tried multiple tests: Middleware: SWAGGER_SETTINGS 3)SPECTACULAR_SETTINGS: Token plus token in authorize form: Url configs: Options 1), 2) and 3) the request headers are: and with 4) return 401 http status code with the options 1), 2), 3) I receive 401 ""Authentication credentials were not provided." and with 4) invalid token Can you help me please? -
Django reverse() behind proxy
My Django REST API is deployed behind an API Gateway (Kong). I want to reserve() some urls in my APIViews. I would like to ask for help to get the right url format. Based on basepath of the API gateway. Communication flow: Client (requesting basepath) <-> Kong (forwarding to upstream) <-> Apache (Reverse Proxy) <-> Django Kong defines a basepath and an upstream to forward client request to Django. Kong includes X_FORWARDED_HOST and X_FORWARDED_PATH in the HTTP header. X_FORWARDED_PATH contains the basepath of the gateway. X_FORWARDED_HOST contains the gateway-url. Gateway basepath is: /gateway-basepath Upstream path is: mydomain.com/py/api/v1 Basically, without gateway, Django reverse() creates following url for users endpoint: mydomain.com/py/api/v1/users/ With the API gateway, the Django creates follow path: apigatewayurl.com/gateway-basepath/py/api/v1/users/ Django is considering X_FORWARDED_HOST, but not X_FORWARDED_PATH I need following result: apigatewayurl.com/gateway-basepath/users Otherwise the Django url resolving is not usable within the api gateway. I would appreciate any help. urls.py from rest_framework.views import APIView from rest_framework import routers from . import views class APIRootView(APIView): def get(self, request, format=None): return Response({ 'users': reverse('user-list', request=request, format=format), }) router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) urlpatterns = [ path('api/v1/', APIRootView.as_view(), name="api_root"), ] urlpatterns += router.urls views.py from rest_framework import viewsets from django.contrib.auth import models as django_models … -
Django 404 email notification
I want to get an email every time someone on my site gets a 404. I added the following code to my settings.py file DEBUG = False MANAGERS = ADMINS MIDDLEWARE = [ 'django.middleware.common.BrokenLinkEmailsMiddleware', ] The problem is that it just doesn't work. After reading this ticket I decided to try to following I went to the file django/middleware/common.py And made a change to the following class class BrokenLinkEmailsMiddleware(MiddlewareMixin): def process_response(self, request, response): """Send broken link emails for relevant 404 NOT FOUND responses.""" if response.status_code == 404 and not settings.DEBUG: domain = request.get_host() path = request.get_full_path() referer = request.META.get("HTTP_REFERER", "") if not self.is_ignorable_request(request, path, domain, referer): ua = request.META.get("HTTP_USER_AGENT", "<none>") ip = request.META.get("REMOTE_ADDR", "<none>") mail_managers( "Broken %slink on %s" % ( ( "INTERNAL " if self.is_internal_request(domain, referer) else "" ), domain, ), "Referrer: %s\nRequested URL: %s\nUser agent: %s\n" "IP address: %s\n" % (referer, path, ua, ip), fail_silently=True, ) return response FROM referer = request.META.get("HTTP_REFERER", "") To referer = request.META.get("HTTP_REFERER", "None") New class class BrokenLinkEmailsMiddleware(MiddlewareMixin): def process_response(self, request, response): """Send broken link emails for relevant 404 NOT FOUND responses.""" if response.status_code == 404 and not settings.DEBUG: domain = request.get_host() path = request.get_full_path() referer = request.META.get("HTTP_REFERER", "None") if not self.is_ignorable_request(request, path, domain, … -
Getting a problem after deploy a Django app on Render
I developed an app in Django using PostgreSQL as DataBase, on a local environment it works without problems, but when it was deployed on Render.com it the app throws me this error. I had to set the debug in True to watch the error This is that Render console shows me: django.db.utils.ProgrammingError: relation "management_notificacion" does not exist Jun 28 04:55:41 PM LINE 1: SELECT COUNT(*) AS "__count" FROM "management_notificacion" ... This is the line of code that is given the error, but in local works without problems context_processors.py from management.models import * def get_notificaciones(request): notificaciones = Notificacion.objects.filter(receptor=request.user.id)[:3] no_vistas = Notificacion.objects.filter(receptor=request.user.id, visto=False).count() return { 'notificaciones': notificaciones, 'no_vistas': no_vistas } def get_mensajes(request): mensajes = Mensaje.objects.filter(receptor=request.user.id)[:4] no_vistos = Mensaje.objects.filter(receptor=request.user.id, visto=False).count() return { 'mensajes': mensajes, 'no_vistos': no_vistos } If anyone can give a hint to solve this, I'll be so grateful! -
How can I modify attributes of objects in a Django queryset for data presentation without modifying the original object?
I want to present a list of objects for which I want to filter/modify one attribute during the presentation of the data. Something close to an annotation, but I did not manage to do it with annotations. These are the models class Airline (models.Model): name = models.CharField() destinations = models.ManyToManyField("city") customers = models.ManyToManyField("user") class City (models.Model): name = models.CharField() country = models.CharField() class User (models.Model): name = models.CharField() preferredDestinations = models.ManyToManyField("city") I want, for a given user, present a list of the Airlines the user is customer, and for each Airline present the list of destinations for the Airline. But instead of presenting all the airline destinations I only want to present the destinations preferred by the user. e,g, Airline1.destinations=["New York", "London", "Paris", "Madrid] Airline2.destinations=["Madrid", "Barcelona", "Rome", "Berlin", "London"] User1.preferredDestinations=["Madrid", "Barcelona", "Paris"] With user1 being a customer of Airline1 and Airline 2, I want the page to present a table showing to which of the user preferred destination every airline flies to. I.e. I do not want to see all the destinations the airline flies to, only the ones the user is interested: E.g. Welcome User1! These are your airlines that fly to your preferred destinations Airline | Destination | … -
DJANGO: replace a combobox created successfully in a list of views.py, with one created with classes in forms.py?
I'm new to Django. I saw that there are 2 different ways to create comboboxes and forms. I would like to replace my current mode, already successfully created, with another mode. WAY 1 (works well, correctly): I have a combobox that works fine, created by putting the items in a list in views.py, for example: color_choices = ("Red","Blue","Black", "Orange"). I am currently using this mode. WAY 2: Way 1 works fine correctly for me, but only now I've seen that it's possible to create comboboxes also by creating a forms.py file, importing from django import forms, and then writing the items in the classes. The combobox uses a static list QUESTION: How can I modify my code (which uses Way 1) and replace it with forms.py with Way 2 classes? I would like to use the classes and the forms.py file, and I would not like to use the items in the views.py file (it works correctly fine with Way 1). Can you show me how I can use Way 2 correctly? Thank you all! Which of the two ways is more correct and better in terms of loading speed? Thank you all! P.S: comboboxes are database independent. they don't … -
Google Analytics GA4
The number of users who have registered on my website on GA4 is less than the one I got from the DB. Anyone can help here? Both google analytics and extracted data are in the UTC time and on GA4 Im checking the total users value Thannk you! -
Django xhtml2pdf, changing to custom font not working
I'm trying to change the font in my html to pdf project using xhtml2pdf (version 0.2.11) in Django (version 4.2.2). I'm running the project on my Windows 11 Home 22H2, using python 3.11.0 Here is how I try to import the font file html snippet, but the font did not reflect on the page. html snippet @font-face { font-family: Ysabeau Infant; src: url('fonts/Ysabeau-Infant.ttf'); } Views.py def report_rednder_pdf_view(request, *args, **kwargs): pk = kwargs.get('pk') report = get_object_or_404(Report, pk=pk) template_path = 'reports/pdf2.html' context = {'report': report} # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') # If downloadable remove comment #response['Content-Disposition'] = 'attachment; filename="report.pdf"' # If viewable remove comment response['Content-Disposition'] = 'filename="report.pdf"' # find the template and render it. template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF( html, dest=response) # if error then show some funny view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response I tried using the absolute path C:\Users\USER\Desktop\PROJECT\static\fonts\Ysabeau-Infant.ttf instead of the relative path, but that did not work, I get the error: TTFError Exception Value: Can't open file "C:\Users\USER\AppData\Local\Temp\tmpwsd3c9z2.ttf" and from the terminal I get the error, Permission denied: 'C:\Users\USER\AppData\Local\Temp\tmpwsd3c9z2.ttf' I tried running … -
Use user id in bigquery SQL query that is passed into the function via an argument
I'm trying to get the last synced data from bigquery for the given user The query consists of this: mc_query = """ SELECT _fivetran_synced, connector_name FROM `database....` WHERE connector_name = 'pm_' + user.id + '_facebook_pages' """ This is the function below: def facebook_last_pulled(user): # i've tried this code on the line below and replaced user.id with current_user_id in order to make sure the id is in the form of a string as well as using the CAST method on user id in the query #current_user_id = str(user.id) mc_query = """ SELECT _fivetran_synced, connector_name FROM `database....` WHERE connector_name = 'pm_' + user.id + '_facebook_pages' """ print(user.id) last_pulled_data = google_big_query(mc_query) Where I print user.id I get the user id I'm looking for but when I put it into the query I get GenericGBQException, Reason: 400 Unrecognized name: user at [4:45]. So from the seems of it user isn't getting picked up in the variable mc_query, anyone know the reason I'm not getting user in there or a way to solve this? I've tried setting a variable for user.id and using the variable instead of user.id as well as the CAST method in order to change it to a string inside the query. … -
How to add multiple "OR" queries in Django
I have 2 models, Item and Category, the model Item has category field as a foreign key In my views.py I get a list of queries from a POST request queries = ['category1', 'category2', 'category3', ...] I don't know the number of the queries I will get from the request, and I want to filter the Item model based on category field I tried this from django.db.models import Q from .models import Item, Category from django import views class myView(views.View): def post(self, request): queries = request.POST.get('queries', '') if queries: queriesList = [] queries = queries.split(',') # queries = ['category1', 'category2', ....] for query in queries: queriesList.append(Q(category__icontains=query)) queryset = Item.objects.filter(*queriesList) # this will do AND but won't do OR # I tried: queryset = Item.objects.filter([q | Q() for q in queriesList]) but it didn't work Also I tried queryset = Item.objects.filter(category__in=queries) but it's case sensitive -
Refreshing variables shown in a html file by pressing a button
I have a program that takes data from a sensor in my raspberry pi and I want the data taken from the raspberry to be shown in a web page, the idea is that it can be updated every time you press a button that its in the web. I'm right now using django to create the web, but I don't know if it is too much complex for what I'm trying to do. Here I have my data extractor code: import bme280 import smbus2 from time import sleep port = 1 address = 0x76 # Adafruit BME280 address. Other BME280s may be different bus = smbus2.SMBus(port) bme280.load_calibration_params(bus,address) bme280_data = bme280.sample(bus,address) humidity = bme280_data.humidity pressure = bme280_data.pressure ambient_temperature = bme280_data.temperature Here I have the django views.py file: from django.shortcuts import render from django.http import HttpResponse import sys sys.path.append('/home/jordi/weather-station/data') from bme280_sensor import humidity, ambient_temperature, pressure from subprocess import run,PIPE # Create your views here. def home(request): return render(request, 'base.html', {'humitat': humidity, 'temperatura': ambient_temperature, 'pressio': pressure}) def index(request): return HttpResponse("EL temps de vilafant") and finally here I have my html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p>Aqui podras veure el temps de vilafant … -
Python Django API authentication
I am new to Django. I need to use some API to get the .json format data. But the API needs authentication. I have already got the username and password. I see my colleague use Postman to enter the account then he can see the JSON file in intellij. I am in Pycharm, I am wondering is there some code I can use to realize the same function of postman rather than install the postman? What I have: API URL, account username and password Any help is really appreciated, also please let me know which file I should write in the Django, views.py?? Update: thank you for all the help!I am sorry I am not familiar with the postman, I only know my colleague show me how to enter the username and password. I have the API/URL, when I click on it, it will direct me to a page with JSON format data, looks like this {"businessOutcomes":[{"businessOutcomeId":"1234","origin":"JIRA",.....]} I have over 100 this kind of URL/API, I want to get the .json file in pycharm and so I can make them as the df to do the data analysis I want. And my colleague told me that the API has some … -
Cant run gTTS in Django
I am trying to build text to voice app and I had a problem with gTTS. the code I try views.py from django.shortcuts import render from gtts import gTTS from django import forms textfortts = [] class UploadFileForm(forms.Form): tts = forms.CharField(label= " convert text to audio here") def text_to_voice(request): if request.method == "POST" : form = UploadFileForm(request.POST) if form.is_valid(): tts = form.cleaned_data["tts"] textfortts.append(tts) obj = say(language='en-us', text= textfortts) return render(request, "text_to_voice_main.html",{ "form": UploadFileForm(), "lang": "en-us", "text": "text to say", }) text_to_voice_main.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Text to voice</title> </head> <body> <form action=""> {% csrf_token %} <audio src="{% say lang text %}" controls {% load gTTS %} ></audio> {{form}} <input type="submit"> </form> </body> </html> I need to have a text to voice converter. can i know what is the probelms and how i can fix it? -
Django forms passing request via get_form_kwargs fails to give form access to self.request.user
Goal I need to make the user accessible to a form for validation (i.e., through self.request.user) Approach Taken I use the get_form_kwargs() function in my view to make the request available to my form (as suggested here: Very similar problem). Problem Despite following the steps outlined in the StackOverflow answer linked above, I'm getting the error 'NoneType' object has no attribute 'user' Code views.py views.py class MemberDetailView(LoginRequiredMixin, generic.DetailView): """View class for member profile page""" model = User context_object_name = 'user' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs,) context['form'] = JoinCommunityForm() return context class JoinCommunityFormView(FormView): """View class for join code for users to join communities""" form_class = JoinCommunityForm def get_form_kwargs(self, *args, **kwargs): form_kwargs = super().get_form_kwargs(*args, **kwargs) form_kwargs['request'] = self.request return form_kwargs def post(self, request, *args, **kwargs): """posts the request to join community only if user is logged in""" if not request.user.is_authenticated: return HttpResponseForbidden return super().post(request, *args, **kwargs) class MemberDashboardView(View): """View class to bring together the MemberDetailView and the JoinCommunityFormView""" def get(self, request, *args, **kwargs): view = MemberDetailView.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = JoinCommunityFormView.as_view() form = JoinCommunityForm(request.POST) if form.is_valid(): forms.py forms.py from communities.models import Community, UserRoleWithinCommunity class JoinCommunityForm(forms.Form): pin = forms.RegexField('^[A-HJ-NP-Z1-9]$', max_length=6, label='', widget=forms.TextInput(attrs={'oninput': 'this.value = this.value.toUpperCase()'})) … -
Getting error : django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username || I'm a beginner trying to save in Djnago
I'm trying to learn django. Just started with a project. It has 2 applications so far. Employee poll I'm trying to do it via CMD. It shows the following issues. Actually I was trying to follow a tutorial for a django project. I checked, there is no UNIQUE keyword used in the code. I even tried deleting and then saving but didn't resolve. Employee :-- **models.py (employee) : ** from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) designation = models.CharField(max_length=20, null=False, blank=False) salary = models.IntegerField(null=True,blank=True) class Meta: ordering = ('-salary',) #minus sign indicates that we need the result in decending order def __str__(self): return "{0} {1}". format(self.user.first_name, self.user.last_name) @receiver(post_save, sender=User) def user_is_created(sender, instance, created, **kwargs): if created: Profile.object.create (user=instance.) else: instance.profile.save() Poll :-- **models.py (poll)** from django.db import models from django.contrib.auth.models import User # Create your models here.` `class Question(models.Model): # models.Model is the base model. we just need to extend it. #All the class varibales will be considered as the columns of the table. title = models.TextField(null=True, blank = True) status = models.CharField(default = 'inactive', max_length=10) #if we don't pass … -
use django-filters on a queryset in the backend
Assuming I have a queryset and some filters I got from the front end, can I use the pre-defined FilterSet to filter over the queryset? example: models.py class User(models.Model): name = models.CharField(...) score = models.IntegerField(...) filters.py class UserFilter(django_filters.FilterSet): q = django_filters.CharFilter(method="text_search_filter") score_min = django_filters.NumberFilter(field_name="score", lookup_expr="gte") score_max = django_filters.NumberFilter(field_name="score", lookup_expr="lte") class Meta: model = User fields = {} def text_search_filter(self, queryset, name, value): return queryset.filter(name__icontains=value) views.py class UserView(View): filter_class = UserFilter ... def post(self, request, **kwargs): qs = User.object.all() filters = {"q": "john doe", "score_min": 5, "score_max": 10} Can I call UserFilter and pass the filter dict? To prevent me applying those filters again, since I already have those defined in the UserFilter Here's what I tried and didn't work: views.py def post(self, request, **kwargs): qs = User.object.all() filters = {"q": "john doe", "score_min": 5, "score_max": 10} filter = UserFilter(request.GET, queryset=qs) filter.is_valid() qs = filter.filter_queryset(qs) # Did not apply the filters