Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why are django tags causing problems?
Is there any reason why 1st django tag above !DOCTYPE html is causing error and {% comment %} tag is not working at all? I'm working in pycharm. -
Adding features and filtering later on the product model
If I need to explain more clearly compared to the title, there is a table on the database of the Product class created in the models.py file. Is it possible for the user to add a new attribute to this Product table? In other words, the user will add a property called color and assign values to this property, and then filter on it. A system written in PHP called IdeaSoft supports this, but is it possible to do this with Django? Is there a library about it? -
ModuleNotFoundError: No module named 'django_heroku'
i wanted to run my project in server. Well when I start the server I get an error ModuleNotFoundError: No module nameddjango_heroku enter image description here but i don't use heroku thanks for answer -
How to get certain item in Django, def view
pk argument works in class views and I have done it in that way but I am curious can i get certain item in function view in Django? views.py def cart(request): cart = Cart.objects.annotate( price=Sum(F('orderitem__item__price') * F('orderitem__quantity')) ).get(order_user=request.user) cart.total = cart.price cart.save() order_items = OrderItem.objects.filter(cart=cart) context = { 'cart': cart, 'order_items': order_items} if 'checkout' in request.POST: reverse('checkout-page') if 'minus' in request.POST: item = OrderItem.objects.filter(??) item.quantity = F('quantity') - 1 item.quantity.save() return render(request, 'shop/cart.html', context) models.py class OrderItem(models.Model): cart = models.ForeignKey('Cart', on_delete=CASCADE, null=True) item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) total_price = models.IntegerField(default=1) -
Make files public when uploading to AWS S3 bucket from Django
I am working with a basic music streaming application at the moment and would like for all files uploaded to my S3 bucket to have public read access. Right now, when they are uploaded using "upload_to" in a FileField they are not public. How would I adjust my code to make this an automatic process? concert.models from django.db import models from django.db.models import ( CharField, TextField, ForeignKey, BooleanField, DateField, FileField, IntegerField, CASCADE ) import uuid import pdb from django.contrib.auth.models import User from django.utils import timezone from django.utils.timezone import now def user_directory_path(instance, filename): random_file_name = "".join([str(uuid.uuid4().hex[:6]), filename]) return "concerts/{0}/{1}/{2}/{3}/{4}/{5}".format(instance.concert.date.year, instance.concert.date.month, instance.concert.date.day, instance.concert.venue, instance.concert.pk, random_file_name) class Band(models.Model): name = TextField() def __str__(self): return self.name class Concert(models.Model): venue = TextField() date = DateField() city = CharField(null=True, blank=True, max_length=100) state = CharField(null=True, blank=True, max_length=100) country = TextField() band = ForeignKey(Band, on_delete=CASCADE, related_name='concert') user = ForeignKey(User, on_delete=CASCADE, related_name='concert') date_created = DateField(default=now) def save(self, *args, **kwargs): '''On save, update timestamps ''' if not self.id: self.date_created = timezone.now() return super(Concert, self).save(*args, **kwargs) def __str__(self): return self.venue class Song(models.Model): title = TextField() concert = ForeignKey(Concert, on_delete=CASCADE, related_name='song') user = ForeignKey(User, on_delete=CASCADE, related_name='song', null=True, blank=True) concert_order = IntegerField(null=True, blank=True) audio_file = models.FileField("Song", upload_to=user_directory_path, null=True) date_created = DateField(default=now) def save(self, … -
How to add view count everytime endpoint get request accessed
I'm building a REST API with Django rest framework. One of the models : class Feed(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length = 200) content = models.TextField() thumbnail = models.ImageField(upload_to=get_profile_image_filepath, default='uploads/feed/index.jpg', blank=True) imgpath = models.CharField(max_length = 200, blank=True, default=timestr) author = models.CharField(max_length = 100) date = models.DateTimeField(auto_now_add=True) view = models.IntegerField(default=0) I want the feed view added when the user accessed the endpoint. views.py class FeedDetail(generics.RetrieveAPIView): queryset = Feed.objects.all() serializer_class = FeedSerializer urls.py path('feeds/<int:pk>/', FeedDetail.as_view()), -
How to set a proxy model for select related in Django?
I have two models: class Parent(models.Model): some_field = models.CharField(max_length=50, default='') class Child(models.Model): parent = models.ForeignKey(Parent) And two proxy models for Parent: class ProxyParentFirst(Parent): class Meta: proxy = True class ProxyParentSecond(Parent): class Meta: proxy = True How to set proxy model of Parent in select related for Child: children = Child.objects.all().select_related('ProxyParentFirst') or children = Child.objects.all().select_related('ProxyParentSecond') -
Adding to manytomany field returns empty queryset
I am trying to add items in the many-to-many field. After adding it, I am getting an empty queryset. It taking me crazy. if request.user.is_authenticated: order = Order.objects.create(restaurant=Restaurant.objects.get(code_name=restaurant_code), table=Table.objects.get(code_name=request.data['table']), customer=request.user ) else: order = Order.objects.create(restaurant=Restaurant.objects.get(code_name=restaurant_code), table=Table.objects.get(code_name=request.data['table']) ) for menuitem in request.data['menuItems']: customList = [ItemType.objects.get(id=v) for v in list(menuitem['addOns'])] orderedMenuItem = OrderedMenuItem.objects.create(quantity=menuitem['quantity'], menuitem=MenuItem.objects.get(pk=menuitem['id']), remarks=menuitem['remarks']) orderedMenuItem.custom_item_types.add(*customList) order.ordered_menu_items.add(orderedMenuItem) order.save() Here I have ItemType as manytomany field got orderedMenuItem model. When trying to add ItemType object into OrderedMenuItem model, its giving empty query set. -
MyModelAdmin must have search_fields for the autocomplete_view
I have 404 in Admin suggest with error ApartmentPromotionAdmin must have search_fields for the autocomplete_view. My admin organized as follows from string import Template from dal import autocomplete from django import forms from django.contrib import admin from django.contrib.admin.widgets import AutocompleteSelect from django.forms import widgets class PromotionApartmentForm(forms.ModelForm): class Meta: fields = "__all__" widgets = { "apartment": AutocompleteSelect( ApartmentPromotion._meta.get_field("apartment").remote_field, admin.site, attrs={"style": "width: 400px"}, # You can put any width you want. ), } class ApartmentPromotionAdmin(admin.ModelAdmin): form = PromotionApartmentForm list_display = ("id", "apartment") autocomplete_fields = ["apartment"] I have admin.site.register(ApartmentPromotion, ApartmentPromotionAdmin) and models are class ApartmentPromotion(models.Model): apartment = models.ForeignKey(Apartment, on_delete=models.CASCADE, related_name="promotions") ... def __str__(self): return f"<{self.id}> {self.apartment} {self.status}" class Meta: indexes = [ models.Index(fields=["id"]), models.Index(fields=["apartment_id"]), ] class Apartment(models.Model): owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="owned_apartments") .... class Meta: indexes = [ models.Index(fields=["owner_id"]), ] could you help me to fix the problem ? -
Update Task APIView' object has no attribute 'action'
I m totally new in django and rest. I wanna write a program that only lets the owner update or delete his tasks. When I try to use it, it doesn't prohibit me to update or delete (others tasks) and when I press the update or delete button it returns me this error "Update Task APIView' object has no attribute 'action'" Thanks for helping models.py class Task(models.Model): title=models.CharField(max_length=250) text=models.TextField() user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False) status=models.ForeignKey('Status',on_delete=models.SET_NULL,null=True) startDate=models.DateTimeField(auto_now_add=True) endDate=models.DateField(null=True) def __str__(self): return self.title class Status(models.Model): name=models.CharField(max_length=250) def __str__(self): return self.name Permissions.py: from rest_framework import permissions class IsOwner(permissions.BasePermission): def has_object_permission(self, request, view,obj): if (obj.user == request.user) | (view.action == 'retrieve'): return True else: return False Serializers.py: from rest_framework import serializers from .models import Task,Status class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task # fields = ['title', 'text', 'status', 'endDate'] fields = '__all__' class StatusSerializer(serializers.ModelSerializer): class Meta: model = Status fields = '__all__' Views.py class TaskViewSet(ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Task.objects.all() serializer_class = TaskSerializer permission_classes = [permissions.IsAuthenticated, IsOwner,] def perform_create(self, serializer): serializer.save(user=self.request.user) class ListTaskAPIView(generics.ListAPIView): serializer_class = TaskSerializer permission_classes = [IsAuthenticatedOrReadOnly] model= Task def get_queryset(self): """ Optionally restricts the returned purchases to a given user, by filtering against … -
Do you need to know how to design a database before you can create a good django model?
Do django developers draw a database architecture before they code it in the models.py? If yes , does it mean you have to be good in database design before you can create a good database-driven website? If yes where do I get to learn database design? -
django many-to-many-field in list display for item like count
I want to display total likes against each item in Django admin list_display. The many to many field is linked with the user model. Below is my code Model: class Item(models.Model): title = models.CharField(max_length=100) description= RichTextField(blank=True, null=True) main_image= models.ImageField(null=False, blank=False,upload_to='images/') upload = models.FileField(upload_to ='uploads/') date = models.DateTimeField(auto_now_add=True) item_category = models.ForeignKey(Categories, default='Coding', on_delete=SET_DEFAULT) item_tool = models.ForeignKey(Tools, default='XD', on_delete=SET_DEFAULT) slug = models.SlugField(unique=True, blank=True, null=True) # new author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='post_likes') def total_likes(self): return self.likes.count() Admin.py from django.contrib import admin from .models import Categories, Item, Tools class ItemAdmin(admin.ModelAdmin): list_display = ('title','author','item_category','date') list_filter = ('item_category',) admin.site.register(Categories) admin.site.register(Item, ItemAdmin) admin.site.register(Tools) -
Can't login in Django project after switching to django 3 and return to django 2
I have a Django 2.2 project that runs in a bunch of different servers, but they use the same database. I've created a branch to migrate to Django 3, but not all servers will be migrated at the same time. I use Argon2: # https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', ] When I switched to django 3.2 in my developing branch everything worked fine. But then, when I returned to Django 2.2, I started getting errors like: Template syntax error Incorrect padding (exception location: .../python3.6/base64.py in b64decode) Those problems where solved by just deleting the cookies and reloading. So I guessed that they were related to the change in django 3.1 to a new default hashing algorithm from sha1 to sha256. Anyway, after reloading, the page worked. But when I tried to login it didn't recognize the credentials. Then I restored the database from backup and could login in django 2.2. I tried again to run on django 3.2 with the setting: DEFAULT_HASHING_ALGORITHM = 'sha1' Now, when switching back to 2.2, I didn't get errors on page load (I didn't need to delete cookies) but the credentials still didn't work. For me it looks like after switching … -
Django model how to do many to one mapping?
I am trying to map multiple field to same field in vendor and menu class. If I map using foreign key like below it works. But this is not what I want. class OrderItem_Mon(models.Model): vendor_name = models.ForeignKey(Vendor, on_delete=models.SET_NULL, null=True) menu_name = models.ForeignKey(Menu, on_delete=models.SET_NULL, null=True) date_created = models.DateTimeField('date created', auto_now_add=True) note = models.CharField('note', max_length=255, null=True, blank=True) I need to map multiple field to same field of specific table like this. class OrderItem_Mon(models.Model): vendor_name_1 = models.ForeignKey(Vendor, db_column='vendor_name', on_delete=models.SET_NULL, null=True) menu_name_1 = models.ForeignKey(Menu, db_column='menu_name',on_delete=models.SET_NULL, null=True) vendor_name_2 = models.ForeignKey(Vendor, db_column='vendor_name',on_delete=models.SET_NULL, null=True) menu_name_2 = models.ForeignKey(Menu, db_column='menu_name', on_delete=models.SET_NULL, null=True) date_created = models.DateTimeField('date created', auto_now_add=True) note = models.CharField('note', max_length=255, null=True, blank=True) However, it does not work. How do I make this work? Basically, I need to make new form that have dropbox that gets value from vendor and menu model to each field. Help -
Django: I want to create a self-generated code based on previous records and a sequential number
I'm a coding noob and I'm writing a website in Django for Project and task management, and I want to generate a project code field in a 'Project' model automatically based on previous records. I was thinking to make the 'project code' a CharField which must have 3 parts: 'department code', a foreign key of a 'Department' model with its own 'name' and 'code' fields, from which I only need the 2-3 letter code value, a 'year' code based on project start date using the last 2 digits of the date's year, and a sequence code which should be the last record based on the above filters +1. The project code field should look like this: DDD-YY-SS, where DDD is department code, YY is 2-digit year number and SS the sequence number. I'm trying to include the code generator in a custom save method like this: def save(self, *args, **kwargs): dpt = str(self.department.code) project_date = self.projectdate yy = str(project_date.year)[-2:] filter_kw = '{}-{}-'.format(dpt, yy) lastrec = ProjectModel.objects.filter(project_code__startswith = filter_kw).last() if lastrec == None: lastrec = '00' else: lastrec = str(lastrec.project_code)[-2:] newnum = "{:02d}".format(int(lastrec)+1) self.code = '{}-{}'.format(filter_kw, str(newnum)) super(ProjectModel, self).save(*args, **kwargs) But I think this code is... sketchy? I feel like using … -
Django race condition aggregate(Max) in F() expression
Imagine the following model: class Item(models.Model): # natural PK increment = models.PositiveIntegerField(_('Increment'), null=True, blank=True, default=None) # other fields When an item is created, I want the increment fields to automatically acquire the maximum value is has across the whole table, +1. For example: |_item____________________________| |_id_|_increment__________________| | 1 | 1 | | 2 | 2 | | 4 | 3 | -> id 3 was deleted at some stage.. | 5 | 4 | | 6 | 5 | .. etc When a new Item() comes in and is saved(), how in one pass, and in way that will avoid race conditions, make sure it will have increment 6 and not 7 in case another process does exactly the same thing, at the same time? I have tried: with transaction.atomic(): i = Item() highest_increment = Item.objects.all().aggregate(Max('increment')) i.increment = highest_increment['increment__max'] i.save() I would like to be able to create it in a way similar to the following, but that obviously does not work (have checked places like https://docs.djangoproject.com/en/3.2/ref/models/expressions/#avoiding-race-conditions-using-f): from django.db.models import Max, F i = Item( increment=F(Max(increment)) ) Many thanks -
Page not found (404) Request Method: GET trying to click to another .html file
I've done so much research I must have clearly missed something done or something wrong. The server I'm running is localhost:8000 I've added the homepage everything works fine until I try to click on another html file and received Page not found (404) Request Method: GET trying to Using the URLconf defined in user.urls, Django tried these URL patterns, in this order: admin/ secret/ home/ [name='home'] home/ [name='contact'] home/ [name='Project'] ^static/(?P<path>.*)$ index/Project.html. Here's the root urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from django.views.generic import RedirectView from portfolio_django import views admin.autodiscover() urlpatterns = [ path('admin/', include('admin_honeypot.urls', namespace='admin_honeypot')), url('secret/', admin.site.urls), path('home/', include("portfolio_django.urls")), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) from django.urls import path from portfolio_django import views urlpatterns = [ path('', views.home, name='home'), path('', views.contact, name='contact'), path('', views.Project, name='Project') views.py from django.shortcuts import render # Create your views here. def home(request): return render(request, 'home.html') def Portfolio(request): return render(request, 'Project.html') def contact(request): return render(request, 'contact.html') -
How to perform multiple count analytics using django?
I have an analytics dashboard - basically it shows the overview of the data's. Lets say that we have a table named "Records" In my analytics dashboard, i need to show various details about the records of particular user: user = Records.objects.filter(id=pk) By this we get all the records associate with the user, now to show various analytics like as follows, Total Records, Total Records by Today Total Records by Week Total Records by Month Total Active Records // Records which has status == active Total InActive Records // Records which has status == inactive How to do all these ? While researching i found few options to follow, Option 1 : Do separate query for each of the need Option 2 : Do fetch all the data's and perform the above calculations in view and send as context How to deal with these ? Am also planning to use charts -
generate a qr code and when scanned display url data in django
here when an item is added when need to automatically generate the qrcode and when scan with our mobile camera it need to show the url data Python version = 2.7 Django version = 1.8 qrcode version = 6.0 lets us consider my models.py as def qr_code_file_name(instance, filename): return '%s/qr_codes/%s/' % (instance.client_id, filename) class StockItems(models.Model): item_name = models.CharField(max_length=512) qr_code = models.ImageField(upload_to=qr_code_file_name, blank=True, null=True) def __unicode__(self): return self.item_name def save(self, *args, **kwargs): qrcode_img = qrcode.make(self.item_name) canvas = Image.new('RGB',(90,90),'white') draw = ImageDraw.Draw(canvas) canvas.paste(qrcode_img) fname = File('qrcode-code1.png') buffer = BytesIO() canvas.save(buffer,'PNG') self.qr_code.save(fname,File(buffer),save=False) canvas.close() When i am trying the save the new item created and the automatically saving the qr_code i am getting an error Here is my traceback of error Traceback (most recent call last): File "/home/andrew/.virtualenvs/projectscan/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/andrew/.virtualenvs/projectscan/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/andrew/.virtualenvs/projectscan/local/lib/python2.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/andrew/devel/projectscan/mcam/server/mcam/core/views.py", line 516, in dispatch return super(CustomAuthMixin, self).dispatch(request, *args, **kwargs) File "/home/andrew/.virtualenvs/projectscan/local/lib/python2.7/site-packages/braces/views/_access.py", line 102, in dispatch request, *args, **kwargs) File "/home/andrew/.virtualenvs/projectscan/local/lib/python2.7/site-packages/django/views/generic/base.py", line 89, in dispatch return handler(request, *args, **kwargs) File "/home/andrew/.virtualenvs/projectscan/local/lib/python2.7/site-packages/django/views/generic/edit.py", line 249, in post return super(BaseCreateView, self).post(request, *args, **kwargs) File "/home/andrew/.virtualenvs/projectscan/local/lib/python2.7/site-packages/django/views/generic/edit.py", line 215, in post … -
Is it important to create virtual environment for new project in django-admin?
Is it important to create virtual environment for new project in django-admin -
Django (HTML) - Clickable label in template (not working)
I'm working on a Django project where I would like using some customized checkbox forms when this issue shown up. Both code chunks are exactly the same, but using different forms. The issue comes when the first's sample label is clickable (so I can hide the radio button), but the second one is not working as expected, the user must click on the radio button, if I hide it the whole label becomes useless. NOT WORKING PROPERLY: <form action="" class="form-group" method="POST"> <div class="modal-body"> <div class="row"> <div class="col"> <ul> {% csrf_token %} <fieldset > {% for radio in form_pizzas.producto %} <li style="list-style-type:none"> <span class="radio">{{ radio.tag }} <label class="label" for="{{ radio.id_for_label }}"> {{ radio.choice_label }} </label> </span> </li> {% endfor %} </fieldset> </ul> </div> <div class="col"> {{form_pizzas.cantidad.label}} {{form_pizzas.cantidad}} {{form_pizzas.observaciones.label}} {{form_pizzas.observaciones}} </div> </div> </div> <div class="modal-footer"> <button class="btn btn-light" type="button" data-bs-dismiss="modal">Volver</button> <input type="submit" class="btn btn-primary" value="Agregar" /> </div> WORKING PROPERLY: <form action="" class="form-group" method="POST"> <div class="modal-body"> <div class="row"> <div class="col"> <ul> {% csrf_token %} <fieldset > {% for radio in form_emp.producto %} <li style="list-style-type:none"> <span class="radio">{{ radio.tag }} <label class="label" for="{{ radio.id_for_label }}"> {{ radio.choice_label }} </label> </span> </li> {% endfor %} </fieldset> </ul> </div> <div class="col"> {{form_emp.cantidad.label}} {{form_emp.cantidad}} {{form_emp.observaciones.label}} {{form_emp.observaciones}} </div> </div> … -
I am trying to sorting data in django the data is coming from different table in different dropdown but I am stuck I am not getting perfect match
**basically I am making a search engine for car's selling company in this search engine data is coming from different models but I am not getting the accurate data using these filter how can I get the perfect match I need help to solve this problem I will be very thankfull to you ** home.html <form action="/searchdd" method="POST" id="indexForm" data-cars-url="{% url 'ajax_load_cars' %}"> {% csrf_token %} <div class="col-md-12"> <div class="row"> <div class=" col-md-3"> <label for="" class="white">Make</label> <select id="companyddl" name="companyname" class="searchengine"> <option disabled selected="true" value="">--Select Make--</option> {% for company in companies %} <option value="{{company.CompanyID}}">{{company.CompanyName}}</option> {% endfor %} </select> </div> <div class=" col-md-3"> <label for="" class="white">Model</label> <select id="carddl" name="carname" class="searchengine"> <option disabled selected="true" value="">--Select Model--</option> </select> </div> <div class="col-md-3"> <label for="" class="white">From Year</label> <select name="fromdate" id="fromdate"> <option disabled selected="true" value="">--select Year--</option> {% for manf in manufac %} <option value="{{manf.ManufacturingYMID}}">{{manf.ManufacturingDate}}</option> {% endfor %} </select> </div> <div class="col-md-3"> <label for="" class="white">To Year</label> <select name="todate" id="todate"> <option disabled selected="true" value="">--select Year--</option> {% for manf in manufac %} <option value="{{manf.ManufacturingYMID}}">{{manf.ManufacturingDate}}</option> {% endfor %} </select> </div> </div> </div> <div class="col-md-12"> <div class="row"> <div class="dropdown my-2 col-md-3 col-sm-12"> <label for="" class="white">Type </label> <select name="type" id="type" class="searchengine" style="padding-right: 7px; margin-left: 3px;"> <option disabled selected="true" value="">--Select Type--</option> {% for ty … -
How can i do this via aggregation in django
I have a method in the model that saves the final price in the cart, it looks like this: class Cart(models.Model): """Cart""" owner = models.OneToOneField('Customer', on_delete=models.CASCADE) meals = models.ManyToManyField(CartMeal, related_name='related_cart', blank=True) total_products = models.PositiveIntegerField(default=0) final_price = models.DecimalField(max_digits=9, decimal_places=2, default=0) in_orders = models.BooleanField(default=False) for_anonymous_user = models.BooleanField(default=False) def save(self, *args, **kwargs): if self.id: self.total_products = self.meals.count() self.final_price = sum([cmeals.final_price for cmeals in self.meals.all()]) super().save(*args, **kwargs) I was told that I can make this line self.final_price = sum([cmeals.final_price for cmeals in self.meals.all()]) with a single query using aggregate. How can I do this and where? In the model or do I need to do this in the view? Thanks. -
Django Unable to test API patch method with query parameters other than pk MultiValueDictKeyError
I have an APIView implementing patch for an entity (lets say money). I can send a request from axios and the money gets updated but I cannot make the test to work. The request.query_params are empty when I send them via self.client.patch inside the test case. Then it throuws MultiValueDictKeyError('money_code') Here is the code: class UpdateMoneyQuantity(APIView): def patch(self, request): try: money_code = request.query_params["money_code"] money_object = Money.objects.get(money_code=money_code) # set partial=True to update a data partially serializer = MoneySerializer( money_object, data=request.data, partial=True ) if serializer.is_valid(): serializer.save() return Response(data=serializer.data, status=HTTP_200_OK) return Response(data=serializer.errors, status=HTTP_400_BAD_REQUEST) except Money.DoesNotExist as err: return Response( data={ "error": "Unable to find the desired code." }, status=HTTP_400_BAD_REQUEST, ) except Exception as err: logger.exception( f"Unable to perform patch on money quantity. \n Exception: {str(err)}" ) return Response(data=str(err), status=HTTP_500_INTERNAL_SERVER_ERROR) Here is the url: path( "update-money-quantity/", UpdateMoneyQuantity.as_view(), name="update-money-quantity", ), Here is the test case I am trying to write but couldn't make it work. class MoneyUpdateTest(APITestCase): def test_update_quantity(self): """ Ensure we can update the quantity. """ obj = Money.objects.create( money_code="RG100TEST1", supplier="Test supplier", ) params = {"money_code": "RG100TEST1"} url = reverse("update-money-quantity") data = { "saving": 110, "actual_saving": 105, } response = self.client.patch(url, data=data, query_params=params) self.assertEqual(response.status_code, HTTP_200_OK) self.assertEqual( Money.objects.get(money_code="RG100TEST1").saving, 110 ) self.assertEqual( Money.objects.get(money_code="RG100TEST1").actual_saving, 105 ) -
HTML files are not recognised in Django project
I am learning Django, everything was working fine but there was no syntax highlighting for django commands like {% block body_block %} {% endblock %} and so on... So, i installed a vscode extensions Django by Baptiste Darthenay and Django by Roberth Solis, now syntax highlighting is working but HTML files are not recognised Link. There is no code completion, everything has to be typed word by word. Disabling these extensions is working well, but then there is not syntax highlightling. Please Help!!