Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django FilterSet for JSON fields
For example, I have a simple django-model: class SimpleModel(models.Model): some_attr = models.JSONField() #there is [attr1, attr2, ...] in JSON Simple view: class SimpleView(ListCreateApivView): filter_backends = [DjangoFilterBackend, ] filterset_class = SimpleFilter And simple filter: class SimpleFilter(django_filters.FilterSet): class Meta: model = SimpleModel fields = {'some_attr': ['icontains', ]} I wanna check is the http://127.0.0.1/simple?some_attr__icontains=['Something, that I have in db'] In my db there is JSONField, which contains [a1, a2, a3 ...], so, how can I check is value from url is in db JSONField? -
'list' object is not callable - django 1.9
First, I want to say that my project is very old (python 2.7, django 1.9). For this piece of code: @property def codes(self): codesList = [] invoices = self.invoice_set.all() for invoice in invoices: for ic in invoice.invoice_codes.all(): code = ic.suggestion_code.number if code not in codesList: codesList.append(code) print(codesList) return codesList def _statistic_claim_count(self): codesList = [] if self.status in [Claim.APPROVED, Claim.INVOICED]: codesList = self.codes() for code in codesList: issc, _ = InvoiceSuggestionCodeStatistic.objects.get_or_create( suggestion_code=code ) if self.status == Claim.APPROVED: issc.count_approved_claims() if self.status == Claim.INVOICED: issc.count_invoiced_claims() issc.count_claims() issc.save() def save(self, *args, **kwargs): super(Claim, self).save(*args, **kwargs) self._statistic_claim_count() I get 'list' object is not callable and the stack trace points out these calls: self._statistic_claim_count() codes = self.codes() I thought there might be something wrong with the way the code was wrritten because wherever you will see codesList in my code the previous name of the variable was codes. I changed them to codesList and I still get this error. Where can this error come from? I really can't get it. Thanks. -
Why do i have to restart the Django server every time I make some changes in views?
I am new to Django and every time I make a change in veiws.py or urls.py I have to run python manange.py run server. This is hectic as for every small change I have to restart the server. Is there any fix? Or is this normal? Thank you!!! -
How to add two numbers in jinja
I have a mark object which I want to list in table {% for mark in marks %} <tr> <td>{{forloop.counter}}</td> <td>{{mark.subject.name}}</td> <td>75</td> <td>25</td> <td>{{mark.mark}}</td> <td>{{mark.mark_pr}}</td> <td>{{ (mark.mark + mark.mark_pr) }}</td> <td>A</td> <td>70</td> </tr> {% endfor %} I want to display the sum of mark.mark and mark.mark_pr into third last but when I try doing (mark.mark + mark.mark_pr) it gives me error saying "Could not parse the remainder: '(mark.mark + mark.mark_pr)' from '(mark.mark + mark.mark_pr)" do anyone have any idea on how to do it? Thanks in advance. -
Openlayers display Points from Geodjango REST API endpoint
I am trying to display points on an OSM map using Openlayers and (Geo)Django. The points should be provided by a REST API endpoint which I want to query from within the openlayers javascript. The JS part looks like this: <div id="map" class="map shadow m-auto"></div> <script type="text/javascript"> var map = new ol.Map({ target: 'map', layers: [ new ol.layer.Vector({ source: new ol.source.Vector({ format: new ol.format.GeoJSON(), url: "http://localhost:8000/api/sites" }) }) , new ol.layer.Tile({ source: new ol.source.OSM(), }) ], view: new ol.View({ center: ol.proj.fromLonLat([8,48]), zoom: 10 }) }); </script> The API endpoint is just serializing a django queryset and therefore returns the following: [ { "sid":13, "site_name":"Burgsteig", "site_notes":"Reuter.2003", "municipality":1047, "geom":{ "type":"Point", "coordinates":[ 8.779644092464917, 48.00504767358004 ] } }, { "sid":14, "site_name":"Brederis, \"Weitried\"", "site_notes":"Hagn2002", "municipality":16180, "geom":{ "type":"Point", "coordinates":[ 9.628734475883569, 47.2756455228491 ] } }, { "sid":15, "site_name":"Burgweinting, \"Villa\"/\"Mühlfeld\"", "site_notes":"Zintl2012, Zintl2013", "municipality":2767, "geom":{ "type":"Point", "coordinates":[ 12.11373087937611, 49.01308089544727 ] } } ] It is just a basic API endpoint by django-rest-framework and as far as i know returns a pretty standard geoJSON format dataset. However, when running this i get an "Uncaught Error: Unsupported GeoJSON type: undefined". The basemap is displaying, it is just something wrong with that geojson. As far as I understand, the API is not … -
django upload image from url
error File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/botocore/hooks.py", line 211, in _emit response = handler(**kwargs) File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/botocore/utils.py", line 2355, in conditionally_calculate_md5 md5_digest = calculate_md5(body, **kwargs) File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/botocore/utils.py", line 2332, in calculate_md5 binary_md5 = _calculate_md5_from_file(body) File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/botocore/utils.py", line 2344, in _calculate_md5_from_file for chunk in iter(lambda: fileobj.read(1024 * 1024), b''): File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/botocore/utils.py", line 2344, in <lambda> for chunk in iter(lambda: fileobj.read(1024 * 1024), b''): File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/s3transfer/utils.py", line 483, in read data = self._fileobj.read(amount_to_read) File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/s3transfer/upload.py", line 86, in read return self._fileobj.read(amount) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte [27/Apr/2022 13:14:52] "POST /api/asset-file/ HTTP/1.1" 500 283894 signal @receiver(post_save, sender=DesignerProductMedia) def save_profile(sender, instance, **kwargs): video = instance.file url = instance.url if url and not video: from django.core.files import File import os result = urllib.urlretrieve(instance.url) instance.file.save( os.path.basename(instance.url), File(open(result[0])) ) instance.save() return model: class DesignerProductMedia(models.Model): url = models.CharField(max_length=255, null=True, blank=True) file = models.FileField(null=True, blank=True, upload_to='asset') Here i am trying upload image from url I have url and using postman i am sending url after saving that from url i am generating file and added to model But getting above error Please take a look how can i solve this -
Unable to import djstripe.models to views.py
All the migrations have been successful and all the models and tables have been imported successfully by running command python3 manage.py djstripe_sync_plans_from_stripe enter image description here -
POST-request not working (django / rest_framework api)
i have got the ticket management system "helpdesk" running in django and i am trying to connect to it via an API (rest_framework). So far, i have managed to get the GET and PUT requests running via the rest_framework APIview. However, everytime i try to do a POST-request, i get the following error: Error Message I tried similar requests with selfmade django projects with simpler models and they all worked fine. Do you have an idea about what i did wrong here? By the way, i'm only working with all of this for about 2 weeks now, so please don't blame me for simple mistakes. Thanks in advance for your help! :) This is my api_views.py: from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import generics, viewsets from rest_framework.pagination import LimitOffsetPagination from .serializers import DatatablesTicketSerializer from .models import Ticket from rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer @api_view() def first_api_view(request): num_tickets = Ticket.objects.count() return Response({'num_tickets': num_tickets}) def all_tickets(request): tickets = Ticket.objects.all() ticket_serializer = DatatablesTicketSerializer(tickets, many=True) return Response(ticket_serializer.data) class AllTickets(generics.ListAPIView): # renderer_classes = [JSONRenderer] #toggle to switch raw json and optimized view queryset = Ticket.objects.all() serializer_class = DatatablesTicketSerializer class TicketViewSet(viewsets.ModelViewSet): # pagination_class = LimitOffsetPagination # ?? #authentication_classes = [] def list(self, request): … -
CSS changes happen on diffrent URL than expected
I am trying to create a webapp and on localhost:8000 I would like to put on the main page a table that shows a dataset of schools. The problem is that the css styles do not apply to localhost:8000, but they happen on localhost:63342 instead. localhost:63342 style modifications can be visible (see GID cell) database does not load localhost:8000 style cannot be seen database loads I would like to be able to see the style modifications on localhost:8000 as well schooldetails.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="schooldetails.css"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>Document</title> <style> th,td{ border: 1px black solid; } </style> </head> <body> <h1>School Page</h1> {% if schools %} <table> <tr id="school-gap "> <th class="cell">GID</th> <th>Type</th> <th>Province</th> <th>Street</th> <th>House_number</th> <th>Postcode</th> <th>City</th> <th>Municipality</th> <th>Geometry</th> </tr> <tr> {% for st in schools %} <td>{{st.gid}}</td> <td>{{st.schooltype}}</td> <td>{{st.provincie}}</td> <td>{{st.straatnaam}}</td> <td>{{st.huisnummer}}</td> <td>{{st.postcode}}</td> <td>{{st.plaatsnaam}}</td> <td>{{st.gemeentena}}</td> <td>{{st.geom}}</td> </tr> {% endfor %} </table> {% else %} <h1>No Data</h1> {% endif %} </body> </html> schooldetails.css /* (A) CONTAINER */ #school-gap { /* (A1) GRID LAYOUT */ display: grid; /* (A2) SPECIFY COLUMNS */ grid-template-columns: auto auto auto; /* we can also specify exact pixels, percentage, repeat grid-template-columns: 50px 100px 150px; grid-template-columns: 25% 50% 25%; grid-template-columns: 100px … -
SendGrid not fetching Send_Email_Id in Django when I am adding SendGrid template_id
I am getting 200 success codes. Email is been sending but when I am adding template id then still 200 is coming but the message is not delivering to the sent email. sg = sendgrid.SendGridAPIClient(settings.SENDGRID_API_KEY) data = { "from": { "email": settings.DEFAULT_FROM_EMAIL, "name": "######" }, "template_id":'########', "personalizations": [ { "subject": "Hello,Testing 1", "to": [ { "email":email } ], "dynamic_template_data ": [ { "info": info } ], } ], } try: response = sg.client.mail.send.post(request_body=data) print(response.status_code) print(response.body) print(response.headers) return Response( data={"message": f"success"}, status=status.HTTP_200_OK, ) except Exception as e: print(str(e)) -
send email when changing value in list_editable in Djngo admin
I am trying to implement a solution that will enable owners to send emails automatically whenever the owner changes the status and clicks save in list_view in the admin panel. The idea is that the owner goes to the admin panel, changes and saves the status for instance from received to in_progress and the user who sent a request receives an email notification. I am not sure what kind of method or function should I overwrite in my RequestsAdmin model to send an email when clicking save in my list_view in the admin panel. Creating the custom action to change status is not an option in this case. models.py class Requests(models.Model): STATUS = ( ('received', _('Question received')), ('in_progress', _('In progress')), ('ready_to_check', _('Ready to check')), ('published', _('Published')), ) user = models.CharField(max_length=255, blank=True, null=True,) owner = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=1000, blank=True, null=True, default='') body = models.TextField('Description') publish_date = models.DateTimeField(default=timezone.now) priority = models.BooleanField(default=False, blank=True, null=True)default=False) status = models.CharField(max_length=32, choices=STATUS, default='received') admin.py class RequestsAdmin(ImportExportModelAdmin): list_display = ('title', 'publish_date', 'priority', 'owner', 'status') list_editable = ('status', ) admin.site.register(Requests, RequestsAdmin) -
How can I test the data saved in a session?
I new to Django and I'm trying to implement unittest. Is there a way to test the data saved in a session ? Here is a simple view, where dummy data is saved in the session. def save_data_in_session(request): request.session["hello"] = "world" # If I print(request.session.items()), output is dict_items([('hello', 'world')]) as expected. context = {} return render(request, "home.html", context) Here is my unittest class TestDummyViews(TestCase): def test_save_data_in_session(self): session = self.client.session url = reverse("home_page:save_data_in_session") response = self.client.get(url) session.save() # If I print(session.items()) output is dict_items([])... # Following test passes self.assertEqual(response.status_code, 200) # Following test fails. KeyError: 'hello' self.assertEqual( session["hello"], "world", ) -
How render django-table when click on TamplateColumn delete button?
I try build user table with delete option I use django table2 to view the list and when I click on delete button and delete user I want to render only the table list_of_user.html: {% load static %} {% load render_table from django_tables2 %} {% load bootstrap4 %} {% bootstrap_css %} <link rel="stylesheet" href="{% static "userApp/list_of_user.css" %}" /> <div class="container"> {% block content %} <div class="row"> {% if filter %} <div class="col-sm-10"> <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='inline' %} {% bootstrap_button 'filter' %} </form> </div> {% endif %} <div id="table-user" class="col-sm-10"> {% render_table table % </div> </div> {% endblock %} </div> userTable.py from django.contrib.auth.models import User import django_tables2 as tables class Bootstrap4Table(tables.Table): email = tables.EmailColumn() username = tables.Column() first_name = tables.Column() last_name = tables.Column() option = tables.TemplateColumn( template_name="userApp/delete_button.html", orderable=False, verbose_name='' ) class Meta: model = User template_name = 'django_tables2/bootstrap4.html' fields = ('email', 'username', 'first_name', 'last_name', 'option') attrs = {"class": "table table-hover", "icon": "bi bi-trash"} delete_button.html {% load static %} {% load bootstrap4 %} {% bootstrap_css %} <button data-toggle="tooltip" onclick="destoryUser({{record.id}})" title="Please note that deletion cannot be undone" type="submit" class="btn-sm btn-primary">delete <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash3" viewBox="0 0 16 16"> <path d="M6.5 1h3a.5.5 0 0 1 .5.5v1H6v-1a.5.5 … -
geeing vertical scroll bar after adding ckeditor django
before adding ckeditor my webpage was working fine but when I add ckeditor to my textarea field I get an vertical scroll bar. my problem is I want to remove that scroll bar which I have got after adding ckeditor template code is <div class="container"> <form method="POST"> <div class="form-group"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4" style="font-weight: 700;">Create Notes</legend> </fieldset> {{form.media}} {{form|crispy}} <div class="form-group"> <button href="" class="btn btn-primary" type="submit"> Create </button> </div> </div> </form> model.py title=models.CharField(max_length=200) description = RichTextField(blank=True,null=True) my second problem is I want to remove image ,table and anchor optio from editor please help me to figure it out thanks in advance -
Problems with Django Avatars
I have a problem in my django app and when I edit a user my avatar photo is deleted and returns to the default one, I think the problem is in the views because it works correctly if I load the values from the django admin, If you could help me, I would appreciate it very much. This is the code: Views: @login_required def editar_user(request): mensaje = "" if request.method == "POST": extension_logued_user, _ = Avatar.objects.get_or_create(user=request.user) FormularioUser = NuestraEdicionUser(request.POST, request.FILES) if FormularioUser.is_valid(): logued_user = request.user #intancia del Usuario logued_user.email = FormularioUser.cleaned_data['email'] logued_user.first_name = FormularioUser.cleaned_data['first_name'] logued_user.last_name = FormularioUser.cleaned_data['last_name'] extension_logued_user.imagen = FormularioUser.cleaned_data['imagen'] extension_logued_user.link = FormularioUser.cleaned_data['link'] extension_logued_user.more_info = FormularioUser.cleaned_data['more_info'] if FormularioUser.cleaned_data['password1'] != '' and `FormularioUser.cleaned_data['password1'] == FormularioUser.cleaned_data['password2']:` logued_user.set_password(FormularioUser.cleaned_data.get("password1")) else: mensaje = "" if extension_logued_user.imagen is None: pass logued_user.save() extension_logued_user.save() return render(request, "index/index.html", {"mensaje":mensaje}) else: extension_logued_user, _ = Avatar.objects.get_or_create(user=request.user) return render(request, "EditUser.html", {"FormularioUser":FormularioUser,"mensaje":mensaje}) extension_logued_user, _ = Avatar.objects.get_or_create(user=request.user) FormularioUser = NuestraEdicionUser( initial={ 'first_name': request.user.first_name, 'last_name': request.user.last_name, 'email': request.user.email, 'imagen': extension_logued_user.imagen, 'link': extension_logued_user.link, 'more_info': extension_logued_user.more_info, } ) return render(request, "EditUser.html", {"FormularioUser": FormularioUser, "mensaje":mensaje}) Template: {% extends 'index/index.html' %} {% load static %} {% block Encabezado %} <h1>Tu cuenta</h1> {% endblock Encabezado %} {% block PruebaTemplate %} {% if msj %} {{msj}} {% endif %} {% if … -
DRF call a cached view in another view
I have some classviews that I cache for a very long amount of time and I want to use the cached version of the result to speed up my API, but each time I call the cached view like so : data = ItemRaw.as_view()(self.request._request).data it will not return me the cached view but will re-request and rebuild the data then give it to me Is there a way to properly call a chached classview to get the cached data from the said view ? Thanks. -
I want to print if the discount value is blank then do not print anything if the discount value is something then show the value
I want to print if the discount value is blank then do not print anything if the discount value is something then show the value. how I will do this in if-else conditions. ** here is my HTML code ** {% for page_details in service %} <div class="row py-5 service_item"> <div class="col-md-12 d-flex justify-content-between"> <p class="border px-3 p-1 rounded text-center bg-light text-secondary font-weight-light">{{ page_details.service_name }}</p> {% if page_details.discount_optional > 1 %} <p class="border px-3 p-1 rounded text-center text-success border-success">{{ page_details.discount_optional }} % OFF</p> {% else %} <p class="border px-3 p-1 rounded text-center text-success border-success"></p> {% endif %} </div> <div class="col-md-8"><h5 class="card-title"></h5></div> <div class="col-md-4 text-right"> <strike class="text-secondary"></strike> &nbsp;<strong>₹ {{ page_details.price }}</strong><br/> <span class="text-secondary">Inc. of all taxes</span> </div> <div class="col-12"><p class="text-success">{{ page_details.Cancellation}}</p></div> <div class="col-12"> <span class="text-secondary"> Weekday_Off : </span><span class="text-dark"> {{page_details.Business_Details.weekday_off }}</span> <span class="text-secondary"> | Open Timings: </span><span class="text-dark">{{ page_details.Business_Details.open_time }}</span> <span class="text-secondary"> | Closed Timings: </span><span class="text-danger">{{page_details.Business_Details.close_time}}</span> </div> </div> {% endfor %} my model.py file class Services(models.Model): Business_Details = models.ForeignKey(Business_Details, on_delete=models.CASCADE, blank=True,null=True) service_name = models.CharField(max_length=100, blank=True, null=True) category = models.ForeignKey(category, on_delete=models.CASCADE, blank=True,null=True) subcategory = models.ForeignKey(subcategory, on_delete=models.CASCADE, blank=True,null=True) price = models.IntegerField( blank=True, null=True) duration = models.CharField(max_length=50, blank=True, null=True) image = models.ImageField() # description = HTMLField() discount_optional = models.CharField( max_length=10,blank=True, null=True) def __str__(self): … -
Get DataError: value too long for type character varying for every string
I use Django+Postgres for my project. I tried to implement user registration, but when I try to send a form with username and password, I get database error psycopg2.errors.StringDataRightTruncation: value too long for type character varying(32) That error appears with every string as a password, even its length less than 32. I tried to print form values, so they are the same that I typed. What can be the reason for value too long error? models.py class Person(AbstractUser): username = models.fields.CharField(max_length=50,unique=True) password = models.fields.CharField(max_length=32) forms.py class RegisterForm(ModelForm): username = forms.CharField(max_length=100) password = forms.CharField(widget=PasswordInput()) class Meta: model = Person fields = ["username", "password"] views.py def register(request): context={} if request.method == 'POST': form = RegisterForm(data=request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] print('username: '+username) print('password: '+password) if len(Person.objects.filter(username=username))==0: Person.objects.create_user(username=username, password=password) else: context['form_errors']=['Person with this username already exists'] else: form = RegisterForm() error -
How to get logged in users credentials in Django?
I am trying to do some API calls from Django views. Is there any way I can get the logged in user credentials directly in the view so that I can use those creds in API authentication without asking the user to input same creds again. -
how do I show the real time value of cart without reloading the page
how do I show the real time value of cart when someone adds something to the cart without reloading the page, my function already handles the logic except it needs to reload, I'm trying to replace location.reload() in my javascript function with ajax that would just show the {{cartItems}} real time value on nav without reloading the page when someone hits the "add-to-cart" button, right now everything has to reload to work. I would really appreciate it if someone can help, thx! views.py def shop(request): data = cartData(request) cartItems = data['cartItems'] products = Product.objects.all() context = {"products": products, "cartItems": cartItems} #the nav is able to access home context def home(request): data = cartData(request) cartItems = data['cartItems'] context = {"cartItems": cartItems} def ajax_update(request): data = cartData(request) cartItems = data['cartItems'] context = {"cartItems": cartItems} return render(request, 'store/shop.html', context) urls.py path('ajax_update/', views.ajax_update, name="ajax_update"), cart.js var updateBtns = document.getElementsByClassName('update-cart') for(var i=0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) console.log('USER:', user) if(user === 'AnonymousUser'){ addCookieItem(productId, action) }else{ updateUserOrder(productId, action) } }) } function addCookieItem(productId, action){ console.log('User is not authenticated') if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 … -
Get the Image from the Private S3 bucket and convert the image to blob using django to give it to React Js
I having a logo field as Imagefield and i connected the filepath to s3 bucket. Once i upload a image in logo it will be uploaded in s3, if i delete or modify it working. But when i want to get the image to show that image in the frontend(reactjs) iam generating a url method where the aws credentials are shown in the url itself. But i need to change the image as blob(binary) and give that data to the frontend for the GET call. I dont know how can be it done, refered many sites but still not clear. Please help me solve this issue. Models.py class Organisation(models.Model): """ Organisation model """ org_id = models.AutoField(unique=True, primary_key=True) org_name = models.CharField(max_length=100) org_code = models.CharField(max_length=20) org_mail_id = models.EmailField(max_length=100) org_phone_number = models.CharField(max_length=20) org_address = models.JSONField(max_length=500, null=True) product = models.ManyToManyField(Product, related_name='products') org_logo = models.ImageField(upload_to=upload_org_logo, null=True, blank=True,) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def remove_on_image_update(self): try: # is the object in the database yet? obj = Organisation.objects.get(org_id=self.org_id) except Organisation.DoesNotExist: # object is not in db, nothing to worry about return # is the save due to an update of the actual image file? if obj.org_logo and self.org_logo and obj.org_logo != self.org_logo: # delete the old … -
Product matching query does not exist
when I try to add an item to a vendor it calls the POST method when this *view is called it shows an error that Product matching query does not exist. if you want any other files to tell I hope someone will fix this issue. class AddBaseproductToStore(AdminOnlyMixin, generic.TemplateView): template_name = 'aldobi-admin/add-product-to-store.html' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['prod_id'] = self.kwargs['pk'] context['vendor'] = self.kwargs['vendor'] return context def get(self, request, *args, **kwargs): product = BaseProduct.objects.get(id=self.kwargs['pk']) vendor_id = self.kwargs['vendor'] base_cat = BaseCategory.objects.all() return render(request, self.template_name, {"product": product, "base_cat": base_cat, 'vendor': vendor_id}) this the continuation of above code def post(self, request, *args, **kwargs): base_product = BaseProduct.objects.get(id=self.kwargs['pk']) vendor_id = self.kwargs['vendor'] base_category = BaseCategory.objects.get(id=request.POST.get('category')) try: p = Product.objects.get(base_product=base_product, category=Category.objects.get(vendor_id=vendor_id, base_category=base_category)) except AttributeError: product = Product() product.category = Category.objects.get(vendor_id=vendor_id, base_category=base_category) product.base_product = base_product product.name = request.POST.get('name') product.ar_name = request.POST.get('ar_name') product.sort_order = request.POST.get('sort-order') product.dryclean = request.POST.get('dryclean', '') == 'on' product.normal_dryclean_price = request.POST.get('dryclean_price') product.normal_dryclean_buffer_time = request.POST.get('dryclean_buffer') product.wash_and_pressing = request.POST.get('wash-press', '') == 'on' product.normal_wash_and_pressing_price = request.POST.get('wash-press-price') product.normal_wash_and_pressing_buffer_time = request.POST.get('wash-press-buffer') product.pressing = request.POST.get('press', '') == 'on' product.normal_pressing_price = request.POST.get('press-price') product.normal_pressing_buffer_time = request.POST.get('press-buffer') product.express_dryclean = request.POST.get('exp-dryclean', '') == 'on' product.express_dryclean_price = request.POST.get('exp-dryclean-price') product.express_dryclean_buffer_time = request.POST.get('exp-dryclean-buffer') product.express_wash_and_pressing = request.POST.get('exp-wash-press', '') == 'on' … -
Django-rest-framework api permission AllowAny authentication failed
I have someViews like below: class SomeView(generics.ListAPIView): serializer_class = SomeSerializer permission_classes = [AllowAny] settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), ... 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), ... } And When I request without any Authorization header it works fine. But When I add Bearer Authorization header it response "detail": "Given token not valid for any token type", "code": "token_not_valid", I gave permission_classes=[AllowAny]. Why? I thought there is no difference between sending or not sending tokens. Because I set permission_class=[AllowAny]. In ASP.NET there is no like this problems. In ASP.NET If I set AllowAny permission this endpoint open for everyone regardless of whether you send a Token or not. -
AttributeError: 'ModelName' object has no attribute 'get' if response.get("X-Frame-Options") is not None:
I'm trying to get a list of Scripts I'm not sure why this error is django throwing however, Can anybody identify if there's something is wrong. Model class Script(models.Model): name = models.CharField(max_length=100) script = models.TextField() def __str__(self): return self.name Serializer class ScriptSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(read_only=True) script = serializers.CharField(read_only=True) view; @api_view(['GET']) def scripts(request): scripts = Script.objects.all() serializer = ScriptSerializer(scripts, many=True) return Response(serializer.data) but when I call this view, I get this error Internal Server Error: /api/v1/seo/scripts Traceback (most recent call last): File "E:\folder\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "E:\folder\venv\lib\site-packages\django\utils\deprecation.py", line 136, in __call__ response = self.process_response(request, response) File "E:\folder\venv\lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'Script' object has no attribute 'get' I have also seen answers related to that issue in Stackoverflow but not able to reproduce the solution. And also this approach is not new to me, I have been using this type of functions all over the project. But I'm surprised now why it's happening. Edit: Imports from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import ScriptSerializer from .models import Script -
(DRF) How to make axios post request on nested object with reverse lookup for foreignkey as primary key
I have made Sample model as a ForeignKey to other two child model, and sample_ID as a primary key using lookup_field. models.py class Sample(models.Model): sample_ID = models.CharField(max_length=10) class Label(models.Model): AI_sample = models.ForeignKey(Sample, null=True, on_delete=models.CASCADE, related_name='AI_sample') AI_position = models.CharField(max_length=50) AI_defect = models.CharField(max_length=50) AI_tool = models.CharField(max_length=50) class Manual(models.Model): manual_sample = models.ForeignKey(Sample, null=True, on_delete=models.CASCADE, related_name='manual_sample') manual_position = models.CharField(max_length=50) manual_defect = models.CharField(max_length=50) manual_tool = models.CharField(max_length=50) Now my API endpoint looks like this: { "id": 3, "sample_ID": "a000001", "AI_sample": [ { "id": 3, "AI_position": "Position 1", "AI_defect": "Defect 1", "AI_tool": "Tool 1" } ], "manual_sample": [ { "id": 8, "manual_position": "Position 3", "manual_defect": "Scratch", "manual_tool": "Tool 2" } ] } Currently I am using reverse lookup of foreignKey to get the child data from sample_ID. Now I can easily make GET request by destructing the data like this: axios.get(url) .then(resp => { let data = []; const manual_sample = resp.data.manual_sample; manual_sample.forEach(el => { data.push({ id: el.id, manual_position: el.manual_position, manual_defect: el.manual_defect, manual_tool: el.manual_tool }); }); }) However, I am not able to make POST request out of a child data, because the I cannot set the primary key of sample_ID in a nested object. I am sending the manual_sample data request like this: { "id": 9, …