Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NextJS and Django Project Deploy
Does anyone know how to deploy the django+nextJs app currently, my frontend is running on localhost:3000 and Django at 127.0.1:8000 and its is working perfectly on my local machine I want to deploy it on a live server anyone who knows how to do this I have deployed the next app on Vercel (https://cropsight-dusky.vercel.app/) but it will not move further from login unless Django is also running simultaneously. I have checked it If the nextJs project is running on Vercel and my Django is running locally then the request from front end will come to me -
How can I separate my labels in the x-axis into separate "categories" in my chart?
If my question didn't make sense then let me explain. Basically I am creating a web app for tracking expenses and I want to incorporate a chart to showcase the expenses in a graphical way. I have made for categories which take in separate data, but for some reason when I render the chart it shows all the categories combined as one. (Attachment is provided) Image of the Bar chart. For this reason only the line and bar chart show but the doughnut (which I want) and the pie charts don't work am guessing because of how the labels (categories) are combined into one. Here is the code for my js file: const renderChart = (data, labels) => { const ctx = document.getElementById('myChart').getContext('2d'); new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: 'Current Month Expenses', data: data, }] }, options: { borderWidth: 10, borderRadius: 2, hoverBorderWidth: 0, plugins: { legend: { display: false }, }, }, }); } const getChartData=() => { console.log("fetching") fetch('expense_category_summary') .then((res)=>res.json()) .then((results)=>{ console.log("results", results); const category_data = results.expense_category_data; const [labels, data] = [ Object.keys(category_data), Object.values(category_data), ]; renderChart([data], [labels]); }); }; document.onload = getChartData(); Please help, I am in a tight deadline. If there … -
Django quiz- multiple question- database falsely saves correct answers
I am striving to build a multiquestion quiz option, but I cannot get my postgreSQL save the correct data. The database only saves the first option without it mattering whether it is the correct answer or not and whether there are more correct answers. "GET /multi-form/ HTTP/1.1" 200 7693 <QueryDict: {'csrfmiddlewaretoken': ['ALONiRKNa0QKQe6LQWacVz9vSQZPbFuyfdaLimGg9czBEy46hQAbAGyQatRLpI33'], 'question': ['Question100'], 'language_name': ['5'], 'ans_count': ['5'], 'answer_0': ['99'], 'answer_1': ['98'], 'answer_2': ['97'], 'is_correct_2': ['on'], 'answer_3': ['Qaz'], 'answer_4': ['Dacia'], 'is_correct_4': ['on'], 'Submit': ['Senden']}> 5 True [{'text': '99', 'is_correct': False}] 99 is chosen as the only answer, but it is not correct ans I chose more correct options as you can spot on the screenshot. forms.py class AddMultipleForm(forms.ModelForm): ans_count = forms.IntegerField(min_value=1, label="Number of Answers Anzahl der Antworten") class Meta: model = MultiQuesModel fields = ["question", "language_name"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ans_count = self.initial.get("ans_count", 1) for i in range(ans_count): self.fields[f"answer_{i}"] = forms.CharField(max_length=200, required=True) self.fields[f"is_correct_{i}"] = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={"class": "checkbox"}) ) def clean(self): cleaned_data = super().clean() ans_count = cleaned_data.get("ans_count") print(ans_count) answers = [] for i in range(ans_count): answer_text = cleaned_data.get(f"answer_{i}") is_correct = cleaned_data.get(f"is_correct_{i}") if answer_text: answers.append({"text": answer_text, "is_correct": is_correct}) if not answers: raise forms.ValidationError( "Please fill out at least one answer. Bitte füllen Sie mindestens eine Antwort aus." ) cleaned_data["answers"] … -
React, When i call handleSubmit() function i am sending data in application/json and multiform/data to backend but none data in student_image: null
please see the code that I have to handle application/json and multiform/data type of data along with other fields student_image: fileState, where fileState is e.target.file[0] value which is the image and other field are just application/json i think but this fileState need multiform/data. how to sent data to api as my api accepts list object of all or any other idea to store image along with other field value in models.py in drf const handleSubmit = () => { let dataToSend = {}; if (Array.isArray(formData)) { // Handle array data dataToSend = formData.map((formFields, index) => ({ // // Map the fields accordingly for each object in the array // // Adjust this based on your data structure sn: formFields.sn, student_image: fileState, // Add other fields as needed })); } else if (typeof formData === 'object') { // dataToSend = [formData] // Handle object data dataToSend = [{ // Map the fields accordingly for the object // Adjust this based on your data structure nepali: formData.nepali, international: formData.international, graduate_school_or_campus: formData.Campus, student_image: fileState, first_name: formData.first_name, middle_name: formData.middle_name, last_name: formData.last_name, email: formData.email, contact_no: formData.contact_no, gender: formData.gender, blood_group: formData.blood_group, ethnicity: formData.ethnicity, religion: formData.religion, date_of_birth_bs: formData.date_of_birth_bs, date_of_birth_ad: formData.date_of_birth_ad, batch: formData.batch, disability_status: formData.disability_status, sponsorship_status: formData.sponsorship_status, rural_district: … -
Does user encoding of uploaded files matter and how to configure it?
I'm making a site on Django. The functionality is as follows - users can download pdf files for processing (converting to different formats, extracting text, etc.). This is how I receive a file from a user and process it - def post(self, request, *args, **kwargs): text = services.extract_text_from_pdf(request.FILES.get('file')) I had the following question - what if users will download files in different encodings? Does their encoding matter or do they all end up being utf-8? I read this from the Django documentation. But I didn't quite understand how to configure file encoding. -
How to use django tags in next.js javascript file?
I have a full stack application built in next.js as frontend and django as backend. The frontend is full next.js and react. I want to use django tags in the javascript pages files the code that i want to use is looking like this : {% for item in items %} <div> <a href="{% url 'item:detail' item.name %}"> <div> <img alt="{{ item.name }}" src="{{ item.image.url }}" class="rounded-t-xl"> </div> <div class="p-6 bg-white rounded-b-xl"> <h2 class="text-2xl">{{ item.name }}</h2> <p class="text-gray-500">Price: {{ item.price }}</p> </div> </a> </div> {% endfor %} Those are some information for an item that is stored in the database through django. I checked another post from stackoverflow and said something like this You can't add any Django template code in js file directly. There are 3 ways you can add the first_name in js file. Write a django ajax views and call the api for first_name from your js file as soon as your page is loaded. or render your first name in your html file hidden input fields and than grab the fields value it's name or id from your jsfile or put a utill function on your html js <sccript> tags which are gonna call you driver.js … -
Django CSRF with Angular frontend served from different domains
I have a dockerized Django backend that uses DRF, django cors headers to allow communications over localhost to the Angular app. The docker-compose.yml file looks like this: version: "3.9" services: db: image: postgres volumes: - ./postgres/db:/var/lib/postgresql/data ports: - "5432:5432" environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres backend: container_name: backend-dev-diary build: context: . dockerfile: ./build/backend/dockerfile command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - ./backend/dev_diary:/code ports: - "8005:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db frontend: container_name: frontend-dev-diary build: context: . dockerfile: ./build/frontend/dockerfile command: sh -c "npm install && ng serve --poll 2000 --host 0.0.0.0 --disable-host-check" volumes: - ./frontend/dev-diary:/code ports: - "8080:4200" depends_on: - backend I want to use session based auth and csrf protection on angular. In the django settings I've set: CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", ] REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"], "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", ], "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", } CSRF_COOKIE_SAMESITE = "Lax" SESSION_COOKIE_SAMESITE = "Lax" CSRF_COOKIE_HTTPONLY = True SESSION_COOKIE_HTTPONLY = True CSRF_TRUSTED_ORIGINS = [ "http://localhost:8080", ] if DEBUG == False: CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True Now I created an endpoint that generates a CSRF token and I read the value in Angular. Now when I make a request I include credentials and … -
Django order by pviot table column
I want to order tasks within a bucket based on the 'order' column in the 'bucket_task' table. Tasks and buckets have a many-to-many relationship. How can I achieve this? My models: class Bucket(AbstractModel): user = models.ForeignKey(User, related_name='buckets', on_delete=models.deletion.DO_NOTHING) unique_id = models.CharField(max_length=255, default=uuid.uuid4, unique=True) title = models.CharField(max_length=191, blank=True) order = models.IntegerField(default=1) class Task(AbstractModel): user = models.ForeignKey(User, related_name='tasks', on_delete=models.deletion.DO_NOTHING) unique_id = models.CharField(max_length=255, default=uuid.uuid4, unique=True) title = models.CharField(max_length=191, blank=True) class BucketTask(AbstractModel): bucket = models.ForeignKey(Bucket, on_delete=models.deletion.CASCADE) task = models.ForeignKey(Task, on_delete=models.deletion.CASCADE) order = models.IntegerField(default=1) My view: class BucketsView(generics.ListCreateAPIView): permission_classes = [IsAuthenticated] serializer_class = BucketSerializer model = Bucket def get_queryset(self): queryset = self.model.objects.filter( user=self.request.user, deleted_on__isnull=True ).prefetch_related( 'tasks' ).select_related('user').order_by('order') return queryset My Serializer: class BucketSerializer(ModelSerializer): tasks = TaskSerializer(many=True, read_only=True) class Meta: model = Bucket fields = "__all__" read_only_fields = ['unique_id', 'tasks'] extra_kwargs = {"user": {"required": False}} -
Error while using migrate in Django to postgresql
`I am using postgresql as database for my django project and it is showing me that i don't have permission to even create the data tables when I run migrate command. Error: django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (permission denied for schema public LINE 1: CREATE TABLE "django_migrations" ("id" bigint NOT NULL PRIMA... ^ ) My code: `DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "knapds", "USER": "admin", "PASSWORD": "password", "HOST": "127.0.0.1", "PORT": "5432", } }` `CREATE DATABASE knapds; CREATE USER knapds WITH PASSWORD 'password'; ALTER ROLE system SET client_encoding TO 'utf8'; ALTER ROLE system SET default_transaction_isolation TO 'read committed'; ALTER ROLE system SET timezone TO 'Africa/Johannesburg'; GRANT ALL PRIVILEGES ON DATABASE knapds TO system; \q`` -
How to generate automatically links to picture with spec. size?
I'm a beginner in programming, I've done a small project in Django, but nothing special. I was given a recruitment task with Django RESTframework, but I don't really know how to approach it. I don't want a ready-made solution, but some guidance or advice on how to go about it. Possibly a shared coding :) Task: Using Django REST Framework, write an API that allows any user to upload an image in PNG or JPG format. You are allowed to use any libraries or base projects / cookie cutters you want (but using DRF is a hard requirement). Skip the registration part, assume users are created via the admin panel. Requirements: it should be possible to easily run the project. docker-compose is a plus ## This is no problem. This is main problem. users should be able to upload images via HTTP request users should be able to list their images there are three builtin account tiers: Basic, Premium and Enterprise: users that have "Basic" plan after uploading an image get: a link to a thumbnail that's 200px in height users that have "Premium" plan get: a link to a thumbnail that's 200px in height a link to a thumbnail … -
aws elastic beanstalk deployment error: 502 gateway error
I've been trying to deploy a django application using Django 4.2.6 on the latest platform that AWS EB has to provide: Python 3.9 running on 64bit Amazon Linux 2023/4.0.4 After any try or redeploy I've been getting a 502 Bad gateway issue and I would appreciate some help in debugging this. On the web.stdout.log file I see this log line: web[2059]: ModuleNotFoundError: No module named 'ebdjango.wsgi' which is confusing because I don't see anything I've done different than what's been suggested across the internet via blogposts and so on. All my sourcecode is available here: https://github.com/kolharsam/assignment-practical-swe These are the links I've been looking into: https://medium.com/@justaboutcloud/how-to-deploy-a-django3-application-on-elastic-beanstalk-python3-7-and-amazon-linux-2-bd9b8447b55 https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html https://testdriven.io/blog/django-elastic-beanstalk/ -
How to Implement Withdrawal Functionality in Django: Integrating Razorpay and Bank Transfers
I am working on a Django web application where users need to be able to withdraw money from their accounts. I am looking for assistance in implementing a withdrawal functionality within my Django project. The process involves saving the withdrawn amount to the Razorpay dashboard and then transferring it to the user's linked bank account. -
SessionInterrupted at /accounts/login/
I have some problems with this error. Error began to appear after implementing the new functionality. Which involves checking whether the user's password has been marked for change. After logging in, the function checks whether the password needs to be changed.If so, it adds a variable to the user's session.The decorator on each page is used to check whether a variable in the session has been set. When the password needs to be changed, the decorator redirects to the password change page. After the change, the variable is deleted and information from the database.The error appears when the user logs in again after changing the password. def check_reset_pass(function): @wraps(function) def wrap(request, *args, **kwargs): if request.session['pass_reset_needed']: return redirect(reverse('password_reset_form')) return function(request, *args, **kwargs) return wrap After changing the password, the user remained on the website. I tried to force the user to log out after changing the password. But that didn't solve the problem. -
Django function based view Login
I've been trying to write a view for users to login.. def LoginView(request): form = LoginForm() if request.method == "POST": form = LoginForm(request.POST) if request.user.id: if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) login(request, user) return redirect("/") else: return render( request, "api/login.html", {"massege": "the user NOT found , register here ", "form": form}, ) return render(request, "api/login.html", {"form": form}) login Form class LoginForm(forms.Form): username = forms.CharField(max_length=70) password = forms.CharField(max_length=65, widget=forms.PasswordInput) class Meta: fields = "__all__" when I try to login as user who exsits in database the funciton eccepts it as non exists user ,and display what under else condition to the template -
Problem with displaying the 'Remove from cart' button in the Django session cart
Good afternoon, I am currently working on a bookstore project, I have a basket for unauthorized users, the problem is that I want the delete button from cart to appear on the template if there is this book in the session basket and hide if this book is not in cart, but this logic does not work because the button does not it is displayed even when there are many copies of the same book in the basket, I need your help. Thank you in advance for your time! views that are associated with a cart of books: class CartView(TemplateView): template_name = 'shop/cart.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) created = self.request.session.pop('created', False) # Извлекаем значение и удаляем его из сессии if self.request.user.is_authenticated: cart = Cart.objects.get(user=self.request.user) cart_items = CartItem.objects.filter(cart=cart) total_price = 0 for cart_item in cart_items: book = cart_item.book if book.discounted_price: total_price += book.discounted_price * cart_item.quantity else: total_price += book.price * cart_item.quantity context["cart"] = cart context["cart_items"] = cart_items context["total_price"] = total_price context["created"] = True else: cart = self.request.session.get('cart', {}) context['cart'] = cart # Создаем список книг на основе идентификаторов из корзины book_ids = [int(book_id) for book_id in cart.keys() if book_id.isnumeric()] books = Book.objects.filter(id__in=book_ids) # Генерируем список книг и их количество … -
Django channels: Execute consumer code from django drf view
I have django app with drf view and I want to call consumer by its name from the view. I'm using the following packages versions: Django==4.2.5 djangorestframework==3.14.0 channels==4.0.0 the following code prints nothing: settings.py: INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... 'rest_framework', 'drf_yasg', 'channels', ] CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", }, } consumers.py: class TestConsumer(SyncConsumer): def test_consumer(self, message): print('start consumer') job = Job.objects.get(id=message.get('job')) job.status = Job.JobStatus.RUNNING job.save() print('Finish consumer') routing.py: ChannelNameRouter({ "test_consumer": TestConsumer, }) views.py: class TestAPIView(APIView): @transaction.atomic def post(self, request, *args, **kwargs): message = {"selected_indices": 'test', "session_search": ''search_test', "job": 1} channel_layer = get_channel_layer() async_to_sync(channel_layer.send)("test_consumer", message) -
How to solve create next app npm run build placing href with _next instead of .next in the html files from the server?
I built an app on django as backend and next.js as frontend. As I am integrating next.js to django I have seen an error when i build the next.js app in the server folder the html pages's hrefs are linked to /_next/... which does not exists as you know when u build the project it automatically creats the .next folder I can see that this is a similar question but without a windows solve : Renaming '_next' to 'next' in the out directory: NextJS tried several work arounds but in vain -
How to run databricks notebook from django web application
I am new to Django, in my project I have below requirement. Run data bricks notebook from web application. For example I have date dropdown in my Django web application and In my databricks notebook I have business logic in it and this notebook will run based on date as parameter and out put this will store as a delta table in ADLS. Now, if user select date from web application(Django),and this date should act as input to the databricks notebook and perform business logic in it and out put of this note book which is store as delta table should return to my web application. if this is possible I kindly request you list down the steps please. waiting for favorable reply. Thanks. I have tried below this, but it is not suitable to my requirement. https://datathirst.net/blog/2019/3/7/databricks-connect-finally/ -
How to localize settings in Wagtail
I am trying to implement localization in Wagtail's settings. I know that Snippets can be localized by inheriting from the TranslatableMixin class. And it works perfectly. However, when I try to localize settings by inheriting from this class in a model that also inherits from BaseGenericSetting to add the model to Wagtail's settings, it does not provide an interface to change the language in the admin panel so that I can create settings for different languages. How can I add an interface for changing the language in the settings, similar to what we do with snippets? For instance, I want to create instances of the below-mentioned model for three different languages (which are added in the LANGUAGES setting in base.py). This means there will be three instances of CompanySettings for three different languages. @register_setting(icon="doc-full") class CompanySettings(TranslatableMixin ,BaseGenericSetting): top_services = models.CharField( _("Top Services"), max_length=250, blank=True, null=True, help_text="add top services separated by comma") copyright_text = models.CharField(_("Copyright Text"), max_length=100, blank=True, null=True) panels = [ FieldPanel('top_services'), FieldPanel('copyright_text') ] I have checked the CompanySettings model by querying its instance to verify whether the locale and translation_key fields are available or not, as these are provided by TranslatableMixin. However, even though they are available, it doesn't … -
Restricting django api to allow access and takes calls from only one domain (xyz.com) website
I have a frontend(react js) and backend api (Django) hosted separately, frontend is hosted on xyz.com and backend is hosted on server.xyz.com. now, the api is https://server.xyz.com which is publicly visible to everyone (in network tab) and anyone is able to access it by making calls. but i want to make it access with only xyz.com website only. My problem is I need to give access to only xyz.com domain and restrict the api to take calls from any other domains or ip addresses. -
Issue with Certbot: "no valid A records found" during certificate renewal
I'm encountering an issue with Certbot while trying to renew SSL certificates for my domain using the --nginx option. The error message I'm getting is as follows: $ sudo certbot --nginx -d your_domain.com -d www.your_domain.com Saving debug log to /var/log/letsencrypt/letsencrypt.log Plugins selected: Authenticator nginx, Installer nginx Obtaining a new certificate Performing the following challenges: http-01 challenge for your_domain.com Waiting for verification... Cleaning up challenges Failed authorization procedure. your_domain.com (http-01): urn:ietf:params:acme:error:dns :: no valid A records found for your_domain.com; no valid AAAA records found for your_domain.com IMPORTANT NOTES: - The following errors were reported by the server: Domain: your_domain.com Type: None Detail: no valid A records found for your_domain.com; no valid AAAA records found for your_domain.com $ I am not sure exactly what to look for to fix this error. I am using Lindo Akamai and the A/AAAA Record is showing the correct IP address also the website is working fine without as Http. I am using Nginx and Gunicorn for a Django Project. My question how to fix the error everytime I run sudo certbot --nginx -d your_domain.com -d www.your_domain.com -
Starting Django Project with gunicorn: No module named: "myproject"
I am having trouble starting my django project with gunicorn In order to figure out what's wrong, I created an empty django project to work with: myproject - myproject - __init.py__ - asgi.py - gunicorn_config.py ... -wsgi.py - hello.py - manage.py Inside gunicorn_config.py: # gunicorn_config.py pythonpath ='/home/mywsl/.virtualenvs/venvname/lib/python3.10' bind = "0.0.0.0:8000" workers = 4 timeout = 60 Then i go into myproject where wsgi.py is located and does gunicorn -c gunicorn_config.py wsgi:application This raises the following error: [2023-10-07 23:21:39 -0400] [102667] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/mywsl/.virtualenvs/venvname/lib/python3.10/site-packages/gunicorn/arbiter.py", line 609, in spawn_worker worker.init_process() File "/home/mywsl/.virtualenvs/venvname/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() ... File "/home/mywsl/.virtualenvs/venvname/lib/python3.10/site-packages/gunicorn/util.py", line 371, in import_app mod = importlib.import_module(module) (This is where the import module points to outside virtualenv, i don't know if this is normal) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed (It goes back to where my project is, and start tracing python inside virtualenv) File "/home/mywsl/Projectname/myproject/myproject/wsgi.py", line … -
Django field formatting within template defined within the field
I have a custom field called Percentage which I would like displayed in Django templates always with a % sign, so if the DB is holding a Float of 100.00 then in the template it would always render as 100%. I know I can write a template tag however I would like this change to be made globally so I don't need to do template tags everywhere. I've seen packages like dj-money do this so that 1 is formatted as $1 automatically. I've looked at the code but can't see exactly how this is occuring. I've investigated methods like to_python, __str__ and __unicode__ on the field but these don't appear to work. How can I customise the field to always format a particular way in string based situations like django templates and django admin? At present I've just created a custom method per field on the model to do the formatting, however I fee like there should be a way to set this on the field level. Thanks for your help -
Why is my Django view not automatically downloading a file
My view transcribes a file and outputs the SRT transcript. Then it locates and is supposed to auto download theT transcript but nothing happens after transcription completes(the file was submitted on a previous page that uses the transcribeSubmit view. The view that handles and returns the file is the initiate_transcription view). Here is my views.py: @csrf_protect def transcribeSubmit(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) request.session['uploaded_file_name'] = filename request.session['uploaded_file_path'] = fs.path(filename) #transcribe_file(uploaded_file) #return redirect(reverse('proofreadFile')) return render(request, 'transcribe/transcribe-complete.html', {"form": form}) else: else: form = UploadFileForm() return render(request, 'transcribe/transcribe.html', {"form": form}) @csrf_protect def initiate_transcription(request): if request.method == 'POST': # get the file's name and path from the session file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path') if file_name and file_path: with open(file_path, 'rb') as f: path_string = f.name transcribe_file(path_string) file_extension = ('.' + (str(file_name).split('.')[-1])) transcript_name = file_name.replace(file_extension, '.srt') transcript_path = file_path.replace((str(file_path).split('\\')[-1]), transcript_name) file_location = transcript_path with open(file_location, 'r') as f: file_data = f.read() response = HttpResponse(file_data, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename="' + transcript_name + '"' return response else: #complete return render(request, 'transcribe/transcribe-complete.html', {"form": form}) def transcribe_file(path): #transcription logic JS: const form = document.querySelector('form'); form.addEventListener('submit', function (event) { event.preventDefault(); const formData = … -
Django Rest Framework: AttributeError when attempting to serialize Elasticsearch InnerDoc
I am working on a Django project with Elasticsearch, using django-elasticsearch-dsl to create documents from my models. I have set up my documents and am trying to create a serializer for my Contest model. However, when I send a GET request to my endpoint (http://localhost:8000/search/offices/economia/), I encounter the following error: AttributeError at /search/offices/economia/ Got AttributeError when attempting to get a value for field `organization` on serializer `ContestSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `InnerDoc` instance. Original exception text was: 'InnerDoc' object has no attribute 'organization'. Here are my document and serializer definitions: document.py: from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry from core.models import Contest, Organization @registry.register_document class ContestDocument(Document): organization = fields.ObjectField(properties={ 'id': fields.IntegerField(), 'name': fields.TextField(), # ... other fields }) # ... rest of the code serializers.py: from rest_framework import serializers from core.models import Contest, Organization class OrganizationSerializer(serializers.ModelSerializer): # ... code class ContestSerializer(serializers.ModelSerializer): organization = OrganizationSerializer() class Meta: model = Contest fields = "__all__" It seems like, for some reason, an Elasticsearch InnerDoc instance is being passed to the ContestSerializer instead of a Contest model instance, causing the AttributeError. I'm not sure why this is happening or how …