Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django race conditions between create() and get()
Since our last release a range of what seems can only DB race conditions have been happening.We use python 3.10, django-rq, Django 4 and Postgres. In one case: x = Model.objects.create() job.delay(x=x) In the job we call Model.objects.get(id=x.id) and it returns nothing. This is happening roughly 1 in 5 times from logs In another case we create the object, add it to a list then act on the list and again it works most of the time but we are getting one off 'matching query does not exist.' errors. I am completely stumped as to what I should do, I cant find many similar issues and can't recreate the issues in my test environment. My best assumption is too many writes to the DB so the transactions aren't being committed by the time the code tries to get the objects again. Any help/advice would be amazing Have gone through the code step by step to ensure the logic is sound Have tried recreating a 'busy' DB but have had no success there Have tried broken data etc but it all gets caught and our logs don't suggest anything like this either -
Enable adding a model field choices to Django admin dashboard and also be able to add or delete the choices
The normal way of interacting with a django model is by using admin.site.register(my_model) in admin.py file. If you want to enforce model's field validation you use the choices field option like this in models.py file. from django.db import models MY_CHOICES=[ ('A','choice 1'), ('B','choice 2'), ('C','choice 3'), .... ] class MY_MODEL(models.Model): ....Some other fields/columns.... options=models.CharField(max_length=2,choices=MY_CHOICES) How would I go about displaying the choices in the admin dashboard and also be able to add new types of choices? Also, is it possible to enforce validation by importing values from the database as field options? I tried having another model that will be a table containing the value and descriptions columns. class MY_CHOICES_MODEL(models.Model): value=models.CharField(max_length=2,..) descriptions=models.TextFeild(blank=False) Trying to pass this around to another models field options is the challenge -
Django model Attributes for Booking system
I'm itermediate in Django ... I work on Booking system with Django. I have two main models : 1.Service & 2.Reservation Service is like this: class AllService(models.Model): title = models.CharField(max_length=100) active = models.BooleanField(default=True) slug_service = models.SlugField(allow_unicode=True, max_length=100, unique=True, default='-') pic = models.ImageField(upload_to='service/') current_queue = models.PositiveSmallIntegerField(default=0) max_queue = models.PositiveSmallIntegerField(default=5) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='services') description = models.TextField() created_at = models.DateTimeField(auto_now_add= True) updated_at = models.DateTimeField(auto_now=True) price = models.FloatField(null=True, blank=True, default=1000) service_off = models.FloatField(null=True, blank=True, validators=[MinValueValidator(0.0), MaxValueValidator(0.2)]) def full_queue(self): if self.current_limit > self.max_limit: self.is_available = False @property def remaining_queue(self): return (self.max_limit - self.current_limit) def adding_in_queue(self): k = self.current_limit k += 1 self.current_limit = k return self.current_limit def reset_queue(self): if datetime.now()==time(hour=0, minute=0, second=0.00): self.current_limit=0 and the Reservation is like this : class Reservation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='reservations') service = models.ForeignKey(AllService, on_delete=models.CASCADE, related_name='reservation') pick_date = models.DateField() description = models.TextField(max_length=1024) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user} {self.service}" class Meta: ordering = ['-created_at'] def clean(self): if self.pick_date < timezone.localdate(): raise ValidationError("day was passed") else: return super().clean() def adding_user_to_queue(self): AllService.adding_in_queue() what I try to do is : when someone choose a service in the Reservation model the "adding_user_to_queue" triger the "adding_in_queue()" method and add up the current_limit field by one, but it doesn't work! I see … -
Pytorch RuntimeError: mat1 & mat2 shapes cannot be multiplied(1x2 and 10000x100)
I am trying to build a spam classifier. However, when sending a POST request, I am getting this error. RuntimeError at /classify/ mat1 and mat2 shapes cannot be multiplied (1x2 and 10000x100) Yes, it's quite straightforward, but even when adjusting the variables, I still get the same result. How can I solve this issue? My model.py file: import nltk from nltk.stem import PorterStemmer import re import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from sklearn.feature_extraction.text import CountVectorizer from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from nltk.corpus import wordnet nltk.download('wordnet') nltk.download('averaged_perceptron_tagger') nltk.download('punkt') try: wordnet.ensure_loaded() except LookupError: nltk.download('wordnet') class LogisticRegression(nn.Module): def __init__(self): super(LogisticRegression, self).__init__() self.linear1 = nn.Linear(10000, 100) self.linear2 = nn.Linear(100, 10) self.linear3 = nn.Linear(10, 2) def forward(self, x): x = torch.flatten(x) x = F.relu(self.linear1(x)) x = F.relu(self.linear2(x)) x = self.linear3(x) return x def classify_spam(message): model = LogisticRegression() model.load_state_dict(torch.load('W:/SpamOrHamProject/SpamOrHamBack/api/AIModel/SpamClassification.pth')) model.eval() cv = CountVectorizer(max_features=10000) processed_message = preprocess_message(message) vectorized_message = cv.fit_transform([processed_message]).toarray() with torch.no_grad(): tensor_message = Variable(torch.from_numpy(vectorized_message)).float() output = model(tensor_message) _, predicted_label = torch.max(output, 0) return 'Spam' if predicted_label.item() == 1 else 'Not Spam' def preprocess_message(message): remove_non_alphabets = lambda x: re.sub(r'[^a-zA-Z]', ' ', x) tokenize = lambda x: word_tokenize(x) ps = PorterStemmer() stem = lambda w: [ps.stem(x) for … -
Getting "404 Error: Page not Found" in Django-ninja API
I've faced this problem with all APIs for any application in the project. To be honest, I've no idea what triggers the problem. Probably, wrong import module or mismatch in urls. I'd like to show you my project structure for better understadning: Project structure Here's my code from news/views.py: from asgiref.sync import sync_to_async # Create your views here. from django.core.exceptions import ObjectDoesNotExist from ninja import Router from ninja.errors import HttpError from .models import News from .schemas import NewsIn router = Router(tags=["News"]) @router.post("/") async def create_news(request, data: NewsIn): news = await sync_to_async(News.objects.create)(**data.dict()) return {"id": news.id} @router.put("/{news_id}/") async def update_news(request, news_id: int, data: NewsIn): try: news = await sync_to_async(News.objects.get(id=news_id)) for key, value in data.dict().items(): setattr(news, key, value) await sync_to_async(news.save()) return {"success": True} except ObjectDoesNotExist: raise HttpError(404, "News not found") @router.delete("/{news_id}/") async def delete_news(request, news_id: int): try: news = await sync_to_async(News.objects.get(id=news_id)) await sync_to_async(news.delete()) return {"success": True} except ObjectDoesNotExist: raise HttpError(404, "News not found") And then code from core/urls.py: `from django.contrib import admin from django.urls import path from ninja import NinjaAPI from news.views import router as news_router from partners.views import router as partners_router from educational_programs_and_categories.views import program_router, category_router api = NinjaAPI() urlpatterns = [ path("admin/", admin.site.urls), path("api/", api.urls), ] api.add_router("news", news_router) api.add_router("partners", partners_router) api.add_router("educational_programs", … -
am having this error trying to run my django project runserver is not working
Traceback (most recent call last): File "C:\Users\user\Desktop\TECH STUDIO FILES\Ecommerce\ec\manage.py", line 22, in main() File "C:\Users\user\Desktop\TECH STUDIO FILES\Ecommerce\ec\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management_init_.py", line 399, in execute_from_command_line utility.execute() File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management_init_.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management_init_.py", line 261, in fetch_command commands = get_commands() ^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management_init_.py", line 107, in get_commands apps = settings.INSTALLED_APPS ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\conf_init_.py", line 54, in getattr self.setup(name) File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\conf_init.py", line 50, in _setup self.configure_logging() File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\conf_init.py", line 72, in configure_logging from django.utils.log import DEFAULT_LOGGING File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\log.py", line 7, in from django.views.debug import ExceptionReporter, get_exception_reporter_filter File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\debug.py", line 12, in from django.template import Template, Context, TemplateDoesNotExist File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\template_init.py", line 53, in from django.template.base import (ALLOWED_VARIABLE_CHARS, BLOCK_TAG_END, File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\template\base.py", line 19, in from django.utils.html import escape File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\html.py", line 14, in from .html_parser import HTMLParser File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\html_parser.py", line 12, in HTMLParseError = _html_parser.HTMLParseError ^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: module 'html.parser' has no attribute 'HTMLParseError'. Did you mean: 'HTMLParser'? every thing but the server fails to run -
Using PyOTP library,giving message wrong OTP
I am using PyOtp library to generate 6 digit otp ,the backend I am using is python django and the frontend is react. My issue is that sometimes(not always) when I generate OTP and click to verify OTP,I enter the correct OTP which is generated but it gives me wrong OTP message and then when I resend OTP,it takes it as correct one.I am not able to figure out that why even after entering the correct OTP ,it is saying me that it is wrong OTP.What could be the issue.I am not using the latest version of PyOTP,could that be an issue or it is something related to time sync. Kindly help me on this. Thnakyou I used the library implemented in API created in python and integrated it in react. -
DRF formdata with file and nested array of objects not taking nested array of objects
Unable to send nested objects when using formdata. Since I have large number of files using base64 is not a solution. current solution was to use JSON.stringify from client side for product_timings and send it as a single field, But I would like to know if normal modal field with file upload is possible with DRF. Here is my APIView class ProductCreateApi(APIView): permission_classes = [permissions.DjangoModelPermissions] queryset = Product.objects.all().order_by("-created_at") parser_class = [MultiPartParser, FormParser, JSONParser, FileUploadParser] class ProductCreateSerializer(serializers.ModelSerializer): class ProductCreateProductTimingSerializer(serializers.ModelSerializer): class Meta: model = ProductTiming fields = ['start_time', 'end_time'] product_timings = ProductCreateProductTimingSerializer(write_only=True, many=True) product_images = serializers.ListField( child=serializers.ImageField(allow_empty_file=False, use_url=False), write_only=True ) class Meta: model = Product fields = '__all__' In post man I tired product_timings[0][start_time]: 09:30:00 product_timings[0][start_time]: 09:30:00 Still it is throwing validation error messages like { "product_timings": [ { "start_time": [ "This field is required." ], "end_time": [ "This field is required." ] } ] } Please note neither base64 image field for product_images nor single JSON field for product_timings is not the solution I'm looking for. -
Something similar to Counter in a Django table
I have a table in sqlite3 with a column that tells me the winners of a game: (computer = 1, human = 2, tie = 0) The model (I'm working on django) is something like this, at least the necessary part: class GameWinners(models.Model): CHOICES = [(0, 'Draw'), (1, 'Computer'), (2, 'Human')] game_winner = models.IntegerField(choices=CHOICES) I would like to obtain a dictionary that counts me the times that each one has won or the ties. something similar to Counter from collections: games = {0: 27, 1: 125, 2: 170} I know that I could do it this way: tie = GameWinners.objects.filter(game_winner=0).count() computer = GameWinners.objects.filter(game_winner=1).count() human = GameWinners.objects.filter(game_winner=2).count() games = {0: tie, 1: computer, 2: human} But I guess there must be a better way to do it. -
JavaScript: Problem accessing 'change' event for a file input
Aim I have two inputs: (1) a 'file-input', and (2) a 'text-input' I want to listen for a 'change' in 'file-input' (i.e. successful choice of file), and upon such a change set the 'text-input' value to the name of the file. Problem The 'change' event is not triggering when I use addEventListener When I use the input's 'onchange' attribute, it does trigger, but I still don't get access to files Context: This is for a Django project, with Bootstrap 5 on the frontend (NO JQuery). I am using Django Crispy Forms where possible, though I have removed them from this file (to see whether that was what was causing the problem - alas, it wasn't). Attempted Solutions I know this should be easy. I have seen lots of similar posts about this, and I set up a 'dummy' HTML script to ensure I'm not going mad. This is posted below and it works perfectly. <!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> <input type="file" name="file" id="file-input" accept=".mp3,.mp4,.mpeg,.mpga,.m4a,.wav,.webm"> <input type="text" name="text" id="text-input"> <script> const fileInput = document.getElementById("file-input"); const textInput = document.getElementById("text-input"); console.log(fileInput); console.log(textInput); fileInput.addEventListener('change', () => { console.log('change registered'); if (fileInput.files.length > 0) { console.log(fileInput.files); console.log(fileInput.files[0].name); textInput.value = fileInput.files[0].name; } }); … -
How to show the ForeignKey' content in Django template
I am beginner in django, there is a question i am fronting is that how to show the content of ForeignKey item, for example i have a table called company, there is a field "parentcompany" for storage the ForeignKey(UID) with the parentcompany, all the company is created on the this company table. I already been success to create this relationship, but I can not show the parentcompany's name in the template. I already tried using this {{company.parentcompany_id.companyName}}, but nothing is shown. -
How can I delete ManyToManyField on Django Model (used in Wagtail Page inheritor)?
I have such field: from wagtail.models import Page class MyModel(Page): ... many_to_many_field = models.ManyToManyField(ToClass, blank=False, related_name='+', verbose_name=_("My models")) ... I tried simply to comment it like this: from wagtail.models import Page class MyModel(Page): ... # many_to_many_field = models.ManyToManyField(ToClass, blank=False, related_name='+', verbose_name=_("My models")) But I've got 'django.core.exceptions.FieldError' while was executing 'python manage.py makemigrations': Traceback (most recent call last): File "D:\projects\myapp\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "D:\Python311\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\Python311\Lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Python311\Lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "D:\Python311\Lib\site-packages\django\core\management\base.py", line 443, in execute self.check() File "D:\Python311\Lib\site-packages\django\core\management\base.py", line 475, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\wagtail\admin\checks.py", line 70, in get_form_class_check if not issubclass(edit_handler.get_form_class(), WagtailAdminPageForm): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\wagtail\admin\panels\base.py", line 162, in get_form_class return get_form_for_model( ^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\wagtail\admin\panels\base.py", line 48, in get_form_for_model return metaclass(class_name, tuple(bases), form_class_attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\wagtail\admin\forms\models.py", line 124, in __new__ new_class = super(WagtailAdminModelFormMetaclass, cls).__new__( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ new_class = super().__new__(mcs, name, bases, attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\modelcluster\forms.py", line 259, in __new__ new_class = super().__new__(cls, name, bases, attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Python311\Lib\site-packages\django\forms\models.py", line 327, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (many_to_many_field) specified for MyModel What is wrong? How can I delete it? -
post name, email and role in django backend, react frontend
i want to the admin to post name, email and role of a user using frontend, and its stored in backend of django, please note that i dont want the admin to store the password, the user will later on add it djangocode: class UserSerializer(serializers.ModelSerializer): class Meta: model = UserAccount fields = ['email', 'name', 'username', 'password', 'role'] def create(self, validated_data): password = validated_data('password') username = validated_data('username') user = UserAccount( email=validated_data['email'], role=validated_data['role'], name=validated_data['name'] ) if username is not None: username=validated_data['username'], if password is not None: user.set_password(validated_data['password']) user.save() return user react code: const handleSubmit = (event) => { event.preventDefault(); const data = { name : name, email : email, role: role }; console.log("data is "+data); axios.post('http://127.0.0.1:8000/api/register/', data) .then(response => console.log("got it"+response.data)) .catch(error => console.log(error)); console.log('name:', name); console.log('email:', email); console.log('role:', role); -
How to store an object id in django admin
I got a top model like Project, and many sub models like Store, Task, Bug, TestCase. I want to seprate project as isolated workspace in admin. when I select a project, store the current project id, and when I create sub model objects or view change list, all object is belong to this project. -
Unable to read django table in admin or through API
I've added few tables to django app, and two of them are acting weird. I'm unable to read these 2 tables through django admin or postman API however, I'm able to read these table through postgres(pg admin). I'm getting index error in django-admin and postman on these two tables(or django models). These tables has data in them as verified using pgAdmin. The tables are stored in postgres, and the DB is connected to django aplication. Any idea why this could be happening and possible solutions? -
Bad Request (400) on adding new domain from hostinger on vercel hosting
I have purchased domain from hostinger after adding the domain in the domain and changing the nameserver of hostinger to ns1.vercel-dns.com ns2.vercel-dns.com i validated the configuration but when i look the site it gives Bad Request (400) error . pushpblogs.fun Valid Configuration Redirects to www.pushpblogs.fun www.pushpblogs.fun Production Valid Configuration Assigned to main i waited for the dns to apply for 24 hours but still no change made. -
Mayan EDMS ,Calling the API remotely using AJAX getting CORS error
I am creating a new webapp that is going to be making calls to the Mayan EDMS API with javascript/ajax Currently i am getting a CORS error. My mayan installation is running inside a docker container. I did find in the settings for Django in the admin->settings-> Django there is a ALLOWED_HOSTS but there is a green checkmark which indicates it is overwritten by a env var. Any Idea what env var that would be. there is nothing obvious in the .env for the docker file It appears that django-cors-headers is there as well. Just not sure how to config How are other people dealing with this? Thanks randy -
Python route usage
How can I use $ in the python url . This is my usage from django.urls import include, path from vote import views urlpatterns = [ path(r'^$', views.index, name='index') ] but it ending with Using the URLconf defined in election.urls, Django tried these URL patterns, in this order: [name='index'] vote/ ^$ [name='index'] I need to get understand what is the best usage -
(Python/Django) Can I use Python's Django framework w/o using templates?
I am learning how to use the Django framework, and as I am learning about Django's template system, I was wondering, if it would be possible for me to use Django without using templates to render the necessary html documents from views? As an alternative to Django's template system, I would prefer to use JavaScript in order to make the necessary data queries from the sites database(s). This might seem counter productive, but in my opinion, I would prefer to learn the traditional front-end web stack(HTML, CSS, JS), and solidify my skills this way before going down the journey of template systems. At this point, I would be using Django only as a back-end until I was ready to incorporate templates into my dev process. Thank you in advance! This my first post on SO, take it easy! I have tried to use Django's template system, but It's a little comprehensive to learn on top of HTML and CSS at the same time. -
Gives 404 error even when audio file exists: GET /data/audio/5dc18de4d34d12a20b21fbc2506b423f35cfd7fc0fc931874bdfe13b1578aeee.m4a HTTP/1.1" 404 179
enter image description here The file is present and still gives a 404 and works on other machine perfectly fine. It is an audio file which is saved inside data/audio and that is where the local is trying to search which is correct location but still gives 404 -
DJango how to manage redshift connection in a server
I am using redshift in my django application. I know we can use psycopg2 for redshift, but i am planning to use the aws library pip install redshift_connector Currently for every query in my view i run. So here I see its taking time to connect to redshift everytime and thats consuming time than then query time. conn = redshift_connector.connect( host='host.docker.internal', database='dev', port=5439, user='user', password='kkshdjhjhsdj' ) cursor = conn.cursor() cursor.execute("SELECT CURRENT_TIMESTAMP") data = cursor.fetchall() I am not sure how django keeps connection live for database and effeciently handle. If we have to use some thirdparty databases then how to handle connection. Can someone guide me what else needs to be taken care. -
Django template: how to show decimal value as currency format with dollar sign, thousand separator with zero or two decimal points
The field in models.py is: order_amount = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) if the order_amount value is 12345.67, how to display it in Django template for the below two formats: without decimal point: $12,345 without two decimal points: $12,345 -
Am getting empty strings in my django database when trying to save JSON data from ajax request
Am new in coding skills so am creating a website now am stuck , in my website users answer a question by clicking one button choice out of many button choices , i want when a button is clicked data to be sent to the django database but unfortunately when i click the button only empty strings is sent to the database views.py import json from django.http import JsonResponse, HttpResponseRedirect from django.shortcuts import render, redirect from django.urls import reverse from .models import JasonData from .form import QuestionForm # Create your views here. def index(request): """The homepage for Stay_healthy""" return render(request, 'Stay_healthy/index.html') def redirect_to_index(request): """The homepage for Stay_healthy""" return HttpResponseRedirect(reverse('index', args=None)) def json_data_store(request): if request.method == 'POST': # this runs incase the request is an ajax if request.headers.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest': data = json.loads(request.body) form = QuestionForm(data) if form.is_valid(): form.save() return JsonResponse({'status': 'success'}) else: return JsonResponse({'status': 'error'}) else: # this runs incase the request is not ajax form = QuestionForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = QuestionForm() return render(request, 'Stay_healthy/question_detail.html', {'form': form}) def check_data(request): stored_data = JasonData.objects.all() return render(request, 'Stay_healthy/check_data.html', {'stored_data': stored_data}) models.py from django.db import models # Create your models here. class JasonData(models.Model): patient_data = models.JSONField(blank=True, null=True, default=dict) form.py … -
How to send multiple objects on serializers.Serializer (got non_field_errors)
I'm trying to send multiple data through a create viewset method to a serializer. However when doing that I get an error as follows: enter image description here Im using many attribute into the serializer, but I sill get the same error. I'm posting data like this: [ { "weekday":"day", "start_time":"time", "end_time":"time" }, { "weekday":"day", "start_time":"time", "end_time":"time" } ] This is the viewset and serializer code: viewset.py class SpecialistAvailabilityView(viewsets.ModelViewSet): model = SpecialistAvailability permission_classes = [IsAuthenticated, IsSpecialist] def get_serializer_class(self): saving_actions = ["create", "update", "partial_update"] if self.action in saving_actions: return WeekDayTimeSerializer return SpecialistAvailabilitySerializer def get_queryset(self): queryset = SpecialistAvailability.objects.filter( specialist__user=self.request.user ).order_by('-start_time__week_day') return queryset def translate_availability(self, data): pass def create(self, request, *args, **kwargs): serializer = WeekDayTimeSerializer(data=request.data, many=isinstance(request.data, list)) print(serializer.initial_data) print(serializer.is_valid()) if serializer.is_valid(): self.translate_availability(serializer.validated_data) return super().create(request, *args, **kwargs) serializer.py import pytz from datetime import datetime from rest_framework import serializers from apps.specialist.models.specialist_availability import SpecialistAvailability from apps.specialist.utils import WEEKDAYS class WeekDayTimeSerializer(serializers.Serializer): weekday = serializers.ChoiceField(choices=WEEKDAYS, required=True) start_time = serializers.TimeField() end_time = serializers.TimeField() # TODO ADD TIME AND WEEKDAY CHECKING # START TIME MUST BE LESS THAN END TIME # JUST ONE DAY MUST BE SENDED IF MANY def validate(self, attrs): self.validate_start_time(attrs['start_time']) self.validate_start_time(attrs['end_time']) self.validate_end_time return super().validate(attrs) def validate_start_time(self, start_time): try: datetime.strptime(start_time, "%H:%M") except: raise serializers.ValidationError("Wrong time format") return start_time … -
Django payment intigration
i want to add a donation page in my DJango project but i have not seen any proper intigration of payment gateway in any articles and videos so plzz help me and give the proper code and explanation. in stripe apy key is not supported in india in razorpay when click on payment error occur amount exceed