Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Value Error saying The QuerySet value for an exact lookup must be limited to one result using slicing
I am working on a project and i am trying to add products in the cart, but i am facing an issue : ValueError at /onlineshopping/add-to-cart/p1/, this is the location. The logic also checks whether the item is current present in the order or not to not create duplicate items. I am not getting where am i wrong. Please help me out. Here is urls.py: path('cart/', views.cart, name='cart'), path('add-to-cart/<str:slug>/', add_to_cart, name='add-to-cart'), Here is models.py: class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(AffProduct, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username Here is views.py: @login_required def add_to_cart(request, slug): item = AffProduct.objects.filter(slug=slug) order_item = OrderItem.objects.get( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("cart") else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("cart") else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("cart") This is my cart.html: {% block … -
Django Models Relationship and Creation Flow - How to link all models to the user's parent
I’me new to software development, and I'm struggling with a basic design problem. I’m building a SaaS platform where the user Admin signs up and creates and Organization. Every user should belong to an organization. The user can add abstract users Workers and Hubs, and every worker belongs to a hub. Any model that is created should belong to an organization. I’m trying to figure out the best practice to associate all the models to their respective organizations and how the signup flow should be with both Admin and Organization. Should I create the user first or the organization? Does it matter? Also I'm a bit confused on how to use created_by.organization or request.user.organization to assign the created Worker to the creator's organization in the worker creation form (the same concept will apply to all other forms). User Model class CustomUser(AbstractUser): ... organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="organization", null=False) ... Organization Model class Organization(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200, blank=False, validators=[MinLengthValidator(3)]) email = models.EmailField(max_length=70, blank=False, unique=True, validators=[ MinLengthValidator(3)]) image = models.ImageField( upload_to='organizations-images/', blank=True, null=True) timezone = TimeZoneField(default='Europe/London', choices_display='WITH_GMT_OFFSET') def __str__(self): return self.name Worker Model class Worker(CustomUser, TimeStampedModel): hub = models.ForeignKey( Hub, on_delete=models.RESTRICT, related_name='hub_workers' ) def __str__(self): return … -
How can update field by overriding save method which is in another models
I have two models PaymentModel and MeterModel. PaymentModel have this fields: payment_id = models.CharField(max_length = 100,primary_key=True, blank=True, editable=False, unique=True, default=create_new_payment_id) meter_serial_number = models.ForeignKey(MeterModel, on_delete = SET_NULL,null=True) payment_amount = MoneyField(max_digits = 14, decimal_places = 2, null = False, blank = True, default_currency = 'INR') payment_timestamp = models.DateTimeField(auto_now_add = True) payment_type = models.CharField(max_length = 20, choices = payment_mode_choises, default = '1') payment_mode = models.CharField(max_length = 20, choices = payment_type_choises, default = '1') # PAyment mode transaction_id = models.CharField(max_length = 25) transaction_details = models.CharField(max_length = 100) and MeterModel have this fields: tarrif_id = models.ForeignKey(TarrifMasterModel,on_delete=models.RESTRICT) ca_number = models.ForeignKey(CustomerDetailModel, on_delete=models.RESTRICT) meter_model_number = models.CharField(max_length=100, blank=True) calibration_certificate_number = models.CharField(max_length=100, blank=True) bill_date = models.PositiveSmallIntegerField(null=True, blank=False, validators=[MinValueValidator(0), MaxValueValidator(31)]) current_outstanding = MoneyField(max_digits=10, decimal_places=2, default_currency='INR', default=0.0) last_bill_number = models.ForeignKey(BillDetailModel,on_delete=SET_NULL, null=True, blank=True) I want to update_field current outstanding in meter_detail after by overriding save method in PaymentModel when payment is post. assume it payment amount is 60 and current outstanding is 10 then payment amount total is 70. If user only pay Rs. 40 then remaining Rs.20 want to be get update in current outstanding of meter_detail I tried this but doesn't work def save(self,*args, **kwargs): print(self.payment_amount) print(self.meter_serial_number.meter_serial_number) print(self.meter_serial_number.current_outstanding) new_outstanding = self.payment_amount - self.meter_serial_number.current_outstanding print("new_outstanding : ",new_outstanding) meter_detail = MeterDetailModel.objects.filter(meter_serial_number=self.meter_serial_number).first() print("meter_detail : … -
Is conditional rendering good in django?
I dont know if conditional rendering a whole html template is good or bad ? I understand that we can do this on templates but just wanna know if this is okay? In my view, if profile.exists(): return render(request, 'index.html') else: return render(request, 'nodata_index.html') Is this good, or shall i do if template condition on templates ? Is there any problem using the above method or shall go with template formats -
Django, xlsxwriter and images
I have django site where I am trying to create an excel file with an image in it. The image is on a AWS: https://unord-tools-django-project-static.s3.eu-central-1.amazonaws.com/media/public/10e8f47bb84901d20ff435071577c58b_TFxmjcV.jpg I am using: xlsxwriter==1.4.5 and trying to write it with: worksheet_s.insert_image(5, thisColumn, str('https://unord-tools-django-project-static.s3.eu-central-1.amazonaws.com/media/public/'+image)) My model looks like this: class Room(models.Model): # Relationships location = models.ForeignKey("asset_app.Locations", on_delete=models.SET_NULL, blank=True, null=True) room_type = models.ForeignKey("asset_app.Room_type", on_delete=models.SET_NULL, blank=True, null=True) # Fields name = models.CharField(max_length=30) image = models.ImageField(storage=PublicMediaStorage(), null=True, blank=True ) The error I am getting is this: worksheet_s.insert_image(5, thisColumn, str('https://unord-tools-django-project-static.s3.eu-central-1.amazonaws.com/media/public/'+image)) TypeError: can only concatenate str (not "ImageFieldFile") to str -
Django Rest Framework Bad Request with Image - "submitted data was not an image"
I am having an extremely similar problem to this stack overflow question: Django REST Framework upload image: "The submitted data was not a file" I am trying to submit an image to DRF, and getting this error: {"image":["The submitted data was not a file. Check the encoding type on the form."]} Except, I'm trying to follow the advice in that question, and while it worked for one model, it is absolutely not working for another. Here's my serializer: from rest_framework import serializers from .models import Blog from article.serializers import Base64ImageField class BlogSerializer(serializers.ModelSerializer): class Meta: image = Base64ImageField(max_length=None, use_url=True) model = Blog fields = ['date', 'body', "id", "title", "image", "published"] The Base64ImageField function is exactly the same as listed on that other question My Blog model looks like this: from django.db import models def imageFile(instance, filename): return '/'.join(['images', filename]) class Blog(models.Model): date = models.DateField("Post date") title = models.CharField(max_length=255) body = models.TextField(blank=True) image = models.ImageField(upload_to=imageFile, null=True, blank=True, max_length=255) published = models.BooleanField() This is working for the Article model, but no matter what I try, I cannot make it save for Blog. Here is the API View class I call: class BlogCreateView(generics.CreateAPIView): queryset = Blog.objects.all() serializer_class = BlogSerializer Why is this error happening? … -
Django how to list and update object in same page?
I am using two different views and html template for update and show my objects. First template for list all objects and second template for update each object. Right now when I am clicking any objects in list page then it's taking me to update page. is it possible to update and show all objects in same page? here is my code: #Here I am listing all objects def ListProjectView(request): project = CustomerProject.objects.all() context = {"project":project} return render(request,'members/clientproject.html',context) #this view for update object def UpdateList(request,pk=None): obj = get_object_or_404(CustomerProject, pk=pk) form = CustomerProjectFroms(request.POST or None, instance=obj) if request.method == "POST": if form.is_valid: form.save() context = {'form':form} return render(request,'members/projectupdate.html',context) urls.py path('reviewproject/', views.ListProjectView, name='list-project-view'), path('<int:pk>', views.UpdateList, name='update-list'), #list_html #here I am showing all objects {%for i in project %} <a href="{%url 'members:update-list' i.pk %}">{{i.project_title}}</a> {%endfor%} #update_html <form method="POST"> {% csrf_token %} {{form}} <button type="submit">SUBMIT</button> </form> -
Django CORS request external redirect not allowed
I faced a problem during send GET request to a django view from react, and those view redirect to GOOGLE_AUTH_ENDPOINT., and this url hit a callback function. But after request from react, it give this error: Access to fetch at "google auth url" (redirected from 'localhost:8000') from origin 'localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. view class Glogin(APIView): params = { 'client_id': CLIENT_ID, 'response_type': 'code', 'scope': 'openid email profile', 'redirect_uri': CALLBACK_DOMAIN, 'state': state, } if APPS_DOMAIN: params['hd'] = APPS_DOMAIN def get(self,request): request.session['googleauth_csrf'] = state request.session['next'] = request.META.get('HTTP_REFERER', None) print('Here') print(urlencode(self.params)) return HttpResponseRedirect("%s?%s" % (GOOGLE_AUTH_ENDPOINT, urlencode(self.params))) #data = {'link':GOOGLE_AUTH_ENDPOINT, 'params':self.params} #return Response(data) ReactJs static GLogIn() { return fetch("http://127.0.0.1:8000/glogin/", { //method: "POST", method: "GET", headers: { "Content-Type": "application/json", }, //body: JSON.stringify(body), }).then((response) => response.json()); } URL urlpatterns = [ path('', include(router.urls)), path('auth/', obtain_auth_token), path('login/',views.LogInViewSet.as_view()), path('logout/',views.LogOutViewSet.as_view()), path('articles/',views.ArticlesView.as_view()), path('articles/<int:pk>/',views.ArticlesView.as_view()), path('glogin/',views.Glogin.as_view()), path('callback/',views.Callback.as_view(), name='googleauth_callback'), #path('articales/',views.ArticlesViewSet.as_view()) ] settings.py CORS_ORIGIN_WHITELIST = ( 'localhost:3000', #'accounts.google.com', #'accounts.google.com/o/oauth2/v2' ) CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] -
django with automatic curd rest api
Django will generate UI automatically, I like to enhance so that all it also has rest API CURD operation automatic so if a order page builder a CURD(Post, Put, Get, Delete) API automatically created with pagination like following: GET <context-url>/orders --> get all orders POST <context-url>/order {"name": "pizza", "quantity" : 2} PUT <context-url>/order {"id" 1, "name": "pizza", "quantity" : 3} DELETE <context-url>/order/1 GET <context-url>/order/1 -
why django is not adding user to my table (i'm using postgres)?
i'm trying to add users to user table which comes default by django, but unfortunately it is not adding the users to table after submitting the register form . whenever i'm submiting the form it is not adding user to the table , even when i'm trying to print on console it is also not working :( don't know what to do , please help me this is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'telusko', 'USER':'postgres', 'PASSWORD':'root', 'HOST':'localhost' } } this is my register.html <Html> <head> <title> Registration Page </title> </head> <body bgcolor="Lightskyblue"> <br> <form action="/users/register" method="post" > {% csrf_token %} <label> Firstname </label> <input type="text" name="firstname" size="15"/> <br> <br> <label> Lasttname </label> <input type="text" name="laststname" size="15"/> <br> <br> <label> username </label> <input type="text" name="username" size="15"/> <br> <br> <label> Password: </label> <input type="password" name="password2" size="15"/> <br> <br> <label> Conform Password: </label> <input type="password" name="password2" size="15"/> <br> <br> <label> Email: </label> <input type="email" name="email" size="15"/> <br> <br> <input type="submit" value=" Register " size="15"/> <br> </form> this is my views.py for register app from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.models import User,auth from django.contrib import messages # Create your views here. def register(request): if request.method=='POST': … -
Increment Value independent of for loop in Django Template
On my template I have the need to include the next css elements: collapseOne collapseTwo collapseThree collapseFour Currently the structure on the template looks like this: for i in list_i: for j in list_j: collapseOne <- On the first iteration this is generated. collapseTwo <- On the second iteration this is generated. collapseTree <- On the Third iteration this is generated. I generate the css element with the next template tag {{ forloop.counter|num_to_word|title }}. but the forloop.counter only consider the second for (list_j). I know that's the behavior expected. I want that the elements are generated for each time that loop is iterated considering the two fors. As result I want : # First Iteration for i in list_i: for j in list_j: collapseOne <- On the first iteration this is generated. collapseTwo <- On the second iteration this is generated. collapseTree <- On the Third iteration this is generated. # Second Iteration for i in list_i: for j in list_j: collapseFour <- On the first iteration this is generated. collapseFive <- On the second iteration this is generated. collapseSix <- On the Third iteration this is generated. If there is another way to solve this, I'll appreciate. -
Creating new Wagtail Hooks
there is list of available Wagtail Hooks. How do I create my own Hook? To give you a little context: I want to create a hook which hooks in right before or after an Image/media or a document is deleted. Within the hook I want to validate every page, so there won't be any empty fields/blocks. For some reason it is possible to delete an image and the page will still get served, so in my opinion there should be a function/hook to validate every page again if an image is deleted. -
Django UpdateView does not save new data when testing
When I use my application on running server to update existing entry it works but when I run the test it creates entry, post it but does not update the fields title and author so I get an assertion error. When I compare prints from updating on running application and test I can't notice any difference. MODEL: class Book(models.Model): title = models.CharField(max_length=120) author = models.CharField(max_length=100) published = models.IntegerField(validators=[MaxValueValidator(datetime.date.today().year)], help_text="Use the following format: YYYY") isbn_10 = models.CharField(max_length=10, null=True, verbose_name='ISBN_10') isbn_13 = models.CharField(max_length=13, null=True, verbose_name='ISBN_13') cover_uri = models.CharField(max_length=200) language = models.CharField(max_length=56) slug = models.SlugField(max_length=120, unique=True, blank=True) TEST: def test_update_book(self): """Create book object and updates fields with correct data""" book = Book.objects.create(title='Camera Work 1', author='Alfred Stieglitz', published='2008', isbn_10='', isbn_13='9788389192868', cover_uri='image.jpg', language='english') response = self.client.post( reverse('books-update', kwargs={'slug': book.slug}), {'title': 'The Catcher in the Rye', 'author': 'J.D. Salinger', 'published': '2008', 'isbn_10': '', 'isbn_13': '9788389192868', 'cover_uri': 'image.jpg', 'language': 'english'}) self.assertEqual(response.status_code, 200) book.refresh_from_db() print('BOOK', book) self.assertEqual(book.author, 'J.D. Salinger') URL PATTERN: urlpatterns = [ path('update/<str:slug>', BookUpdateView.as_view(), name='books-update'), ] AND VIEW: class BookUpdateView(UpdateView): model = Book fields = '__all__' success_url = '/' template_name = 'books/book_update.html' def post(self, request, *args, **kwargs): print('POST', request.POST, kwargs) return super().post(request, *args, **kwargs) When I use my template to update that entry it works but … -
npm ERR! missing script: dev on linux
This is the complete error that I am getting. $ npm run dev npm ERR! missing script: dev npm ERR! A complete log of this run can be found in: npm ERR! /home/twinkle/.npm/_logs/2021-08-05T15_26_27_095Z-debug.log I am trying to integrate django and react so my django server is working on port 8000 as normal but when I type the command npm run dev or npm run build, I get this error despite including them in "scripts" in package.json. My package.json file "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development --watch", "build": "webpack --mode production" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.15.0", "@babel/preset-env": "^7.15.0", "@babel/preset-react": "^7.14.5", "babel-loader": "^8.2.2", "react": "^17.0.2", "react-dom": "^17.0.2", "webpack": "^5.48.0", "webpack-cli": "^4.7.2" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.14.5", "@material-ui/core": "^4.12.3", "@material-ui/icons": "^4.11.2", "react-router-dom": "^5.2.0" } } Any help regarding this matter would be beneficial. -
django basic search function saying NoReverseMatch
I'm trying to follow this tutorial to make a todoapp and if i search something its saying NoReverseMatch at /todoapp/ with Reverse for 'search' not found. 'search' is not a valid view function or pattern name. here's my views.py def searchtodolist(request): if request.method == 'GET': query = request.GET.get('content', None) if query: results = Todoitem.objects.filter(content__contains=query) return render(request, 'todoapp.html', {"results": results}) return render(request, 'todoapp.html') and here's the urls.py urlpatterns = [ # path('url path, views.py function names) # ex. 127.0.0.1:8000/admin/ path('addTodo/', addTodo), path('admin/', admin.site.urls), path('deleteTodo/<int:todo_id>/', deleteTodo), path('search/', searchtodolist), ] and lastly my todoapp.html <body> <br> <form action="{% url 'search' %}" method="get">{%csrf_token%} <input type="text" name="content" placeholder="Search a todolist" class="form-control"> <input type="submit" name="submit" value="Search"/> </form> <table> <tr> <th colspan="2">List of Todos</th> </tr> {% for result in results %} <tr> <td>{{result.content}}</td> <td><form action="/deleteTodo/{{todo_items.id}}/" style="display: inline; " method="post"> {%csrf_token%} <input class="button button1" type="submit" value="Delete"/> </form></td> </tr> {% endfor %} </tr> </table> </body> -
How to limit Django URL parameter to a list of options?
I have the following URL in my project: from django.urls import include, path urlpatterns = [ path('case/<str:type>/<int:id>/', views.case, name='case'), ... ] It works fine, but the type URL parameter can literally only have 2 values in my database: "internal" and "external". How can I limit this in my URL path itself? Would save me from having to validate it in the view. Thanks for any help. -
Django Formset one form in each row
How to place each form of a formset on a horizontal line, one below the other without using a table? My html is putting everything on one line. Any help much appreciated. Html [<div class="form-group row"> <div class="row"> {{ formset.management_form }} {% for form in formset.forms %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} <div class="col-sm-2"> {{ form.logical_operator|as_crispy_field }} </div> <div class="col-sm-3"> {{ form.event|as_crispy_field }} </div> <div class="col-sm-2"> {{ form.operator|as_crispy_field }} </div> <div class="col-sm-2"> {{ form.event_value|as_crispy_field }} </div> <div class="col-md-1 align-self-center delete-form"> <button onclick="exclude(this)" type="button" title="Excluir" class="btn btn-danger btn-sm"> <i class="feather icon-trash-2"></i> </button> </div> {% endfor %} </div> </div> -
unit test for django models containing "User" as ManyToManyField
So, I have a model 'P' that has the already provided with django model, "User" as the manyToManyField like this, favorite = models.ManyToManyField(User, related_name='pages') I think to unit test, I first create an instance of P then assign what a user to the favorite field? For this , I would have to create an instance of User ,right ? Can you suggest how to go on about what should go in this favorite field to create an object of this kind successfully and how to have P be related to favorite to be able to conduct unit test. Also, what unit test can I do for this ManyToManyField? -
Yelp fusion api returns empty list in django
I need to get the list of nearby restaurants with yelp api , this is my function : def list_of_search_result_by_yelp(categories,lat,lng,radius): api_key = 'mykey' url = 'https://api.yelp.com/v3/businesses/search' headers = {'Authorization': 'Bearer %s' % api_key} parameters = {'categories':categories,'latitude':lat , 'longitude':lng, 'limit':50, 'radius':radius} response = requests.get(url=url, params=parameters , headers=headers ) bussines_data = response.json() return JsonResponse(bussines_data ,safe=False) and this the url i try to send parameteres with GET method : http://127.0.0.1:8000/api/time/yelplocation/?categories=restaurants&lat=29.62184903895586&lng=52.52689019901044&radius=2000 it returns empty list but i can see info of restaurants around this place on google map! -
How set example of value in input box of django form
I would like to do the exact same thing as this has the only difference that the default text disappears when the user enters text name = models.CharField(max_length=16, default="default value") Exemple : Thks -
Storing values in django template
in my random_numbers.py i have this: from django import template from random import randint register = template.Library() @register.simple_tag() def randomNumber(): return randint(1, 250) I basically want to call a random number in the Django template, store it, then compare. I tried using javascript and wrote this: {% load random_numbers %} <script> var random_number = "{% randomNumber %}" console.log(random_number); document.getElementById("random").innerHTML = random_number; </script> But I'm not sure how to collect the js variable in the Django template, can anyone help with this or show me another approach? -
Create view with more models
hi everyone I have a doubt with the use of forms and models. I have to create a code that creates records in multiple tables and I don't know how to do it. my goal is to create a page where I can enter all the data and when I save it creates the various tables filled in with the data provided by the user. I'm a beginner I still have to learn the mechanism well =) forms.py from django import forms from .models import Schede, DatiGruppi, Gruppi class CreaSchedaForm(forms.ModelForm): nome_scheda = forms.CharField( required = True, label ='Nome scheda', widget = forms.TextInput( attrs = { 'class': 'form-control', 'placeholder' : 'nome scheda', 'autocomplete' : 'off' } ) ) data_inizio = forms.DateField( label='Data inizio', widget = forms.DateInput( attrs= { 'type': 'date', 'class': 'form-control', 'placeholder' : 'data inizio' } ) ) data_fine = forms.DateField( label='Data fine', widget = forms.DateInput( attrs= { 'type': 'date', 'class': 'form-control', 'placeholder' : 'data fine' } ) ) class Meta: model = Schede fields = ['nome_scheda','data_inizio','data_fine'] class CreaDtGruppoForm(forms.ModelForm): giorni_settimana = forms.ChoiceField( choices = DatiGruppi.giorni_settimana_scelta ) dati_gruppo = forms.ModelChoiceField( queryset = Gruppi.objects.all(), empty_label = "-", required = True ) class Meta: model = DatiGruppi fields = ['giorni_settimana', 'dati_gruppo'] views.py @login_required … -
form validation redirection problems
Hi i am adding comments on a post using django, im saving the information directly in the database , this operates successfuly, but after submitting the post it suppose to redirect on the same page with the comment but, the form keep on resubmitting help please? views.py class PostDetailView(DetailView): def get(self, request, slug, *args, **kwargs): post = Post.objects.get(slug=slug) form = CommentForm() comments = Comment.objects.filter(post=post).order_by('-date_created') context = { 'post':post, 'form': form, 'comments': comments } return render(request, 'my_news/post_detail.html', context ) def post(self, request, slug, *args, **kwargs): post = Post.objects.get(slug=slug) form = CommentForm(request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.name = request.user new_post.post= post new_post.save() comments = Comment.objects.filter(post=post).order_by('-date_created') context = { 'post':post, 'form': form, 'comments':comments } return render(request, 'my_news/post_detail.html', context ) -
how to use tag url in js admin django "django.jQuery"
I have a js app using ajax, but it's being called in admin, example js django.jQuery.ajax({ type: 'post', // url: "{% url 'emails_checkout' %}", url: '{% url "emails_checkout" %}', data: { 'template': evt.editor.getData() }, but url rendering is real url plus string in http /admin/shop/post/1/change/%7B%%20url%20%22emails_checkout%22%20%%7D HTTP/1.1" 500 12622 how to use the tag {% url '' %} correting -
Could you help me please how i can put an empty file in django rest framework
I am using django rest framework my problem is that i can post image successfully but i want to post an empty image using put method only. Following is my code: My models.py file class Blog(models.Model): id = models.AutoField(primary_key=True) title = models.TextField(max_length = 50) author = models.TextField(max_length = 50) description = models.TextField() date = models.DateField(auto_now=True) time = models.TimeField(default=timezone.now) image = models.FileField(null=True, verbose_name="") user = models.ForeignKey(User, on_delete=models.CASCADE) My serializers.py file class BlogSerializer(serializers.ModelSerializer): title = serializers.CharField(max_length=128, required=True, error_messages={'blank': "Please provide title"} ) author = serializers.CharField(max_length=128, required=True, error_messages={'blank': "Please provide author"}) description = serializers.CharField(max_length=128, required=True, error_messages={'blank': "Please provide description"}) image = serializers.FileField(required=False, error_messages={'invalid': "Please upload Image, Video or Audio file"}) # user_id = serializers.SerializerMethodField('get_user_id') id = serializers.SerializerMethodField('get_id') date = serializers.SerializerMethodField('get_date') time = serializers.SerializerMethodField('get_time') class Meta: model = Blog # fields = ["id","title","author","description","image","date","time","user_id",] fields = ["id","title","author","description","image","date","time",] # Adding additional fields to a modelserializer using SerializerMethodField def get_user_id(self, user_id): user_id = self.context['request'].user.id return user_id def get_id(self, blog): id = blog.id return id def get_date(self, blog): date = blog.date return date def get_time(self, blog): time = blog.time return time My views.py file @api_view(['PUT']) # @csrf_exempt @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def update_blog(request, id): try: blog = Blog.objects.get(id=id) except Blog.DoesNotExist: return Response(status=404) if blog.user_id != request.user.id: return Response({'response':'You do …