Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: invalid literal for int() with base 10: '-----'ValueError: invalid literal for int() with base 10: ''
Product(product_id2=prod_id2,shop=request.user,product_name=prod_name,category=category.objects.get(id=int(cat)),subcategory=subcategory,price=price,price_not=price_not,desc=desc,gst=gst_l,image1=image1).save() i tried int(float(Cat)) but its showing could not convert string to float: '-----' -
Why django can't recognize 2 path convertors from each other?
I have a django application and I have 2 url paths that are only different in the last part which is the path convertors: path('questions/<pk>', views.QuestionDetailView.as_view(), name='question_detail'), path('questions/<slug:tag_slug>', views.QuestionListView.as_view(), name='questions_by_tag') When I go to 127.0.0.1:8000/questions/1 it's ok and it shows the correct results, but when I go to 127.0.0.1:8000/questions/something(something is a slug) it says page not found!(It must use the seconed url path but it does not!) When I change the paths order it shows the second one correctly and the other one is a problem! Can anybody help me please? -
How to Check data is int, float in python
I know similar questions have been asked and answered before like here: How do I check if a string is a number (float or Int ) in Python? However, it does not provide the answer I'm looking for. What I'm trying to do is this: def is_int_or_float(s): try: a = float(s) return 1 if s.count('.')==0 else 2 except ValueError: return -1 val = input("Enter your value: ") data = is_int_or_float(val) print(data) What if User enters => "22" # Then Above code will gives -1.Please help me to resolve this -
How to save data from an online API to display it in Django rest framework?
I am trying to get pricing API from coinmarketcap and save them or display them locally in Django Rest framework on localhost? What different things should I do in my models.py? What different thing should I do in my views.py? I have created a requests.py with the header from which I want to get data/ API endpoint? How will I connect or store it in my models.py? At the moment my request.py file inside my API folder also gives an error of module import for requests? I have just simply created a request.py with endpoint url for getting data from coinmarketcap, where should I save it to display on drf frontend? import requests headers = { 'Accepts': 'application/json', 'X-CMC_PRO_API_KEY': ' MY API KEY', } res = requests.get("https://pro-api.coinmarketcap.com/v1/fiat/map", headers=headers) print(res.json()) print(res.text) Views.py from django.shortcuts import render from rest_framework.response import Response from rest_framework.decorators import api_view @api_view(['GET']) def getUrls(request): api_urls = { 'Crypto Prices': '/prices', } return Response(api_urls) models.py from django.db import models class Prices(models.Model): symbol = models.CharField(max_length=50) def __str__(self): return self.name -
Redirect to same page after form submitted in views.py not working while using Django paginator
I want to redirect to same page after submitting form which fetches view from views.py. The problem is paginator. After submitting Django form page reloads to page 1. I want browser to stay on the same page after submitting form. Error I get: django.urls.exceptions.NoReverseMatch: 'http' is not a registered namespace. Help would be greatly appreciated! Code calling path in js: let path = window.location.href Fetching api: subedit[i].addEventListener('click', () => { fetch(`/edit/${content[i].id}`, { method: 'POST', headers: {'X-CSRFToken': csrftoken}, mode: 'same-origin', body: JSON.stringify({ post: textarea[i].value, page: path })}).then(() => { editdiv[i].style.display = 'none'; post[i].style.display = 'block'; })}) views.py: def edit(request, post_id): data = json.loads(request.body) content = data.get("post", "") post=Post.objects.get(id=post_id) page = data.get("page", "") if request.method == "POST": if post.user == request.user: post.post=content post.save() return HttpResponseRedirect(reverse(str(page))) -
CSRF verification failed. Request aborted in Django rest framework sending the request from flutter
I've followed everything mentioned in both documentation of Django rest-framework and Flutter http but still getting the error ..here is my code : Django Settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } View @csrf_exempt @permission_classes(["isAuthenticated"]) @api_view(['POST']) def chanage_image(request): data = {} if request.method == "POST": token = request.META['HTTP_AUTHORIZATION'][6:] lang = request.META['HTTP_LANG'] image = request.data['image'] main_user = Token.objects.get(key=token).user app_user = AppUser.objects.get(main_user=main_user) format, imgstr = image.split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) # You can save this as file instance. app_user.image = data app_user.save() data = {"success": True, "details": AppUserSerializer( app_user).data, "message": "Image changed" if lang == "en" else "تم تغيير الصورة"} return Response(data, headers=get_headers()) URLS path('chanage_image/', chanage_image,name="chanage_image"), Flutter Request Map<String, dynamic> body = { "image": base64Image, }; Future<UserModel> changePlayerImage(Map<String, dynamic> body) async { return await httpClient.post('api/user/change-image', body: body, headers: {'referer': 'https://www.l-dawri.com/'}).then((response) { print(response.body); return UserModel.fromJson(response.body); }); } but still in the end am always getting this error : CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. -
Django Notify user execution state
When making a call to server I want the server to notify each time a "stage" has been completed instead of waiting complete execution. Let's say I have a call in views.py def some_call(request): final_body = long_process_with_stages() return HttpResponse(json.dumps(finalbody)) # I need to change this # return StreamingHttpResponse(long_process_with_stages()) where def long_process_with_stages(): sleep(30) print("Stage 1 completed") sleep(30) print("Stage 2 completed") sleep(30) print("Stage 3 completed") sleep(30) return "This is the final response" I tried the StreamingHttpResponse but method kept being called even after it finished Is it possible to achieve this? -
Resetting password in authenticationApp
I need the users to give their old password too while resetting the password using the link they receive from django backend. How do I implement this? Thanks in advance. -
Create a register in another table with the id as FK of the first table automatically after creating the register in the first table Django
Models.py class Email(models.Model): id = models.CharField(max_length=200, primary_key=True) subject = models.CharField(max_length=200) message = models.CharField(max_length=2000) time = models.CharField(max_length=50) read = models.BooleanField() starred = models.BooleanField() hasAttachments = models.BooleanField() class Attachments(models.Model): type = models.CharField(max_length=200) filename = models.CharField(max_length=200) preview = models.CharField(max_length=200) url = models.CharField(max_length=200) size = models.CharField(max_length=200) referring_email = models.ForeignKey(Email, related_name='email',on_delete=models.CASCADE, null=True, blank=True) Serializers.py class AttachmentSerializer(serializers.ModelSerializer): class Meta: model = Attachments fields = '__all__'#·('type','filename','preview','url','size') class EmailSerializer(WritableNestedModelSerializer): #to = ToSerializer(many=True) #froms = FromsSerializer() attachments = AttachmentSerializer(many=True, required=False) class Meta: model = Email fields = '__all__' def create(self, validated_data): #Popeo del JSON los campos Foreign Keys hayAttachments = False if(validated_data.get('attachments') != None): attachments_data = validated_data.pop('attachments') hayAttachments = True #Creo el objeto email a partir del JSON tocado email = Email.objects.create(**validated_data) if(hayAttachments): for attachment_data in attachments_data: attachment = Attachments.objects.create(**attachment_data) attachment.referring_email = email return email When I create an email, I want to automatically create an attachment and put the current email id as foreign key in the attachment table. I tried with this but only creates the attachment and set the FK=NULL, any help will be apreciated. (If you need anymore information, I'll update it) This is the Json from wich I load the data: { "id": "15459251a6d6b397565", "subject": "Commits that need to be pushed lorem ipsum dolor … -
Response.status_code 400 for a simple view test
I'm passing a simple json body to my view but I'm getting a 400 instead of a 200. It should be a really straightforward test but I can't quite figure out what is wrong. Thanks. Url: "api/v2/ada/send", views.sendView.as_view(), name="ada-send", ), View: class sendView(generics.GenericAPIView): permission_classes = (permissions.IsAuthenticated,) def post(self, request, *args, **kwargs): body = request.data return Response(body, status=status.HTTP_200_OK) View Test: class AdaSendGet(APITestCase): url = reverse("ada-send") def test_choice_type_valid( self,): user = get_user_model().objects.create_user("test") self.client.force_authenticate(user) response = self.client.post( self.url, { "contact_uuid": "49548747-48888043", "choices": 3, "message": ( "What is the issue?\n\nAbdominal pain" "\nHeadache\nNone of these\n\n" "Choose the option that matches your answer. " "Eg, 1 for Abdominal pain\n\nEnter *back* to go to " "the previous question or *abort* to " "end the assessment" ), "step": 6, "value": 2, "optionId": 0, "path": "/assessments/assessment-id/dialog/next", "cardType": "CHOICE", "title": "SYMPTOM" }, content_type="application/json", ) self.assertEqual(response.status_code, status.HTTP_200_OK) Error: self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 400 != 200 -
How to display 2 months in my calendar in Django?
so I'm making a calendar application based on this calendar design and this is how it currently looks However I want to display 2 months side by side in this calendar (in the example above I would want April to be right next to March and the days would go from March 30th, 31st and then April 1st - April 30th). Does anyone know how to do this. utils.py from datetime import datetime, timedelta from calendar import HTMLCalendar from .models import Event class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'{week}' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = Event.objects.filter(start_time__year=self.year, start_time__month=self.month) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' #cal += f'{self.formatweekheader()}\n' months … -
Django FOREIGN KEY constraint failed, when adding Many To Many Association to Instance for the second time
i am currently trying to teach myself the django framework. Something really odd is happening when trying to connect to object instances via a ManyToManyField. Starting from a fresh Database (object creation in Shell, but same problem in Code): When i create the first object (Product) everything works fine. I create the object and add the other object (ProductTag) to the ManyToManyField of the first one. Now here comes the Problem: after I did that, and try the same thing again with different Instances (or the same ones, as last time) I get an django.db.utils.IntegrityError, which says "FOREIGN KEY constraint failed" Console In/Output of the problem: (InteractiveConsole) >>> from onlineShop.apps.products.models import Product, ProductTag >>> from django.contrib.auth.models import User >>> from onlineShop.apps.profiles.models import Profile >>> p = Profile.objects.first() >>> t = ProductTag.objects.create(name="outdoor", name_verbose="Outdoor") >>> p.save() >>> p <Profile: superuser> >>> t.save() >>> t <ProductTag: Outdoor> >>> prod1 = Product.objects.create(vendor=p, title="test1", price=123.42, description="test1-desc") >>> prod1.save() >>> prod1 <Product: test1> >>> prod2 = Product.objects.create(vendor=p, title="test2", price=223.42, description="test2-desc") >>> prod2.save() >>> prod2 <Product: test2> >>> prod1.tags.add(t) >>> prod1.save() >>> prod1 <Product: test1> >>> prod2.tags.add(t) Traceback (most recent call last): File "C:\Users\lukas\.virtualenvs\Django_Shop-2dmIjN-v\lib\site-packages\django\db\backends\base\base.py", line 267, in _commit return self.connection.commit() sqlite3.IntegrityError: FOREIGN KEY constraint failed The above … -
Issue with serializer and api
My problem is that I want to to get category.name instead of category.id in api. class PostSerializer(serializers.ModelSerializer): class Meta: model = models.Post fields = ['id', 'title', 'content', 'category', 'img', 'date_posted'] But when I adding it, there disappears option in POST method to set category. For api view I use generics.ListCreateAPIView def getCategory(self,obj): return obj.category.name category = serializers.SerializerMethodField("getCategory") -
NoReverseMatch at /register Reverse for 'activate' with keyword arguments '{'uidb64': 'MjA', 'token': 'b30qd1-7f95e1136cc4896c8b15fdc839486de
I have this code running for one project and not working for another project. def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): # save form in the memory not in database user = form.save(commit=False) user.is_active = False user.save() # to get the domain of the current site current_site = get_current_site(request) mail_subject = 'Activation link has been sent to your email id' message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') else: form = SignupForm() return render(request, 'signup.html', {'form': form}) {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} def activate(request, uidb64, token): User = get_user_model() try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') path('activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/', activate, name='activate'), -
How to fill a Django form with an API response?
I need to create a form of persons, where the camp Name must receive an API response. I created the formulary e rendered the api response in template, but I can´t put it in my formulary, in order to save in my Models camp Name. So, I just want to save my API respone inside my forms and in my database. Views def cadastro(request): url = 'https://gerador-nomes.herokuapp.com/nome/aleatorio' api = requests.get(url) nome_api = ' '.join(api.json()) form = PessoaForm() form.nome = api if request.method == 'POST': form = PessoaForm(request.POST) if form.is_valid(): form.cleaned_data('nome') form.save() return redirect('/') context = {'form': form, 'api': nome_api} return render(request, 'base/pessoa_form.html', context) pessoa_form.html <body> <form action="" method="post"> {% csrf_token %} {{form}} <input type="submit" name="Cadastrar"> </form> </body> </html> Forms from django.forms import ModelForm from . models import Pessoa class PessoaForm(ModelForm): class Meta: model = Pessoa fields = '__all__' Models from django.db import models class Pessoa(models.Model): name= models.CharField(max_length=255, null=True) lastname= models.CharField(max_length=255, null=True) age= models.IntegerField(null=True) birthday_date= models.DateField() email = models.CharField(max_length=255, null=True) nickname= models.CharField(max_length=255, null=True, blank=True) note = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return self.nome class Meta: ordering = ['nome', 'sobrenome'] I have tried some things of my head but nothing actually worked, like try to access the variable Name in my forms … -
How to link between django views components
Actually, I am pretty new in Django. I have created three views in my views.py. This is my following code in views.py : from django.shortcuts import render import pymongo from .models import * from .serializers import * from .forms import * from .codes.scraping import scrap def home_view(request): context = {} context ['form'] = Scraping() return render(request,'home.html',context) def loading_view(request): return render(request,'loading.html') def datatable_view(request): client = pymongo.MongoClient("mongodb://localhost:27017/") db= client["aliexpress_db"] col = db["segment"] products = col.find() context = {'products' : products} return render(request,'datatable.html', context) My question is that I want to get a method in order to get the home_view first then my loading_view while the scraping is processing then my datatable_view. I don't know how to link between these views. I am completely beginner. Any help would be great. -
React index.js in Django Project doesn't render imported components
I am trying to build a project with a hybrid architecture with Django as Backend and React as Frontend. For this I use Webpack and Babel to pipe the js files into djangos static index-bundle.js. However I encountered a problem which I don't understand. Apparently I can not import other components into my index.js react file. Instead, the root div stays empty. While this works and the text is visible in the Browser... ReactDOM.render( <h1> React in Django </h1> document.getElementById('root') ); ... importing it from another component doesn't work (div "root" has no inner elements) ReactDOM.render( <App />, document.getElementById('root') ); class App extends Component { render() { return ( <h1>React in Django</h1> ) } } In the end I want to have the "normal" react behaviour inside the django project. -
Test User logout in Django fails
I need to test if my user is logged out correctly. When I tried to logout, the test fails. def test_user_logout(self): """Test user logout.""" user = User.objects.create_user(username="test", password="test") self.logged_in = self.client.force_login(user=user) response = self.client.post(path=reverse("logout"), follow=True) self.assertEqual(response.status_code, 200) self.assertRedirects(response, reverse("login")) self.assertTrue(user.is_anonymous) # this fails My view method is: def user_logout(request): logout(request) return redirect("login") -
How do I make signup page avilable only for logged in staff users in Django allauth?
I'm very new to Django. I used allauth to make email verification and user management system simple. I want a system where only admins (staff users) can signup users. But as it is now signup page is only available for not logged in users. How do I make signup page available only for logged in staff users in Django allauth? -
display data without using a loop Django
how do I forgo the loop and display only one product represnted by {data.title }} {% for data in data %} <h3 class="my-4 border-bottom pb-1">{{data.title }}</h3> <div class="row"> {% endfor %} tried to use <h3 class="my-4 border-bottom pb-1">{{data.title }}</h3> <div class="row"> and got a blank section, the loop works perfectly though the views function booking_detail(request, slug, id): booking=Bookings.objects.all().order_by('-id') return render(request,'booking_detail.html',{'data':booking}) model class Bookings(models.Model): title=models.CharField(max_length=200) image=models.ImageField(upload_to="rooms_imgs") slug=models.CharField(max_length=400) detail=models.TextField() features=models.TextField() location=models.ForeignKey(Location, on_delete=models.CASCADE) category=models.ForeignKey(Category, on_delete=models.CASCADE) hostel=models.ForeignKey(Hostel, on_delete=models.CASCADE) amenities=models.ForeignKey(Amenities, on_delete=models.CASCADE) roomsizes=models.ForeignKey(RoomSizes,on_delete=models.CASCADE) status=models.BooleanField(default=True) is_featured=models.BooleanField(default=False) is_availabe=models.BooleanField(default=True) url path('booking/<str:slug>/<int:id>',views.booking_detail,name='booking_detail'), -
Django - How to use django signals in async consumer classes?
I want to send a web socket from a Django signal receiver in an asynchronous consumer. The code below results in an error: Object of type coroutine is not JSON serializable Consumers.py class MessagePreviewConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() last_message_general = await self.last_message_general() await self.send(text_data=json.dumps({ 'last_message_general': last_message_general, })) @sync_to_async def last_message_general(self): last_msg = Message.objects.filter(room = 'General')[len(Message.objects.filter(room = 'General'))-1::] if len(Message.objects.filter(room = 'General')) >= 1 else Message.objects.filter(room = 'General') if last_msg: for m in last_msg: result = m.content, m.author.username, m.date_added.strftime("%H:%M") return str(result) break else: pass @receiver(post_save, sender=Message) def message_preview(sender, instance, created, **krwargs): if created: print(sender, instance, created) last_message_general = MessagePreviewConsumer.last_message_general() MessagePreviewConsumer.send(text_data=json.dumps({ 'last_message_general': last_message_general, })) Question: How can I call this send function from the signal receiver? -
Get value from span to Django view
I have this javascript that gets longitude and latitude from a Google Map: <script> // Get element references var confirmBtn = document.getElementById('confirmPosition'); var onClickPositionView = document.getElementById('onClickPositionView'); var latonIdlePositionView = document.getElementById('latOnIdlePositionView'); var longonIdlePositionView = document.getElementById('longOnIdlePositionView'); // Initialize locationPicker plugin var lp = new locationPicker('map', { setCurrentPosition: true, // You can omit this, defaults to true }, { zoom: 15 // You can set any google map options here, zoom defaults to 15 }); // Listen to map idle event, listening to idle event more accurate than listening to ondrag event google.maps.event.addListener(lp.map, 'idle', function (event) { // Get current location and show it in HTML var location = lp.getMarkerPosition(); latOnIdlePositionView.innerHTML = location.lat; longOnIdlePositionView.innerHTML = location.lng; }); </script> This is the HTML I have for a user to define his or her location: <form method="POST" action="{% url 'geolocate' %}"> {% csrf_token %} <div class="card-header"> <div class="float-start"> <h3 class="card-title">Me localiser</h3> </div> </div> <div class="card-body no-padding"> <div id="map"></div> <p>Latitude: <span id="latOnIdlePositionView"></span> Longitude: <span id="longOnIdlePositionView" ></span></p> </div> <div class="card-footer text-end"> <button type="submit" class="btn btn-primary">Mettre à jour</button> </div> </form> This is my view: def geolocate(request): if request.method == 'POST': lat = request.POST.get('lat_kw') long = request.POST.get('long_kw') caccount = Account.objects.get(username=request.user.username) caccount.lat = lat caccount.long = long caccount.save() return redirect('monprofil') … -
Django i18n multi-line translate
How to translate the snippet below using django's internalization? utils.py template = _("Below is the result of your WWE Account verification.\n" "Thank you!") django.po # try msgid "Below is the result of your WWE Account verification.\nThank you!" msgstr "A continuación se muestra el resultado de la verificación de su cuenta WWE.\n ¡Gracias!" But when I do the code snippet below... $ python manage.py shell >>> from django.utils.translation import activate, ugettext_lazy as _ >>> activate('zh-cn') >>> template = _("Below is the result of your WWE Account verification.\n" "Thank you!") >>> template 以下是您的 WWE 帐户验证结果。\n谢谢 The above outout of template is wrong. I expected a new line like below: 以下是您的 WWE 帐户验证结果。 谢谢! or Below is the result of your WWE Account verification. Thank you! -
Django request.FILE returning None
My html template <form method="post" action="" enctype="multipart/form-data" class="form-group"> {% csrf_token %} <h1 class="m-3 text-center">New Post</h1> <div id="tui-image-editor-container" style="min-height:750px;"></div> <!--<input type="file" name="name" value="" />--> <div class="row m-2"> <input type="datetime-local" class="form-control-lg col m-2" name="date" default="" /> <input type="text" class="form-control-lg col m-2" name="location" placeholder="Where are You ?" /> </div> <div class="row m-2"> <input type="text" class="form-control col m-2" name="hashtags" placeholder="Hashtags" /> <input type="text" class="form-control col m-2" name="tags" placeholder="Tag Your Friends" /> </div> <div class="row m-4"> <input type="submit" class="btn btn-primary btn-lg col" id="abc" value="Create"> </div> Javascript File document.querySelector(".tui-image-editor-load-btn").setAttribute("name", "PostedImage") views.py def newpost_view(request,email,*args,**kwargs): if request.method == 'POST': newpost = { 'date':request.POST['date'], 'location':request.POST['location'], 'hashtags':[f['value'] for f in json.loads(request.POST['tags'])], 'tags':[f['value'] for f in json.loads(request.POST['hashtags'])] } print(newpost) print(request.FILES.get('PostedImage')) id = email[0:5] variables={'id':id} return render(request,'newpost.html',variables) I want to get the Image from the input. the element itself is added via javascript, because I am using a Vanilla image manipulation snippet It gets rendered fine and my browser shows the element with the name tag added as "PostedImage" . But it shows up as an error as request.FILE['PostedImage'] shows up empty. Is it that i can't add elements once the page is loaded or I can't add name tags after and django is not reading them? I can't do this using … -
Deleting object in Django
What is the best practice to delete object in Django? Using simple "a tag" with the link to the view like this: def deleteStudent(request,id): student = get_object_or_404(Student, id = id) student.delete() return redirect('/') or using post method: <form method="POST"> {% csrf_token %} Are you want to delete this item ? <input type="submit" value="Yes" /> <a href="/">Cancel </a> </form> and in views: def deleteStudent(request, id): student = get_object_or_404(Student, id = id) if request.method =="POST": student.delete() return redirect('/') return render(request, "delete_view.html") I saw in courses that people use both of the methods (it's example code, I'didn't test it or secure views). So if we can delete objects with "POST" method, can I say in the job interview that "POST method can be also used to delete objects"? Thanks for all answers.