Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send variable from HTML to python Django 5
Hi Im trying to build a html with python in backen (Django 5) and I trying to take a variable from HTML to python I found this old question and try to use that Django - pass value from html template to python function But I stuck in views.py I dont know how set path in url patters and I follow the answear, please can some help to figure out this my view.py file: urlpatterns = [ path('form_page/',views.form_name_view,name='form_page'), path('register/',views.register,name='register'), path('project_info/',views.project_info,name='project_info'), path('user_login/',views.user_login,name='user_login'), from old question Django - pass value from html template to python function <input type="text" name="name_id" placeholder="placeholder value"/> <input type="submit" name="value1"/> <input type="submit" name="value2"/> <input type="submit" name="value3"/> In the view you can then check with: def some_view(request): if request.method == 'POST': if 'value1' in request.POST: # … pass elif 'value2' in request.POST: # … pass elif 'value3' in request.POST: # … pass You can work with a name="…" attribute on the submit <button>s: <form method="POST" action=""> {% csrf_token %} <input type="text" name="name_id" placeholder="placeholder value"/> <input type="submit" name="value1"/> <input type="submit" name="value2"/> <input type="submit" name="value3"/> </form> In the view you can then check with: def some_view(request): if request.method == 'POST': if 'value1' in request.POST: # … pass elif 'value2' in request.POST: … -
Has anyone created a YouTube video to MP3 converter project in Python using Django?
I would like to create a project to convert YouTube videos to MP3 format and download them. If anyone has already done this, could you please share the GitHub repository link so that I can refer to it? I am looking for a YouTube video to MP3 conversion project in Python using Django. I have confusion on handling large size videos. -
Logging inside function called by django-apscheduler
I have running django-specific scheduler: django-apscheduler and it works fine as scheduler, it starts needed job as required, but i have problem with logging inside called function by scheduler. Logger created with no errors reported, with name as defined in settings.py, but looks strange, has some few atributes, has level = 0, and do nothing with logging commands. Part of settings.py LOGGING = { "version": 1, # the dictConfig format version "disable_existing_loggers": False, # retain the default loggers "handlers": { "debug_file": { "class": "logging.FileHandler", "filename": BASE_DIR / "main/logs/debug.log", "level": "DEBUG", "formatter": "verbose", }, "error_file": { "class": "logging.FileHandler", "filename": BASE_DIR / "main/logs/errors.log", "level": "ERROR", "formatter": "verbose", }, "cron_file": { "class": "logging.FileHandler", "filename": BASE_DIR / "main/logs/cron.log", "level": "DEBUG", "formatter": "verbose", }, }, "loggers": { "main.payment_callback": { "level": "DEBUG", "handlers": ["debug_file", "error_file"], "propagate": True, "cron": { "level": "DEBUG", "handlers": ["cron_file"], "propagate": True, }, }, }, "formatters": { "verbose": { "format": "{name} {levelname} {asctime} {module} {message}", "style": "{", }, "simple": { "format": "{levelname} {message}", "style": "{", }, }, } Part of scheduler.py using to add a job: import logging from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.executors.pool import ProcessPoolExecutor, ThreadPoolExecutor from django_apscheduler.jobstores import register_events, register_job from django.conf import settings from .cron import manager_subscribtion_updater # Create scheduler … -
JsonResponse is not outputing the data in the correct structure
I have the following view function which takes the daily stock prices, and convert them to weekly prices. When I return JsonResponse it does not output the values in the correct form. def weeklyPrices(request, ticker): prices = DailyCandles.objects.filter(symbol=ticker.upper()).all().values() weekly = pd.DataFrame(list(prices)) logic = {'open' : 'first', 'high' : 'max', 'low' : 'min', 'close' : 'last', 'volume': 'sum'} weekly['date'] = pd.to_datetime(weekly['date']) weekly.set_index('date', inplace=True) weekly.sort_index() weekly = weekly.resample('W').apply(logic) weekly.index = weekly.index - pd.tseries.frequencies.to_offset('6D') weekly.reset_index(drop=True, inplace=True) return JsonResponse(weekly.to_dict(), safe=False) The output: open 0 "134.19" 1 "137.0" 2 "136.63" high 0 "137.73" 1 "138.4" 2 "137.74" The expected output is where all the values (open, high, low, close) in row 0 are places together, rather then being placed separately. -
can't connect local Django to postgresql container duo to credentials
I'm working on a Django locally and want to connect it to postgres container, I can connect to postgres using pgadmin but not Django here is my code : Compose file : db: image: postgres:latest ports: - 5432:5432 # volumes: # - ~/apps/postgres:/var/lib/postgresql/data environment: POSTGRES_PASSWORD: ${DATABASE_PASSWORD} POSTGRES_USER: ${DATABASE_USER} POSTGRES_DB: ${DATABASE_NAME} .env file: DATABASE_NAME="postgres" DATABASE_USER="postgres" DATABASE_PASSWORD="password" DATABASE_HOST="localhost" DATABASE_PORT="5432" settings.py file: import os from dotenv import load_dotenv load_dotenv() DATABASES = { 'default': { "ENGINE": "django.db.backends.postgresql", "NAME": os.getenv("DATABASE_NAME"), "USER": os.getenv("DATABASE_USER"), "PASSWORD": os.getenv("DATABASE_PASSWORD"), "HOST": os.getenv("DATABASE_HOST"), "PORT": os.getenv("DATABASE_PORT"), } } -
javascript debug statements not showing up on console
So I am working on a Django mock website similar to restoplus, where restaurants can fill in their name, image, details, menus, sides, toppings, pick their brand colours (primary colours and secondary colours) and it will generate a standard landing page for that restaurant using the brand colours and details and menus. Now the problem is I am trying to update the price in real time using js depending on what the user selects. But it's not working. Also the quantity + - buttons are also not working. Now for that I have tried to use debug statements but even when I click on the buttons or select a menuitem option, neither the price gets updated not the quantity, and the console is clear, nothing appears on the console. Why is this? Can anyone help me out here? Thanks! My models.py: from django.db import models from django.contrib.auth.models import User from django.utils.text import slugify class Restaurant(models.Model): name = models.CharField(max_length=100) description = models.TextField() image = models.ImageField(upload_to='restaurant_images/') banner_image = models.ImageField(upload_to='restaurant_images/', null=True) primary_color = models.CharField(max_length=7) # Hex color code secondary_color = models.CharField(max_length=7) # Hex color code favicon = models.FileField(upload_to='restaurant_favicons/', null=True, blank=True) slug = models.SlugField(unique=True, max_length=100, null=True) def save(self, *args, **kwargs): if not self.slug: self.slug … -
Can one inherit a ModelSerializer and Merge Models
I am trying to inherit djoser's UserCreatePasswordRetypeSerializer Djoser Modelserializer's model is User. The child Serializer that I am implementing represents a different model, Customer. So could one do: class CustomerSerializer(UserCreatePasswordRetypeSerializer): class Meta: model=Customer fields = ('customer_name',)+UserCreatePasswordRetypeSerializer.Meta.fields When I do this django is complaining because Customer model does not have the model fields that User has. this is the customer model but this model does exactly represent this model. class Customer(models.Model): customer_name = models.CharField(max_length=255) user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='user') Would passing User as a parent class solve this issue? class Customer(User): customer_name = models.CharField(max_length=255) would this work with inherited ModelSerializers. As Djoser is an app I can not change the UserCreatePasswordRetypeSerializer to fit my needs. I can either inherit is or this is the second approach i was thinking. create something like, class CustomerSerializer(serializers.ModelSerializer): user=UserCreatePasswordRetypeSerializer class Meta: fields = ('customer_name','user') since this is a nested serializer I will have to write create method myself. the issue is how can I call the create of the UserCreatePasswordRetypeSerializer in the create method that I implement because I need to use the create method of UserCreatePasswordRetypeSerializer since it handles sending emails and all the other features in the serializer. So I can not basically just pop … -
Unable to form ORM queryset in Django
I am required to include a field present in a parent table to a grandchild table. I have to form a queryset to achieve the mentioned to return list of records for my mobile application. Refer below my models to have a clear picture. #models.py class Client(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) contact = models.CharField(max_length=10, unique=True) email = models.EmailField(null=True) address = models.TextField() modified_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'clients' ordering = ['id'] verbose_name = 'Client' verbose_name_plural = 'Clients' def __str__(self): return str(self.id) + ". " + self.name class Rent(models.Model): id = models.AutoField(primary_key=True) address = models.TextField() rent_amount = models.IntegerField() deposit_amount = models.IntegerField() rent_date = models.DateField() document = models.TextField(null=True) remarks = models.TextField(null=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) client_id = models.IntegerField() class Meta: db_table = 'rent' verbose_name = 'Rent' verbose_name_plural = 'Rents' def __str__(self): return self.id def get_client_name(self): client = Client.objects.get(pk=self.client_id) return client.name class RentSchedule(models.Model): id = models.AutoField(primary_key=True) rent_due_date = models.DateField() paid_amount = models.IntegerField(default=0) remaining_amount = models.IntegerField() payment_status = models.IntegerField(choices=[(0, 'Unpaid'), (1, 'Paid')], default=0) created_at = models.DateTimeField(auto_now_add=True) rent_id = models.IntegerField() class Meta: db_table = 'rent_schedule' verbose_name = 'Rent Schedule' verbose_name_plural = 'Rent Schedule' def __str__(self): return self.id def get_client_name(self): rent = Rent.objects.get(pk=self.rent_id) client = Client.objects.get(pk=rent.client_id) return client.name … -
Azure Deployment - Server Error (500). Environmental Variables Error?
my azure environmental variables OPENAI_API_KEY = os.getenv('OPENAI_API_KEY') This doesn't seem to be working for azure deployment? What other steps do I need to make to ensure my azure deployed website can access my openai api key? I have created a vector database driven website using django. I am able to run the webapp and perform searches using the api key on local host. I am able to do this while connected to the azure database. However, when I access my website through the public domain, I can't seem to perform searches. I've added the api key to the azure environmental variables already. It says Server Error 500 when I try to perform searches. Is there anything else I need to do? What could be causing server error 500? -
How do I reference the author name column from the Author table in my InsertBook function?
(https://i.sstatic.net/EiBqboZP.png) In the browser, I'm trying to add a new book to my books table but I keep receiving a Value error from django where for example I can't assign "'Virginia Woolf'": "Book.author" must be a "Author" instance. After I enter all the fields to add a new book and then click the Insert button in the browser, I receive the Value error. Below is the structure of my sql table as well as related python scripts for reference: --Create the books table CREATE TABLE books ( book_id SERIAL PRIMARY KEY, title VARCHAR(200) NOT NULL, author_id INTEGER REFERENCES authors(author_id), genre VARCHAR(50), price DECIMAL(10, 2), publisher VARCHAR(100), --Adding the column for the ISBN to populate the table with an extra instance isbn VARCHAR(20) ); --Create the videos table CREATE TABLE videos ( video_id SERIAL PRIMARY KEY, title VARCHAR(200) NOT NULL, genre VARCHAR(50), price DECIMAL(10, 2), publisher VARCHAR(100), release_date DATE ); views.py: from django.shortcuts import render from bookstore.models import Author, Book from django.contrib import messages from bookstore.forms import Authorforms, Bookforms def index(request): return render(request, 'index.html') def author(request): allauthor=Author.objects.all() return render(request, 'author_list.html', {'authors': allauthor}) def Insertauthor(request): if request.method=="POST": if request.POST.get('author_id') and request.POST.get('name') and request.POST.get('birthdate') and request.POST.get('nationality'): saverecord=Author() saverecord.author_id=request.POST.get('author_id') saverecord.name=request.POST.get('name') saverecord.birthdate=request.POST.get('birthdate') saverecord.nationality=request.POST.get('nationality') saverecord.save() messages.success(request,'author … -
Django Logout request returning forbidden 403 CSRF related
from rest_framework import views, status from rest_framework.response import Response from django.contrib.auth import authenticate, login,logout from rest_framework.permissions import AllowAny, IsAuthenticated from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse class LoginView(views.APIView): permission_classes=[AllowAny] def post(self, request): username = request.data.get('username') password = request.data.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return Response({'message': 'Logged in successfully'}, status=status.HTTP_200_OK) return Response({'message': 'Invalid credentials'}, status=status.HTTP_400_BAD_REQUEST) class LogoutView(views.APIView): def post(self, request): logout(request) return Response({'message': 'Logged out successfully'}, status=status.HTTP_200_OK) @csrf_exempt def logoutView(request): print(request.COOKIES) logout(request) return JsonResponse({'message': 'Logged out successfully'}, status=status.HTTP_200_OK) class UserInfoView(views.APIView): permission_classes=[IsAuthenticated] def get(self, request): user = request.user return Response({'username': user.username}, status=status.HTTP_200_OK) When sending request to login or userinfoview it works fine with csrf tokens. however the class LogoutView returns forbidden 403. The logoutView FUNCTION works fine ONLY when csrf_exmpt is applied. when printing request.cookies its returning: {'csrftoken': 'DdQZJC56QBSAcDqXVlrXz4mMeVWitpNV', 'sessionid': 'poul3qidl8xw4k5bp2rwazbxo76eq9sq'} which is what it returns in all the other classes as well. i tried to csrf exmpt the class because thats what i ultimitly want to use instead of the function for the cleaner looking code but couldnt figure out how to exmpt the class. moreover, i dont want to exmpt the csrf to begin with unless its the only solution. -
Why do I get the email but not the ID of the user in Django when using users_data = validated_data.pop(‘users’, [])?
I am working on a Django project and encountering an issue related to extracting user data in a serializer's create method. In the code, users_data contains email addresses of users, but I need to associate users with the task using their IDs instead. However, when I replace User.objects.get(email=user_data) with User.objects.get(id=user_data), I encounter an error. How can I modify my serializer's create method to correctly associate users with their IDs instead of emails? Any insights or suggestions would be greatly appreciated. Thank you! Here is a snippet of my code. Payload: { "id": null, "title": "Task Title", "description": "Task Description", "due_to": "2024-06-28T22:00:00.000Z", "created": null, "updated": null, "priority": "LOW", "category": "TECHNICAL_TASK", "status": "TO_DO", "subtasks": [ { "task_id": null, "description": "Subtask 1", "is_done": false } ], "users": [ 1 ] } class BaseTaskSerializer(serializers.ModelSerializer): """Serializes a task object""" subtasks = SubtaskSerializer(many=True, required=False) class Meta: model = Task fields = ['id', 'title', 'description', 'due_to', 'created', 'updated', 'priority', 'category', 'status', 'subtasks', 'users'] read_only_fields = ['created', 'updated'] def create(self, validated_data): #print('self: ', self) users_data = validated_data.pop('users', []) subtasks_data = validated_data.pop('subtasks', []) task = Task.objects.create(**validated_data) print(users_data) #print('validated_data', validated_data) #print('users_data', users_data) for user_data in users_data: #print(user_data) #print('users_dataaa: ', users_data) #user = User.objects.get(id=user_data) user = User.objects.get(email=user_data) task.users.add(user) for subtask_data in … -
Error in verify_key function from discord_interactions library for Python: Signature was forged or corrupt
I have this code snippet: def interactions_view(request): if request.method == 'POST': try: raw_body = request.body signature = request.headers.get('X-Signature-Ed25519') timestamp = request.headers.get('X-Signature-Timestamp') logger.debug(f"Signature (type: {type(signature)}): {signature}") logger.debug(f"Timestamp (type: {type(timestamp)}): {timestamp}") logger.debug(f"Raw Body (type: {type(raw_body)}): {raw_body}") if not signature or not timestamp: return JsonResponse({'Error': 'Missing signature or timestamp'}, status=400) try: verify_key(raw_body, signature, timestamp, PUBLIC_KEY) except Exception as e: logger.error(f"Signature verification failed: {e}") return JsonResponse({'Error': 'Signature verification failed'}, status=401) . . . And it returns this error on the server logs: 2024-06-29T22:14:41.227687+00:00 app[web.1]: Signature was forged or corrupt With a status code of 200 OK everytime Discord attempts to send it a POST request for verification (I want my server to be an interactions endpoint for a bot) I have tried decoding and encoding the keys to bites and strings and it returns different errors each time like "could not concatenate str object to bytes" and viceversa, among other things like debugging and capturing logging info as shown above, but nothing works. Can someone please tell me if I'm missing something? Or if I did something wrong? -
TypeError: 'staticmethod' object is not callable during Django migrations
When I run python manage.py migrate, I encounter the following error: File "/home/seyedbet/virtualenv/WanderSight/3.9/lib/python3.9/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) TypeError: 'staticmethod' object is not callable Django Version: 4.2, Python Version: 3.9 How can I resolve this? -
Static in django
How can I add a static template tag for this in Django?{% static %} <body style="background-image: url('path') "></body> I try this, but it does not work <body style="background-image: url('{% static "path" %} ') "></body> -
How to configure django templates and webpack
I am using a django project created by django-cookiecutter template.I want to use webpack to bundle my js files (normal js) and css files..previously I used django-compressor to compress css files. I am a newbie in webpack and I would like to ask the following direct questions How do I configure my entry point to include all static files How do I render bundled js files from form Media class I am seeing a substantial increase in js size from my browser network tab.(from 500b to 132kb for example)..Am I doing something wrong or is webpack meant for larger js files only.. Also webpack is not producing any bundle files on my output directory set although I can see bundled js served.Is this the intended behaviour. -
I'm trying to ensure that only the Person that will be at an Event will only be able to view the Events they're attending. How do I do this?
I'm using Django for the purposes of this project and I have a Many-to-Many relation between Person and Event (many people can be at many [existing] Events) and I want to make sure that each Person can only view the Events they're attending, not any other. I'm trying to do this through the admin panel with the use of has_view_permission, but I haven't a clue how to go on about this. I'm trying to use request.user for the purposes of this check. I know that using a through table with models.ForeignKey also works, but since Django already has that implementation invisible to the end user, I wanted to try this idea with a models.ManyToManyField. So far, I have this for my models.py: class Person(models.Model): # fields in the model such as id, name, etc. class Event(models.Model): # fields similar to Person - id, name, date, etc. attendees = models.ManyToManyField(Person) and for the admin.py from django.contrib import admin from .models import Person, Event class EventAdmin(admin.ModelAdmin): def has_view_permission(self, request, obj=None): if Event.objects.filter(attendees = request.user): return True else: return False However, as one might imagine, this disallows anyone but the people in events to actually view the events, thus giving me a ValueError … -
Add Payment Method on my SAAS using an API from local gateway
I have a SAAS program on Django and Python, that manage Clients accounts (one or many). As for now, we handle all payment manually, adding a new client manually to reoccurring monthly payment 3'rd party system For a client with many accounts we have a payment calculator and we charge the amount manually. The major issue we handle is that each month most of our clients have different payment cost, according to number of accounts running. we don't have Stripe here. So my Questions are of 2 types, the way to calculate the payments and the way to execute it. is it safe to add a payment gateway by a simple API, and handle the payment from the backend of the server side ? is it done with a cron job kind of tasker? this it the API: https://documenter.getpostman.com/view/16363118/TzkyNLWB how can I calculate the payment monthly, should I make a smart way to do it, are there more existing solution for the case ? for example an account was running 1.7-5.7 stopped and resumed in 15.7-30.7 is there an recommended algorithm for storing the data? We charge clients world wide. how to manage all payments ? how to enable more … -
Django CreateView get_context_context_data not passing additional object to template
I'm creating a forum app in django. A user can reply to a Thread by pressing a button. This takes them to a new page containing a form with a textbox to post their reply. The PK of the thread being replied to is passed it through the url and saved as the parent_post of the reply within the CreateView. This all works fine (so far...) but I also want to display the title of the thread that is being replied to at the top of the page, but I can't seem to be able to use this passed in pk to display the title of the thread at the top of the html page. URLS: path('reply/<int:pk>/', NewReplyView.as_view(), name='new-reply'), View: class NewReplyView(generic.CreateView): form_class = NewReplyForm initial = {'key': 'value'} template_name = 'forum_app/new_reply.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['x'] = "hahaaha" p = Post.objects.get(pk=self.kwargs.get('pk')) # Why does this not work, seems to work in the def post() method context['thread'] = p return context def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form':form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): submission = form.save(commit=False) submission.author = request.user submission.parent_post = Post.objects.get(pk=self.kwargs.get('pk')) submission.save() #return redirect(to='/') # TODO: redirect … -
Changes not being saved to user profile in Django
I'm having an issue with my Django application where changes are not being saved to a user's profile. I've created a form to edit the user's profile, but when I submit the form, the changes are not being saved to the database. Here's my code: views.py: def customerprofile(request): profile = get_object_or_404(Profile, user_name=request.user) if request.method == "POST": print(request.POST) # Check what data is being sent image = request.FILES.get("image") full_name = request.POST.get("full_name") phone = request.POST.get("phone") address = request.POST.get("address") country = request.POST.get("country") golden_user = request.POST.get("golden_user") == 'on' diamond_user = request.POST.get("diamond_user") == 'on' if image != None: profile.image = image profile.full_name = full_name profile.phone = phone profile.address = address profile.country = country profile.golden_user = golden_user profile.diamond_user = diamond_user try: profile.save() print("Profile saved successfully") # Check if the profile was saved messages.success(request, "Profile Updated Successfully") return redirect("useradmin:customerprofile") except Exception as e: print("Error saving profile:", e) # Check for errors context = { "profile":profile, } return render(request, 'useradmin/customerprofile.html', context) customerprofile.html: {% load static %} {% block content %} <div class="container mt-4"> <div class="card"> <div class="card-header"> <h2 class="card-title">Edit Profile</h2> </div> <div class="card-body"> <form method="post" enctype="multipart/form-data" id="profileForm"> {% csrf_token %} <div class="row"> <div class="col-md-6 text-center"> <img id="imagePreview" src="{% if form.instance.image %}{{ request.user.Profile.image.url }}{% else %}https://static.vecteezy.com/system/resources/thumbnails/009/292/244/small/default-avatar-icon-of-social-media-user-vector.jpg{% endif %}" alt="Preview" … -
Django static files not working on cpanel
my settings.py static settings are STATIC_URL = 'static/' STATIC_ROOT = '/home/mywebsite/public_html/dj/static/' I have run: manage.py collectstatic successfully I restarted the app. But when i hit the URL http://mywebsite/admin there is no CSS. Maybe there's something to do with .htaccess somewhere. I need help -
getting NoReverseMatch error even after correct urls and views
getting the error message of NoReversedMatch even after creating path in urls.py and function in views.py when i type url manually its working properly so the path is not wrong pleaze someone help me NoReverseMatch at /mcq_web/ Reverse for 'quizes' not found. 'quizes' is not a valid view function or pattern name. the html where it is giving error is href = "{% url 'quizes' quiz_type.id %}" here is my urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.show_quiz, name="quiz_show"), path('add/',views.add_user, name ="new user"), path('show_quiz/', views.show_quiz, name="quiz_types"), path('<int:quiz_type_id>/quizes/', views.quizes, name="ShortedQuizTypes"), ] this is my views.py part to that error def quizes(request,quiz_type_id): quiz_type = get_object_or_404( Quiz_types,pk = quiz_type_id) quizes = quiz_data.objects.all() quiz_types = Quiz_types.objects.all() details = {'quiz':quizes,'quiz_type':quiz_type,'quiz_types':quiz_types} return render(request,'shorted_show_quiz.html',{'details':details}) just in case this is my whole views.py from django.shortcuts import render from django.shortcuts import get_object_or_404 from .models import quiz_data,quiz,quiz_history,Quiz_types,options,user from .forms import user_form # Create your views here. # function to show quiz by type def quizes(request,quiz_type_id): quiz_type = get_object_or_404( Quiz_types,pk = quiz_type_id) quizes = quiz_data.objects.all() quiz_types = Quiz_types.objects.all() details = {'quiz':quizes,'quiz_type':quiz_type,'quiz_types':quiz_types} return render(request,'shorted_show_quiz.html',{'details':details}) # function to add new users def add_user(request): if request.method == 'POST': form = user_form(request.POST) if form.is_valid: form.save() … -
How do i record an audio in .wav file format that would meet the standard of Google Speech To Text API in React Native Expo
I have a function that starts and stops recordings, when the recording stops, i can playback the recording and everything works well, but whenever I upload the audio file to Google for transcription, I get an empty response. But when i upload another .wav file (downloaded online, not the recording). I get the transcription of that audio. const startRecording = async () => { try { console.log("Requesting permissions.."); const { status } = await Audio.requestPermissionsAsync(); if (status !== "granted") { alert("Sorry, we need audio recording permissions to make this work!"); return; } console.log("Starting recording.."); await Audio.setAudioModeAsync({ allowsRecordingIOS: true, playsInSilentModeIOS: true, }); const { recording } = await Audio.Recording.createAsync({ android: { extension: ".wav", outputFormat: Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_DEFAULT, audioEncoder: Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_DEFAULT, sampleRate: 16000, numberOfChannels: 1, bitRate: 128000, }, ios: { extension: ".wav", audioQuality: Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_HIGH, sampleRate: 16000, numberOfChannels: 1, bitRate: 128000, linearPCMBitDepth: 16, linearPCMIsBigEndian: false, linearPCMIsFloat: false, }, }); setRecording(recording); } catch (err) { console.error("Failed to start recording", err); } }; const stopRecording = async () => { console.log("Stopping recording.."); if (recording) { await recording.stopAndUnloadAsync(); const uri = recording.getURI(); setRecording(null); uploadAudio(uri); } }; function getOtherUser(data, username) { if (data.receiver.username !== username) { return data.receiver; } if (data.sender.username !== username) { return data.sender; } return null; } … -
ModuleNotFoundError: No module named 'walk.myadmin'
I am trying to import my myadmin models into shoppingapp when I am getting error from walk.myadmin.models import Order I am trying this code and getting error when also I tried this one from myadmin.models import Order but same error I am expecting to import my models from one app to another in the same project. -
Django Template Not Displaying Vendor Contact and Description Fields
I'm working on a Django project where I have a Vendor model. The goal is to display the vendor's profile, including their contact information and description, on a profile page. However, the contact and description fields are not displaying in the template. Here is my Vendor model definition: class Vendor(models.Model): vid=ShortUUIDField(length=10,max_length=100,prefix="ven",alphabet="abcdef") title=models.CharField(max_length=100,default="Nest") image=models.ImageField(upload_to=user_directory_path,default="vendor.jpg") cover_image=models.ImageField(upload_to=user_directory_path,default="vendor.jpg") description=RichTextUploadingField(null=True, blank=True,default="Normal Vendorco") address=models.CharField(max_length=100, default="6,Dum Dum Road") contact=models.CharField(max_length=100, default="+91") chat_resp_time=models.CharField(max_length=100,default="100") shipping_on_time=models.CharField(max_length=100,default="100") authenticate_rating=models.CharField(max_length=100,default="100") days_return=models.CharField(max_length=100,default="100") warranty_period=models.CharField(max_length=100,default="100") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) class Meta: verbose_name_plural="Vendors" def Vendor_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title Here is the view function that retrieves the vendor profile: def shop_page(request): products = Vendor.objects.all() revenue = CartOrder.objects.aggregate(price=Sum("price"))["price"] total_sales = CartOrderItems.objects.filter(order__paid_status=True).aggregate(qty=Sum("qty"))["qty"] context = { "products": products, "revenue": revenue, "total_sales": total_sales, } return render(request, "useradmin/shop_page.html", context) Here is the template shop_page.html: {% load static %} {% block content %} <style> body, html { height: 100%; margin: 0; } .container-fluid { height: 100vh; display: flex; justify-content: center; align-items: center; } .profile-card { border-radius: 12px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); background: #ffffff; overflow: hidden; } .card-header { background-color: #007bff; color: #fff; padding: 20px; border-bottom: none; } .card-title { font-size: 2rem; font-weight: 700; margin: 0; } .card-body { padding: 30px; } .profile-image { max-width: 200px; height: …