Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Raising an issue after upgrading Django version
I upgraded my Django version from 3.1.2 to 3.2. But it gives me this error. django.core.exceptions.ImproperlyConfigured: Cannot import 'api'. Check that 'apps.api.apps.ApiConfig.name' is correct. Please give a suggestion. Thank you. -
Django, Javascript: passing data disables functions inside app
I'm aware that a lot of people asked a similiar question, but none of these helped me with my problem!? Inside my view I'm passing the name of the active user... views.py def index(request): user = User.objects.get(username=request.user) user_name = f"{user.first_name} {user.last_name}" json_data = json.dumps(user_name) return render(request, 'index.html', {"user_name": json_data}) script.js let user_name = {{user_name|safe}}; But when trying to attach the data to my variable inside javascript, I'm getting the following error and all of my other functions inside js stop working! SyntaxError: Unexpected token '{' Does someone know what I'm doing wrong here? Thanks for your help and have a great day! -
How to iterate on dict which contains another dict in Django?
i have some issue with my application. Here's my code : view.py dict_test = {} for result in myMongoDbRequest: dict_in_dict = {} for otherResult in result["myList"]: dict_in_dict[otherResult["1"]] = [otherResult["2"], otherResult["3"]] dict_test[result["name"]] = [result["value1"], dict_in_dict] template_filter.py @register.filter def get_in_list(list, index): return list[index] template.html {% for key, values in dico_test.items %} <div id="div{{key}}"> {% for key, value in values|get_in_list:1.items %} <div class="{{ key }}"> {{ value }} </div> {% endfor %} </div> {% endfor %} Obviously, the .items in the template is incorrect, but i wonder how to resolve this problem ? Maybe with another filter ? I try several things but nothing works, like this filter : @register.filter def convert_in_dict(a): return vars(a) {% for key, value in values|get_in_list:5|convert_in_dict.items %} But django raise Could not parse the remainder: '.items' from 'values|get_in_list:1|convert_in_dict.items' -
Having one single generic Viewset that can be resolved through its router basename on Django Rest Framework
My question is more about refactoring, best practices and potential vulnerability while organizing my routes and views in DRF. My app is really a simple one and all the views are to be described in the same fashion. Take my views.py file for example: # views.py class TrackView(viewsets.ModelViewSet): queryset = Track.objects.all() serializer_class = TrackSerializer class AlbumView(viewsets.ModelViewSet): queryset = Album.objects.all() serializer_class = TrackSerializer class ArtistView(viewsets.ModelViewSet): queryset = Artist.objects.all() serializer_class = ArtistSerializer class ChartView(viewsets.ModelViewSet): queryset = Chart.objects.all() serializer_class = ChartSerializer And in urls.py I can do: #urls.py router = DefaultRouter() router.register(r'tracks', TrackView) router.register(r'albums', AlbumView) router.register(r'artists', ArtistsView) router.register(r'charts', ChartsView) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] In this scenario every new View is a copied logic of each other only changing the name of the model they use, and for every new model added that needs a view I would basically have to create the same repeated code in urls.py and views.py. Instead of doing like that I refactored it like this: # views.py from rest_framework import viewsets class APIView(viewsets.ModelViewSet): queryset = None def get_queryset(self): return eval(self.basename).objects.all() def get_serializer_class(self): return eval(self.basename+'Serializer') # urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter from top_charts.views import * from .routes import ROUTE_NAMES router … -
Why does this work?? Class Meta, model = User
Can someone please explain this?? I'm in the process of trying my first post-tutorial project. I've made a model called Profile with 4 attributes (given_name, surname, bio, image). I've made a form called ProfileForm which inherits from UserCreationForm and i've added the 4 attributes of my model into the form as form attributes. MY Question is: Why does it only work like this class Meta: model = User This is my models.py file class Profile(models.Model): given_name = models.CharField(max_length=255) surname = models.CharField(max_length=255) bio = models.TextField(blank=True, null=True) image = models.ImageField(upload_to='uploads/', blank=True, null=True) def __str__(self): return self.given_name class Meta: ordering = ['given_name'] This is my forms.py file class ProfileForm(UserCreationForm): firstName = forms.CharField(max_length=255) lastName = forms.CharField(max_length=255) bio = forms.CharField(widget=forms.Textarea) image = forms.ImageField() class Meta: model = User fields = ['firstName', 'lastName', 'username', 'password1', 'password2', 'bio', 'image'] This is my views.py file def sign_up_view(request): if request.method == "POST": form = ProfileForm(request.POST, request.FILES) if form.is_valid(): user = form.save() login(request, user) profile = Profile.objects.create( given_name=form.cleaned_data['firstName'], surname = form.cleaned_data['lastName'], bio = form.cleaned_data['bio'], image = form.cleaned_data['image']) return redirect('home') else: form = ProfileForm() return render(request, 'core/sign_up.html', {"form": form}) Note : I'm able to achieve my desired outcome, but I'm having trouble in understanding how its working. **Also if i wanted … -
XLWT TypeError at /XLS 'tuple' object is not callable
I am getting the above-mentioned error when clicking the "export to excel" button on my form. I am using the XLWT module to print the excel sheet, so I think it might have something to do with that. Please see the below code and full error message: Views.py from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse import pyodbc from django.http import FileResponse from django.contrib import messages from django.views import View from django.template.loader import render_to_string from weasyprint import HTML import tempfile from django.db.models import Sum import datetime from datetime import datetime from dateutil.relativedelta import relativedelta import xlwt def printToXLS(request): response = HttpResponse(content_type= 'application/ms-excel') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.xls' wb=xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('TrialBalance') row_num = 0 font_style = xlwt.XFStyle() columns = ('Account' , 'Description' , 'Debit' , 'Credit') all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] AS genLedger'\ ' Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = genLedger.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType'\ ' WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122)' cursor = cnxn.cursor(); cursor.execute(all); xAll = cursor.fetchall() cursor.close() xAll_l = [] for row in xAll: rdict = {} rdict["Description"] = row[0] rdict["Account"] = row[1] rdict["Credit"] = row[2] rdict["Debit"] = … -
celery logging not showing in django application inside docker shell
from logging import error @app.task def partial_bid_created_event(event): event_time = get_event_time() print('wrong function') a = getWrongfunc() # here it should throw error because that function is not exist. error showing in my docker django shell . antiquely | Starting development server at http://0.0.0.0:8000/ antiquely | Quit the server with CONTROL-C. watcher | wrong function watcher exited with code 1 watcher | Monitoring 1 contracts using %s rinkeby.infura.io watcher | subscription id: %s 0x1feed3405f0f0680df9c9684957ad03d It is just showing exited with code 1 but i am expecting exact error for logging Is it because of celery async task ? How to get exception on this error . Please take a look -
Add and remove items in ManyToMany relation in Django
I have model as follows: class BusinessUnitGroup(models.Model): name = models.CharField(max_length=255) business_units = models.ManyToManyField(to=BusinessUnit, blank=True, null=True) capacity = models.IntegerField(null=True, blank=True) def __unicode__(self): return self.name Now in an view I have fields with group id's where the business unit needs to be added. From the other one it needs to be remove if it exists. I do it as follows: business_unit = get_or_none(BusinessUnit, id=business_unit_id) # Groups old_groups = BusinessUnitGroup.objects.exclude(id__in=form_data['groups']) for group in old_groups: group.business_units.remove(business_unit) new_groups = BusinessUnitGroup.objects.filter(id__in=form_data['groups']) for group in new_groups: group.business_units.add(business_unit) Where form_data['groups'] is an param and it's just a list of ids [1, 2, 3] That works fine, but is there any better way to do it? -
Instantiating URLS , Views and Models in Django
Is there a way to instantiate SQLite models, views and URLs in Django? I have tried to research it but couldn't find anything on the automatic creation of views, URLs and templates etc. I have thought of maybe creating models that have key values which tell the program what to instantiate, however, this doesn't seem to be the most efficient and user-friendly way of doing this -
Django tries to return the file (which was previously generated by Celery) and cannot find it
i deployed two docker files to Heroku (Celery, Django), but due to the fact that the volume is not scrapped as in docker-compose, Django tries to return the file (which was previously generated by Celery) and cannot find it. How can I solve the problem? -
In Dajango How import a function from another view?
I have this folder hierarchy: |---- ksy |---- shop |---- views.py |---- over_time |---- views.py On my shop/views.py, I have this functions: def check_consumed_hour(request, job_no, booked_hour): estimate_hour, consumed_hour = 0.0, 0.0 obj_job = JobNumbers.objects.get(Q(job_no=job_no)) total_consumed_hour = float(obj_job.consumed_hour) for job in obj_job.estimatedhours_set.all(): if request.user.userinform.section in job.shop_name: estimate_hour = float(job.man_hour) else: pass for job in obj_job.consumedhours_set.all(): if request.user.userinform.section in job.shop_name: consumed_hour = float(job.man_hour) else: pass balance_hour = estimate_hour - consumed_hour book_hour = float(booked_hour) # if balance_hour >= book_hour: # ESTIMATED HOUR EXCEED MSG SHOW. for job in obj_job.consumedhours_set.all(): if request.user.userinform.section in job.shop_name: man_hour = float(job.man_hour) man_hour += book_hour job.man_hour = str(man_hour) job.save() total_consumed_hour += book_hour obj_job.consumed_hour = str(total_consumed_hour) obj_job.save() return True else: pass On my core/views.py, I need the day_studies() function, so I'm importing like this: from plater_shop.views import check_consumed_hour But I'm getting the error: from shop.views import check_consumed_hour ImportError: cannot import name 'check_consumed_hour' How can I make this importation? I don't want to reply all code. -
How i access my django project on browser after deploye on aws ec2 used by container?
containers are working good but I'm trying to access it on browser ,but fail to access -
is there any way to send webrtc frame to python script?
I created first web app(python and django) which shows client's webcam frames This is my video.js 'use strict'; // On this codelab, you will be streaming only video (video: true). const mediaStreamConstraints = { video: true, }; // Video element where stream will be placed. const localVideo = document.querySelector('video'); // Local stream that will be reproduced on the video. let localStream; // Handles success by adding the MediaStream to the video element. function gotLocalMediaStream(mediaStream) { localStream = mediaStream; localVideo.srcObject = mediaStream; } // Handles error by logging a message to the console with the error message. function handleLocalMediaStreamError(error) { console.log('navigator.getUserMedia error: ', error); } // Initializes media stream. navigator.mediaDevices.getUserMedia(mediaStreamConstraints) .then(gotLocalMediaStream).catch(handleLocalMediaStreamError); However, I want to use client's webcam frame as an input to my machine learning script(python .py) file. In local, it was easily done via opencv and numpy. But in web, I cannot feed frames to ML model. Any suggestions? -
Django database routing parameter transmission problem
class AuthRouter: def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ params = hints.get('params') return 'default' def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ params = hints.get('params') return 'default' I want to pass some parameters to **hints, but I don’t know how to do it, can you tell me, thank you very much! I tried the following methods, but none of them work # read TestModel.objects({'params': 'Hello World'}).filter() # {TypeError}'UserManager' object is not callable TestModel.objects.filter(hints={'params': 'Hello World'}) # {FieldError} Cannot resolve keyword 'hints' into field ... # write TestModel.objects.filter().first().save(hints={'params': 'Hello World'}) # {TypeError}save() got an unexpected keyword argument 'hints' -
How to get the instance when upload file using model FileField in Django
I have a Customer model and I have a upload model, linked to Customer: model.py class BasicUploadTo(): prefix = '' suffix = dt.now().strftime("%Y%m%d%H%M%S") def upload_rules(self, instance, filename): (filename, extension) = os.path.splitext(filename) id = instance.customer_id.customer_id.user_id return os.path.join(str(id), "Docs", f"{self.prefix}_{self.suffix}{extension}") def upload_br(self, instance, filename): instance1 = Customer.customer_id self.prefix = "BR" dir = self.upload_rules(instance, filename) return dir class AttachmentsBasic(models.Model): customer_id = models.OneToOneField("Customer", verbose_name="client ID", on_delete=models.DO_NOTHING, blank=False, null=True) br = models.FileField(upload_to=BasicUploadTo().upload_br, verbose_name="BR", null=True, blank=True) class Customer(models.Model): customer_id = models.OneToOneField("UserID", blank=False, null=True, verbose_name="Client ID", on_delete=DO_NOTHING) ... class UserID(models.Model): user_id = models.CharField(max_length=5, blank=False, verbose_name="Client ID") class Meta(): verbose_name = "Client" verbose_name_plural = "Client" def __str__(self): return f"{self.user_id}" form.py: class ClientUploadForm(ModelForm): class Meta: model = AttachmentsBasic fields = ( "br",) def __init__(self, path, *args, **kwargs): super(ClientUploadForm, self).__init__(*args, **kwargs) print(path) for x in self.fields: self.fields[x].required = False def save(self, client_id, commit=True): clientDoc = super(ClientUploadForm, self).save(commit=True) print(self) instance = Customer.objects.get(customer_id__user_id=client_id) clientDoc.customer_id = instance if commit: clientDoc.save() return clientDoc views.py def clienInfo(request, client): clientsIDs = [c.customer_id.user_id for c in Customer.objects.all()] if client in clientsIDs: matching_client = Customer.objects.filter(customer_id__user_id=client) if request.method == "POST": instance = Customer.objects.get(customer_id__user_id=client) uploadForm = ClientUploadForm(request.POST, request.FILES, instance.customer_id.user_id) if uploadForm.is_valid(): uploadForm.save(request.POST["customer_id"]) else: print("Client's document form got error.") else: print("Client form got error.") uploadForm = ClientUploadForm sale = sales.objects.all() return … -
enable to verify whether data exists in database for login
i am a beginner i am trying to do a post request to get the coer_id and password from the client and then i am trying to check whether they exists in database or not .i am enable to perform it.it will be really helpful if you can tell me how i can correct it or do it . models.py from django.db import models from django.core.validators import RegexValidator class student_register(models.Model): name=models.CharField(max_length=100) father_name=models.CharField(max_length=100,null=True) bhawan=models.CharField(max_length=100,null=True) branch=models.CharField(max_length=40,null=True) coer_id=models.CharField(max_length=12,unique=True,null=True) phone_regex=RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+9999999999'. Up to 12 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17) password=models.CharField(max_length=100) serializer.py from django.db.models import fields from rest_framework import serializers from .models import student_register class register_serializers(serializers.ModelSerializer): class Meta: model = student_register fields = '__all__' class login(serializers.ModelSerializer): class Meta: model = student_register fields = ['coer_id','password'] views.py from rest_framework.response import Response from rest_framework import viewsets from .models import student_register from .serializer import register_serializers from .serializer import login from rest_framework.decorators import api_view from rest_framework import status class register_view(viewsets.ModelViewSet): queryset= student_register.objects.all() serializer_class= register_serializers @api_view(['POST']) def check_login(request): serializer=login(data=request.data) if serializer.is_valid(): if student_register.objects.filter(coer_id=serializer['coer_id']).exists(): if student_register.objects.filter(password=serializer['password']).exists(): return Response(serializer.data) else: return Response(status=status.HTTP_404_NOT_FOUND) this is the error which i get when i send the json file and post it Internal Server Error: /login/ Traceback (most … -
Where is class "django.template.Node " defined in Django source code
I am reading Django official guide and came across a statement as below: When Django compiles a template, it splits the raw template text into ‘’nodes’’. Each node is an instance of django.template.Node and has a render() method. A compiled template is a list of Node objects. But I did not find django.template.Node definition in Django source code, where is it please ? -
how can i route from one nginx serve to another?
i have a containerized nginx server currently setup with https (nginx.main) and it's serving my django app that's in another container. unfortunately, django is not responding with the static files - and i've read that's a normal thing. so, what i'd like to do is setup another instance of nginx to do that for me (nginx.static) nginx.main default.conf config that i've tried: ...some stuff going to --> server { listen 4430 ssl; listen [::]:4430 ssl default ipv6only=on; server_name avnav.com; ssl_certificate /etc/nginx/_cert/etc/letsencrypt/live/avnav.com/fullchain.pem; ssl_certificate_key /etc/nginx/_cert/etc/letsencrypt/live/avnav.com/privkey.pem; ssl_dhparam /etc/nginx/_cert/etc/letsencrypt/live/dhparam.pem; ...some security stuff... location / { proxy_pass http://django_app; proxy_set_header Host avnav.com; } location /media { proxy_pass http://nginx_static; } } nginx.main nginx.conf config: upstream django_app { server droplet.ip:8000; } upstream nginx_static { server droplet.ip:8082; } nginx.static default.conf config: server { listen 8080 default; server_name localhost; location / { root /usr/share/nginx/static/; } at first i thought it was an issue with alias vs root, but not so. the volumes are setup so that the host static files are mounted to /usr/share/nginx/static in nginx.static. inside that folder, there are subfolders for css, js, etc. nginx.main runs on port 8081:8080 django runs on 8000 nginx.static runs on 8082:8080 -
Access blocked by CORS policy: No 'Access-Control-Allow-Origin'
I am using the following versions Python 3.9.6 Django 3.2.3 django-cors-headers==3.7.0 I have the following in my settings.py CORS_ALLOW_ALL_ORIGINS=True CORS_ORIGIN_WHITELIST = ('http://localhost:3000',) For some reason, one of the API call fails out with this error. Access to fetch at from origin has been blocked by CORS policy: 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. I am not able to understand why I get this error. Here are the relevant request and response details as extracted from Google Chrome Developer tools General Request URL: http://10.0.123.123:8998/api/box?unit=101&box=TOT000000000051345&login_user_id=USERID&reserve_locn=101 Request Method: OPTIONS Status Code: 200 OK Remote Address: 10.0.123.123:8998 Referrer Policy: strict-origin-when-cross-origin Response Headers Access-Control-Allow-Headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT Access-Control-Allow-Origin: * Access-Control-Max-Age: 86400 Connection: keep-alive Content-Length: 0 Content-Type: text/html; charset=utf-8 Date: Tue, 07 Sep 2021 01:15:10 GMT Server: nginx/1.20.1 Vary: Origin Request Headers OPTIONS /api/box?unit=101&box=TOT000000000051345&login_user_id=USERID&reserve_locn=101 HTTP/1.1 Host: 10.0.123.123:8998 Connection: keep-alive Accept: / Access-Control-Request-Method: GET Access-Control-Request-Headers: content-type Origin: http://10.0.123.123:8999 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Sec-Fetch-Mode: cors Referer: http://10.0.123.123:8999/ Accept-Encoding: gzip, deflate Accept-Language: en-GB,en-US;q=0.9,en;q=0.8 -
How to connect AWS Elasticache Redis from a local machine for a Django project?
I've Redis chace installed on both my local and aws elasticache. My Django project runs well on my local machine with Redis. However, when I connect to my redis remotely on aws, I get the following error. Error 10060 connecting to xyz.0001.use2.cache.amazonaws.com:6379. A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. I have the following Django settings for the local redis: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } And this the Django settings for the remote redis instance: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://xyz.0001.use2.cache.amazonaws.com:6379', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } Again, when I switch from local to remote caches settings, I get that error above. I know that I it is not possible to connect ElastiCache outside AWS unless you have a vpn connection. So, I've set up the vpn client end point on aws and connected to it using the aws vpn client. I can successfully connect via vpn as shown below. Any idea why I still can't connect from my local machine to the remote redis … -
raise ValueError('Filename must be a string') ValueError: Filename must be a string when upload file to AWS S3 in Django
I have used Django to develop a web app. In the frontend, the user is supposed to upload an image by upload button to AWS S3. But I got the error at s3_client.upload_file: raise ValueError('Filename must be a string') ValueError: Filename must be a string view.py def save_pic(request): print("save_pic") if request.method == 'POST': image = request.FILES.get('image') print(image) img_name = image.name ext = os.path.splitext(img_name)[1] img_path = os.path.join(settings.IMG_UPLOAD, img_name) with open(img_path, 'ab') as fp: for chunk in image.chunks(): fp.write(chunk) import boto3 from botocore.exceptions import ClientError s3_client = boto3.client('s3', aws_access_key_id='XXX', aws_secret_access_key='XXX', region_name='XXX') try: with open(img_path, 'rb') as fp: response = s3_client.upload_file(fp, 'etp-tms', 'image_0.jpg') except ClientError as e: print(e) try: data = {'state': 1} except: data = {'state': 0} return JsonResponse(data) return JsonResponse(data="fail", safe=False) HTML: function renderCover(value, row) { return '<input id="image-input" accept="image/*" type="file" />\n' + '<img id="image-img" /> ' } function upload() { //alert("upload"); var formdata = new FormData(); formdata.append("image", $("#image-input")[0].files[0]); formdata.append("csrfmiddlewaretoken",$("[name='csrfmiddlewaretoken']").val()); $.ajax({ processData:false, contentType:false, url:'/save_pic/', type:'post', data:formdata, dataType:"json", success:function (arg) { if (arg.state == 1){ alert('success') }else { alert('fail') } },error: function () { alert("error") } }) } when I upload the img, the error occurs at response = s3_client.upload_file(fp, 'etp-tms', 'image_0.jpg').: raise ValueError('Filename must be a string') ValueError: Filename must be … -
putting fields labels in django table in first row
I want to: print the label in the first row set with of each field to 45px put the first column where C will enumerate 1,2,3,... according to the rows. it should be something like this: V x1 x2 direct RHS C1 field field field field C2 field field field field C3 field field field field in the body of page.html: <table> {% for form in formset %} <tr> {{ form.label }} {% for item in form %} <td style="width:10px; text-align: center">{{ item }}</td> {% if not item.label_tag = 'direction' %} ...do something... {% endif %} {% endfor %} </tr> {% endfor %} </table> in forms.py: class linprog_vars(forms.Form): x1 = forms.FloatField(label='x1') x2 = forms.FloatField(label='x2') direct = forms.CharField(label='direct') rhs = forms.FloatField(label='rhs') En views.py def linprog(request): extra_lines = 3 formset = formset_factory(linprog_vars, extra=extra_lines) context = {'formset': formset} return render(request, 'linprog/linprog.html', context) -
Django Models Data is not shown in Bootstrap Modal
I have faced a problem to pass the model data to Bootstrap modal. The information is not displayed in Bootstrap modal but when I try to pass data to a normal template, the information is shown. Can you guys please help me to find out where is the problem. I will be very appreciated for your help! Here is the code. catalog.html <div class="row"> {% for getdata in furniture %} <div class="col-md-4"> <a class="" href="{{ getdata.update_view_count_url }}" data-toggle="modal" data-target="#product_modal"> <div class="card text-center mb-5"> <img src="{{baseUrl}}/{{getdata.furnitureImg}}" alt="" class="card-img-top mt-3 px-2"> <div class="card-body"> <h3 class="card__fName text-uppercase">{{getdata.furnitureName}}</h3> <h2 class="card__fPrice">${{getdata.unitPrice}}</h2> <a href="{{ getdata.add_to_cart_url }}" class="card__button text-uppercase"> <i class="uil uil-shopping-cart"></i> Add To Cart </a> </div> </div> </a> </div> {% endfor %} {% include 'user/product.html' %} </div> models.py def update_view_count_url(self): return reverse("ecommerce:view", kwargs={ 'slug': self.slug }) urls.py from django.urls import path from . import views from . import recommendation from .views import ItemDetailView, CartDetailView, OrderSummaryView app_name = 'ecommerce' urlpatterns = [ path('view/<slug>/', views.updateViewToItem, name='view'), path('product/<slug>/', ItemDetailView.as_view(), name='product'), ] views.py class ItemDetailView(DetailView): model = Furniture template_name = "user/product.html" # View the item after clicking def updateViewToItem(request, slug): item = get_object_or_404(Furniture, slug=slug) viewed_item = User_Views.objects.filter(userId=request.user, furnitureId=item) if viewed_item.exists(): get_viewed_item = User_Views.objects.get(userId=request.user, furnitureId=item) get_viewed_item.viewCount += 1 get_viewed_item.save() else: view … -
Why can't I get Axios to set CSRF token headers?
I have an HTTP only cookie that was set by Django for session based authentication. When I try to make a POST request in my Next.Js app I get detail: "CSRF Failed: CSRF token missing or incorrect.". I know I need the X-CSRFToken header but Axios won't set it for me. The cookies are being sent in the request just not as a header. My post request looks like: axios .post(`${process.env.NEXT_PUBLIC_API_URL}/shops`, createShopFormData, { xsrfHeaderName: 'X-CSRFToken', xsrfCookieName: 'csrftoken', withCredentials: true, }) .then((response: AxiosResponse) => { console.log(response); }) .catch((error: AxiosError) => { console.log(error.response?.data.message); }); }; -
Django and nginx: How to add url prefix to all the django urls
I have the following nginx config: I am running two servers Nodejs(port:3000) and django(port:8000) http { server { listen 80; server_name localhost; location / { proxy_pass http://127.0.0.1:3000; <-- NODEJS APP } location /api { proxy_pass http://127.0.0.1:8000; <-- DJANGO APP } } } I want to access Django at {domain_name}/api and anything other than that will be fetched from Nodejs I want to access all the /admin and whatever urls mentioned in the Django at /api Is there any way to do that. I know i can add /api infornt of all the urls in the urls.py. But this can be dynamic. So I dont want to disturb the urls.