Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Simple Django blog using JSON files?
I am seeking AdSense approval and my site, even though it contains content, is apparently insufficient for AdSense approval. So I want to add a lightweight blog to the site. However, I don't want to create additional data models, etc. and would prefer to just edit a JSON file that is parsed for blog content. And following that, just include a "blog.html" template on various pages which will load the content. Is there any JSON-fed blog module for Django? I feel like this wouldn't be too hard to create, but I don't want to reinvent the wheel. Thanks! -
Handling request in django view: accessing the body
I' trying a modify my database on a condition based on a body object from the request. here is my fetch function: document.addEventListener('change', function(e) { event.preventDefault(); const magazinOption = e.target.value; const mag_url = "{% url 'my-subscriptions' %}"; if (magazinOption === 'digital') { fetch(mag_url, { method: "POST", headers: { "X-CSRFToken": Cookies.get('csrftoken'), "Accept": "application/json", "Content-Type": "application/json" }, body: JSON.stringify({ 'magazine': 'digital' }) }) .then(response => { return response.json(); }) .then(data => { console.log('Choix de magazin:', paper_magazine ); }); } }); Then in my view file i have this. def post(self, request): ... request_body = json.loads(request.body.decode('utf-8')) print(request_body) print('body:', request_body['magazine']) print('body to string:', str(request_body['magazine'])) if str(request_body['magazine']) == 'digital': user.paper_magazine = False user.save() And in my terminal this is what i see: 04/Jul/2021 08:08:18] "GET /static/src/images/earth.svg HTTP/1.1" 200 3503 {'magazine': 'digital'} body: digital body to string: digital Internal Server Error: /client-profile-new/subscriptions/ Traceback (most recent call last): File "/Users/marcusbey/.pyenv/versions/jaenv36/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/marcusbey/.pyenv/versions/jaenv36/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view apps.front.views.profile.NewProfileSubscriptionsView didn't return an HttpResponse object. It returned None instead. [04/Jul/2021 08:08:25] "POST /client-profile-new/subscriptions/ HTTP/1.1" 500 73892 What am i missing ? Why can't i access the body object's value? -
how to notify the user about the incoming message to the receiver in flutter chat app?
So, I need a chat feature implementation to my flutter app. Since on research many tutorials uses Firebase Firestore as their database. I use my own Django server to have my logic. So, If I'm going to use Django I can implement websockets to connect a user to database and update the changes in real time. The chat is going to be like a one to one connection. So, I have some question First of all, in all those firebase application uses a single documentID to make changes to firebase which will be like room is it a good practice to do so for professional? How can I notify the receiver about the sender message when receiver app is not open state(cleared the app from cache)? What will be the best database design for this application(I have mentioned mine below)? If all the above satisfies, How can I reinitiate the chat sequence of that one to one chat? -
Nuxt Auth Token & refresh token not set
I took the following example from the Nuxt Auth documentation: auth: { strategies: { local: { scheme: 'refresh', token: { property: 'access', maxAge: 1800, global: true, type: 'Bearer' }, refreshToken: { property: 'refresh', data: 'refresh', maxAge: 60 * 60 * 24 * 30 }, endpoints: { login: {url: '/token', method: 'post'}, refresh: { url: '/token/refresh', method: 'post'}, user: false } } } } And I got the following response from my API (Django): { "refresh": "y", "access": "x" } At last, I have the exact same login 'page' as show in the documentation of Nuxt Auth but when I run this neither the refresh or access token is set into the local storage. Upon changing login: {url: '/token', method: 'post'} to login: {url: '/token', method: 'post', propertyName: 'access'} the access token is set properly but doing similar for the refresh token doesn't work. How can I get Nuxt Auth to set both my refresh and access token properly? -
Django Multiple filter with range look-up
my model: class Attendance(models.Model): date = models.DateField() subject = models.ForeignKey(Subject, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) attendance = models.BooleanField() the query i am trying att = Attendance.objects.filter(date__range=(st_date,ls_date)).filter(student__range=(1,10)) it is giving me an error : File "C:\Users\user1\Desktop\backend\environment\lib\site-packages\django\db\models\sql\query.py", line 1184, in build_lookup raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: range -
how to filter django model object if contains in python django
i am trying to filter out a model which contain sender,receiver,user, the problem is when i try to use return Private_messages.objects.filter(sender__contains=sender,receiver__contains=receiver,user=user) it is strict in checking and will only return if condition are met... model example id:1 sender:"dan" reciever:"harry" id:2 sender:"harry" reciever:"dan" id:3 sender:"dan" reciever:"harry" in this sometimes sender is dan sometimes not. with Private_messages.objects.filter(sender="dan",receiver="dan") i want to get all object with the who has sender dan and receiver dan not both dan how can i get something like this in python django? -
Auto-populating a Django model field using JavaScript fails consistently
I have a model named Package. It has fields named, diagnosis, treatment, patient_type, max_fractions and total_package. The fields diagnosis, treatment and patient_type have foreign keys defined in separate individual classes, making diagnosis, treatment and patient_type choice fields. Now what I want is to auto-populate the max_fractions and total_package fields whenever treatment and patient_type's values are selected. I was suggested to use JavaScript to accomplish that. I tried and wrote the codes but to no avail. I'm trying it on max_fractions field first, when I succeed in doing that, I will do it for all the needed fields. Can anyone help me on this, it will be much appreciated. Here are my models: class Diagnosis(models.Model): diagnosis=models.CharField(max_length=30, blank=True) def __str__(self): return self.diagnosis class Treatment(models.Model): treatment=models.CharField(max_length=15, blank=True) def __str__(self): return self.treatment class PatientType(models.Model): patient_type=models.CharField(max_length=15, blank=True) def __str__(self): return self.patient_type class Package(models.Model): rt_number=ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=ForeignKey(Treatment, on_delete=CASCADE) patient_type=ForeignKey(PatientType, on_delete=CASCADE) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) forms.py: class DiagnosisForm(ModelForm): class Meta: model=Diagnosis fields='__all__' class TreatmentForm(ModelForm): class Meta: model=Treatment fields='__all__' class PatientTypeForm(ModelForm): class Meta: model=PatientType fields='__all__' class PackageForm(ModelForm): class Meta: model=Package fields='__all__' widgets={ "max_fractions" : forms.NumberInput(attrs={"onfocus":"mf();"}), } views.py: def package_view(request): if request.method=='POST': fm_package=PackageForm(request.POST, prefix='package_form') fm_diagnosis=DiagnosisForm(request.POST, prefix='diagnosis_form') fm_treatment=TreatmentForm(request.POST, prefix='treatment_form') fm_patient_type=PatientTypeForm(request.POST, prefix='patien_type_form') if fm_package.is_valid() and fm_diagnosis.is_valid() and fm_treatment.is_valid() and fm_patient_type.is_valid(): … -
Automatically change price when I change inventory in Django?
I am creating an invoice form. I would like to have a function where if I change the inventory (dropdown search), the corresponding price will also change. You can see an illustration of what I want here: https://www.dropbox.com/s/4kpyfve3gzxmcls/dj006_ultimate_goal_for_adding_variable_attr.jpg?dl=0 What I know so far is I can I can query the inventory dropdown search through: inventory = Inventory.objects.get(pk=request.POST['inventory_dropdown_id']) price = inventory.price But how do I propogate such "get" function throughout all the forms (since I'm using query set) how do I set the price (in the view.py) back to the html file when the html file is already rendered? Is there away around this? P.S. Probably been asked before here but I couldn't find any reference. (Hard to find what proper keyword to search) So if you want to post a link. I'd be happy to take a look at it. -
Celery Beat how to calculate difference between datetime.now() and the next scheduled Periodic Task django
I have a celery beat cron schedule set for day 3 of every week. In django shell I can access this schedule: >>> schedule = PeriodicTask.objects.get(name="Bulk Newsletter Send") which results in: >>> <PeriodicTask: Bulk Newsletter Send: * * * * 3 (m/h/dM/MY/d) UTC> My question is, how can I calculate the time difference in days between datetime.now() and the next PeriodicTask? -
When I can call myself a Django developer and be able to apply for a job?
I learnt a Python and Django, by using these I build a web-app but it is not live/online. I have neither certificate and nor IT degree. Now, I wanna actually want to know which things make me a Django/Python web-developer or I am not a web-developer? -
Cannot resolve keyword 'username' into field. Choices are: address, age, city, country, gender, name, phone, pt_id, user, user_id
Please help me, I am stuck at this error. I am new to django, I don't know how to solve this errorstrong text patients/views.py @method_decorator([login_required, patient_required], name='dispatch') class EditPatient(UpdateView): model = Patient_Profile fields = ['pt_id', 'name', 'gender', 'age', 'phone', 'address', 'city', 'country'] template_name = 'patient/patient_edit.html' slug_field = 'username' slug_url_kwarg = 'slug' success_url = reverse_lazy('patients:patient_page') def get_context_data(self, *args, **kwargs): context = super(EditPatient, self).get_context_data(*args, **kwargs) return context patients/models.py class Patient_Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) pt_id = models.CharField(max_length=50) name = models.CharField(max_length=100) gender = models.CharField(max_length=15) age = models.CharField(max_length=10) phone = models.CharField(max_length=20) address = models.TextField() city = models.CharField(max_length=100) country = models.CharField(max_length=100) def __str__(self): return self.user.username patients/urls.py app_name = 'patients' urlpatterns = [ path('', views.patient_page, name='patient_home'), path('profile/<slug>', views.EditPatient.as_view(), name='profile'), ] template <h1>I am {{user.username}} </h1> <a href="{% url 'patients:profile' slug=user.slug %}">Edit Patient</a> {%endblock%} -
Try Uploading multiple image but form was not submitting
I was trying to add multiple images in django. I had shared my code below. every time i click on submit(Add Farm) it will remain on same page. it is not calling post method. models.py class Farm(models.Model): user=models.ForeignKey(FarmUser,related_name="farm_owner",on_delete=models.CASCADE) farmname=models.CharField(max_length=50) SizeOfFarm=models.IntegerField() address=models.TextField(default='') area=models.CharField(default='',max_length=20) city=models.CharField(default='',max_length=20) pincode=models.IntegerField() class FarmImage(models.Model): farm = models.ForeignKey(Farm, related_name="farm_image", on_delete=models.CASCADE) images = models.FileField(upload_to='farm/') forms.py class FarmFormFileds(forms.ModelForm): class Meta(): model = Farm fields=('user','farmname','SizeOfFarm','address','area','city','pincode') class FarmForm(FarmFormFileds): images=forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta(FarmFormFileds.Meta): fields = FarmFormFileds.Meta.fields + ('images',) views.py class NewFarm(CreateView): form_class=FarmForm template_name='farmuser/addfarm_form.html' success_url=reverse_lazy('dashboard') def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('images') if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) I just want to upload multiple files. In above code some functionalities are missing but the problem is that the method is not calling -
Wishlist items are showing correctly in Django
wishlist column from All_Collections have PK of Wishlist.But this below code pointing to the user id instead Wishlist PK(id). products = All_Collections.objects.filter(wishlist= request.user.id) in this line facing issue Can anyone please help me to solve this. View.py @login_required def wish_list_add(request,id): item = get_object_or_404(All_Collections,id=id) wished_item,created = Wishlist.objects.get_or_create(product_id=item, user = request.user.id) messages.info(request,'The item was added to your wishlist') return redirect('all_collections') @login_required def wish_list(request): data = All_Collections.objects.filter() print("All Collections(product table) : ", data.values('wishlist')) data = Wishlist.objects.filter() print("Wishlist PK : " ,data.values('id')) data1=Wishlist.objects.filter(user=request.user.id).values_list('id', flat=True) print("Wishlist pk values :" ,data1) user_id = Wishlist.objects.filter(user = request.user.id) print('wishlist user :' ,user_id) products = All_Collections.objects.filter(wishlist= request.user.id) print('Wishlist Items : ',products) return render(request=request, template_name="D_Crown/wishlist.html",context={'wishlist': products}) @login_required def wish_list_remove(request,id): item = get_object_or_404(Wishlist,id=id) Wishlist.delete(item.id) return redirect('wish_list') Model.py class All_Collections(models.Model): name = models.CharField(max_length=200) image = models.ImageField(upload_to='Images') collection_desc = models.TextField() material_details = models.TextField() price = models.IntegerField() color = models.CharField(max_length=200) shape = models.CharField(max_length=200) review = models.IntegerField() no_purchases = models.IntegerField() offer = models.BooleanField(default=False) offer_percentage = models.IntegerField() new_price = models.IntegerField() exchange = models.BooleanField(default=False) quantity = models.IntegerField() items_left = models.IntegerField() delivery_info = models.CharField(max_length=300) def _str_(self): return self.d_crown_all_collection class Wishlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(All_Collections, on_delete=models.CASCADE) added_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username output: Quit the server with CTRL-BREAK. All Collections(product table) : <QuerySet [{'wishlist': 4}, … -
Reverse for 'product_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['products/detail/(?P<slug>[-a-zA-Z0-9_]+)/$']
What I am trying to do I was trying to make urls as human-readable urls with slug, instead of using the pk that Django automatically gives me. What I tried at first time Here are my codes that are relevant to my works. models.py from django.urls import reverse class Product(TimeStampModel): slug = models.SlugField(max_length=80, null=False, default='', editable=False) ... def save(self, *args, **kwargs): from django.utils.text import slugify if not self.slug: self.slug = slugify(self.product_name, allow_unicode)=True super().save(*args, **kwargs) def get_absolute_url(self): kwargs = { 'slug': self.slug, } return reverse('products:product_detail', kwargs=kwargs) views.py ProductListView is the view that shows products from all categories ProductDetailView is the view of detail page of product. from django.views.generic import DetailView, ListView class ProductListView(ListView): model = models.Product template_name = 'products/product_all.html' context_object_name = 'products' paginate_by = 12 paginate_orphans = 5 ordering = 'created' class ProductDetailView(DetailView): model = models.Product template_name = 'products/product_detail.html' context_object_name = 'products' urls.py urlpatterns = [ path('all/', views.ProductListView.as_view(), name='product_list_all'), paht('detail/<slug:slug>/', views.ProductDetailView.as_view(), name='product_detail'), ] templates Directory for template file for ProductListView is templates/products/product_all.html Directory for template file for ProductDetailView is templates/products/product_detail.html <section id="all" class="product-list"> <ul class="item-grid"> {% for product in products %} <li class="item"> <a href="{{ product.get_absolute_url }}"> <img src="{{ product.product_thumbnail.url }}" alt="product-image" class="product-image"> <div class="product-info"> <h1 class="product-name">{{ product.product_name }}</h1> <h2 class="product-price">{{ … -
Django + postgres CI/CD testing guide
Working example for how to implement Gitlab CI/CD testing for Django using postgres? -
Django: create endpoint for a file
I have a mesh.obj file and I would like to create an endpoint for it. For example, the endpoint could be of the form 'path/to/mesh'. How would I do this? -
DRF: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'
I am creating ecommerce api using Django Rest Framework. This is my order model. I have 2 many to many fields for address and order items. payment_options= ( ('COD', 'Cash on Delivery'), ('BANK', 'Bank Transfer'), ('WALLET', 'Wallet Transfer'), ) delivery_options= ( ('Placed', 'Placed'), ('Processing', 'Processing'), ('Delivered', 'Delivered'), ('Cancelled', 'Cancelled'), ) order_number = models.AutoField(primary_key=True) items = models.ManyToManyField(OrderItem) order_address = models.ManyToManyField(Address) delivery_date = models.DateTimeField(auto_now_add=False) price = models.FloatField() payment_method = models.CharField(max_length=6, choices=payment_options) delivery_status = models.CharField(max_length=16, choices=delivery_options, default='Placed') class Meta: ordering = ['order_number'] def __str__(self): ord = str(self.order_number) ord_text = "Order #"+ord return ord_text Here is my Serializer: class OrderItemSerializer(serializers.ModelSerializer): prod = ProductSerializer() class Meta: model = OrderItem fields = ["quantity", "prod"] class AdressSerializer(serializers.ModelSerializer): class Meta: model = Address fields =[ "address_1", "address_2", "city", "state", "postcode", "country" ] class CompleteOrderSerializer(serializers.ModelSerializer): items = OrderItemSerializer(many=True) order_address = AdressSerializer(many=True) class Meta: model = Order fields =[ "order_number", "items", "delivery_date", "price", "payment_method", "delivery_status", "order_address", ] def create(self, validated_data): ord_id = [] address_data = validated_data.pop('order_address') print(address_data) for j in range(len(address_data)): address = Address.objects.create( address_1=address_data[j]['address_1'], address_2=address_data[j]['address_2'], city=address_data[j]['city'], state = address_data[j]['state'], postcode=address_data[j]['postcode'], country=address_data[j]['country'] ) ord_id.append(address.id) item = validated_data.pop('items') ids = [] for i in range(len(item)): prod = item[i]['prod']['name'] count = item[i]['quantity'] product = OrderItem.objects.create( prod=Product.objects.get(name=prod), quantity=count ) ids.append(product.id) Order.order_address = Address.objects.filter(id__in=(ord_id)) … -
Django setup url parameter for certain requests only
So I'm trying to setup my Django view such that when they POST to an endpoint they don't need an url parameters, but when they call GET they require it path('posts/', views.PostView.as_view(), name="post"), path('posts/<int:count>/', views.PostView.as_view(), name="post"), The issue with this is that it makes swagger messy and swagger with assume that url/posts/ you can POST and GET from, and url/posts// you can as well, but I only want to be able to POST to the first and GET from the 2nd. Is there a way to do this without creating separate view classes for them? Or is it better practice in this case to create separate view classes? -
Is it easier to create a web or mobile app using Python and Django? What are the other things I need to know?
I am Python intermediate programmer and have no experience in web or mobile development. I only do wish to create a website using python only. I would really be grateful if you could explain all the necessary stuff I should know in order to this. What I am intending to do is to create a QUiz application. -
The modal message does not show the correct data when I added bootstrap into my django project
**homepage.html** {% for country in countries %} <tr> <th scope="row">{{ country.id }}</th> <td>{{ country.name }}</td> <td align="center"><a class="btn btn-warning" href="{% url 'edit_country' country.id %}">Edit</a></td> <td align="center"><a class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#exampleModal">Delete</a></td> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Delete post</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> Are you sure you want to delete {{ country.name }}? </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-danger" href="{% url 'delete_country' country.id %}">Delete</button> </div> </div> </div> </div> </tr> {% endfor %} views.py def homepage(request): countries = Countries.objects.all() context = {'countries':countries} return render(request,'homepage.html',context) models.py class Countries(models.Model): name = models.CharField(max_length=75) landmark = models.CharField(max_length=100,null=True) food = models.CharField(max_length=100,null=True) entertainment = models.CharField(max_length=100,null=True) image = models.ImageField(upload_to='travel', default='default.png',null=True) def __str__(self): return self.name Here I have a problem that when I use the Django component Modal although I used for loop to pass the parameter country the modal message could appear but it does not show the correct {{country.name}} data. I tried clicking the delete button on the second row but the message still only shows the data of the first object instead of the second one. May I ask is there a problem that I put the modal … -
How to remove Set-Cookie header from Django response
I've created a middleware but there doesn't seem to be a Set-Cookie header in the response? But when testing the responses, its definitely there MIDDLEWARE = ( "apps.base.middleware.RemoveHeadersMiddleware", ### ) class RemoveHeadersMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): response = self.get_response(request) # No Set-Cookie header here????? # del response._headers['Set-Cookie'] return response -
My HTML and CSS causes this padding issue to happen in Django
I am not sure why when resizing my page this happens around the iPad media query level, and then gets fixed for smaller mobile devices like the iPhone once the toggle hamburger icon appears. It is broken until it goes below 768 x 1080 and above 908 x 1080. A lot of this was copy, and paste as I was trying to understand it, but this is stumping me. If anyone can help explain this issue in detail I would be very appreciative. Navbar HTML: <nav class="sticky-top navbar navbar-custom navbar-expand-md"> <div class="container-fluid"> <a class="navbar-brand abs" href="{% url 'home' %}" >"Pure White Logo Here"</a > <button class="custom-toggler navbar-toggler ms-auto" type="button" data-bs-toggle="collapse" data-bs-target="#collapseNavbar" > <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse" id="collapseNavbar"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="Home" href="{% url 'home' %}" >Home</a > </li> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="About" href="#" >About</a > </li> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="Leadership" href="#" >Leadership</a > </li> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="Programs" href="#" >Programs</a > </li> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="News & Events" href="#" >News & Events</a > </li> <li class="nav-item"> <a class="nav-link" data-toggle="tooltop" data-placement="auto" title="Chapter Membership" href="#" >Chapter Membership</a > </li> <li class="nav-item"> <a class="nav-link" … -
Should a background process be part of Django project?
I'm trying to build a web app which provide an interface to do some queries upon data extracted from another public API server. To complete the queries in real time, I would have to prefetch the data from the public API server. So I think it is reasonable to separate the app deal with query input(there is still some logic here, so only javascript wouldn't be enough) from the app which runs in background and builds the database which could possibly answer the query in real time. Then what comes to my mind is does this background app really have to be a part of Django project? It runs almost without interacting with any Django component. Except for the database which is also accessible by a Django app and some signals maybe(when to start/stop collecting data, but this could probably also decided internally). What would a be good design choice for my situation? -
How to Dockerize a React-Django where the front-end is served from Django?
I'm new to Docker. I have been surfing through the internet to find any resources for how to Dockerize a React-Django project, in which the React App is served from Django, both running on port 8000, but couldn't find any proper resource for this. Can someone help me with the procedure for Dockerizing a React-Django project having a monolithic architecture? -
Django REST error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'BoundField'
I have a funtion which outputs friday by taking in week number as a parameter def fridayOfWeek(p_week): p_year=2021 monday = datetime.datetime.strptime(f'{p_year}-W{int(p_week )- 1}-1', "%Y-W%W-%w").date() wednesday = monday + datetime.timedelta(days=2) friday = monday + datetime.timedelta(days=6.9) - datetime.timedelta(days=2) return friday but when I serializer data and Set serialize = ExamSimulatorSerializer(request.data) date = fridayOfWeek(serializer["week"]) it gives me and error File "C:\Users\user1\Desktop\backend\data_manager\views.py", line 43, in examSimulator date = fridayOfWeek(m['week']) File "C:\Users\user1\Desktop\backend\week_into_date.py", line 10, in fridayOfWeek monday = datetime.datetime.strptime(f'{p_year}-W{int(p_week )- 1}-1', "%Y-W%W-%w").date() Exception Type: TypeError at /api/exam-simulator/ Exception Value: int() argument must be a string, a bytes-like object or a number, not 'BoundField' my serializer class class ExamSimulatorSerializer(serializers.Serializer): week = serializers.IntegerField() subject = serializers.CharField() code = serializers.CharField() def create(self, validated_data): pass my views.py @api_view(['POST']) @parser_classes([JSONParser]) def examSimulator(request): m = ExamSimulatorSerializer(request.data) code = m['code'] date = fridayOfWeek(m['week']) subject = Subject.objects.get(name = m['subject']) for s in subject.students.all().values(): student = Student.objects.get(roll_num=s['roll_num']) score = random.randint(25,95) Exam.objects.create(code=code, date=date, student=student, subject=subject,score=score) return Response(status=status.HTTP_200_OK) Moreover Is this the right way to make a model-less serializer class