Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST framework smiple jwt add custom payload data and access it in route
I am generating a custom jwt token for authentication using RefreshToken.for_user(user) at the time of login and registration. I can access user using request.user in the API endpoint but I also want to add user type in the payload data, so that I can access the user_type field in the API endpoint. This is what I am doing. def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), class UserRegistrationView(APIView): def post(self, request, format=None): serializer.is_valid(raise_exception=True) token = get_tokens_for_user(user) return Response({ 'token':token }) Now at endpoint class FileDetail(APIView): permission_classes = (IsAuthenticated,) def get(self, request, pk): user = request.user user_type = request.user_type // this data I want to save in the payload and get here. so I want user_type and other data at API endpoint from jwt payload data -
Store image with mongoengine django
I am working on a project in which I have a Company template which contains a name, url and an image under a Mongoengine Document. I would like to know how to store the image in the MEDIA folder without having to store it in DB as with the django model that allows direct image upload only in the folder. Thanks to all I didn’t find any documentation on the mongoengine website or internet without storing it into db -
Django crontab ModuleNotFoundError: No module named 'fcntl'
I'm trying to run a cron job using django-crontab with Django REST framework. I followed all the setup steps described in the library on GitHub, but when I run this command: python manage.py crontab add I get the following error: ModuleNotFoundError: No module named 'fcntl' I'm working locally on Windows, but the project will be deployed to a Linux server. I heard that "The fcntl module is not available on Windows." My questions are: Should I run the project on a Linux docker container instead? Should I search for package similar to fcntl for Windows? Should I try with another cron job package instead of django-crontab? Does anyone have any suggestions? -
Django Rest Framework authentication class override request.user
in my django App I have created a custom Authentication class using rest_framework: from business.models import BusinessToken from rest_framework.authtoken.models import Token from rest_framework import authentication, exceptions class AuthenticationMixin(authentication.BaseAuthentication): def authenticate(self, request): raw_token = request.META.get('HTTP_AUTHORIZATION') if not raw_token: return None token_key = raw_token.replace("Token ", "") user_token = Token.objects.filter(key=token_key).first() if user_token is not None: user = user_token.user request.user = user return user, None business_token = BusinessToken.objects.filter(key=token_key).first() if business_token is not None: business = business_token.business request.business = business user = business.owner request.user = user return business, None raise exceptions.AuthenticationFailed('No such user or business') As you can see the class has to authenticate the user or the business based on the token pass from http request. If the user authenticate itself through the business token in the api view I have to access to request.user as the business.owner and request.business as the business, but request.user is set to business, it's override somewhere. -
Is there any way to host django project with xampp?
I was trying to deploy it on apache24 lounge I was wondering if it is passible -
TypeError at /dj-rest-auth/google/ string indices must be integers
I wanted to do social authentication using dj-rest-auth with google. But getting an error like this doesn't understand anything. I want the advice of the experienced. I tried after submitting the access token it will return me a key for authentication. But I can't get it because of the error! -
How can i include multiple Plotly graphs in a webpage?
i am trying to build an application that shows plots generated out of data in the db . I want to publish these in a grid in same webpage now can i do this Here is my views.py unique_m = df['metric'].unique() hlist = [] for m in unique_m: df2 = df.loc[df['metric'] == m] fig = px.line(df2, x="date", y="value", title=m, width=700, height=500) file = fig.write_html("Templates/plots/%s.html" % m ) hlist.append(file) context1 = {'plotly_div': hlist} return render(request, 'index.html', context1 ) Here is my index.html {% extends "base.html" %} {% block content %} <div> <!-- {% autoescape off %} --> <div style="margin: 0 auto; width:855px; height:500px;"> {% for x in plotly_div %} <div style="margin: 0 auto; width:855px height:500px;"> <iframe src="{{ plotly_div }}" style="border:none;" style="height:500px;width:800px;" seamless="seamless" scrolling="yes"></iframe> </div> {% endfor %} </div> </div>` <!-- {% endautoescape %}} --> {% endblock content %} -
Django Many to Many (through) with three tables and extra attributes
I have an already existing database with 3 tables: Person, Card, and Permission. A user may have access to multiple cards, of which only some is owned by the person. How would I get all cards that the person has access to with the ownership status? Due to how the system should work, it's essential that the DB fetch is done in a single query. It's as if the usage of some magic values (such as objects.<table_name>_set....) is necessary to get this working? Ideal target query (including the person table) would be: SELECT card.id, card.text, permissions.owner FROM person.id JOIN permissions ON person.id = permissions.person_id JOIN cards.id = permissions.card_id WHERE person.id = <some person id>; Example target result from the query fetching cards for user id=1: [ { "id": 123, "text": "some random text", "owner": false }, { "id": 682, "text": "more random text", "owner": true } ] I've also tried some other solutions in some other threads, but most of them either don't include the extra data from the through-table, or don't work as they seem to require an extra table (such as Many-to-many relationship between 3 tables in Django which will throw an error "relation personcardpermissions does not exist" … -
How to implement consumer for voice chat app on Django?
I am currently working on a voice chat app as a personal project and this app will be like Discord, where users can hop into a chat room and start talking to people in that room. I am only going to make it voice only for now (I will implement text messaging later). I have been looking at examples on Github and I am having a little trouble with how to make the Consumer. Here is what I have right now: import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class VoiceConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = "chat_%s" % self.room_name # join the room async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, closed_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): text_data_json = json.loads(text_data) # Ask about this, how to receive voice ? voice_message = text_data_json['message'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, {'type' : 'chat_message', 'message': voice_message} ) As you see, I am confused about the text_data_json['message'] part. This is based off an example I have seen where someone implements messages, but I want to implement voice only. What do I change about this to where I can implement voice only ? text_data_json = json.loads(text_data) # Ask about this, how to receive voice … -
Django - Error during inporting Excel csv file with Pandas
I am having error on this code which is for csv importing data into the database using Django. This is the error. Many thanks for your help MultiValueDictKeyError at /countyImportFromExcelPd/ 'countryList' #model.py ### For the list of the country class Country(models.Model): ### country_di = models.AutoField(primary_key=True) country_iso2 = models.CharField(verbose_name='Country ISO 2 codes', max_length=4, null=True, blank=False) country_iso3 = models.CharField(verbose_name='Country ISO 3 codes', max_length=4, null=True, blank=False) country_name_EN = models.CharField(verbose_name='English', max_length=256, null=True, blank=True) country_name_FR = models.CharField(verbose_name='Francais', max_length=256, null=True, blank=True) country_name_DE = models.CharField(verbose_name='Desch', max_length=256, null=True, blank=True) country_name_ES = models.CharField(verbose_name='Espagnol', max_length=256, null=True, blank=True) country_comment = models.CharField(verbose_name='Comments', max_length=1024, null=False, blank=True, help_text='Coments on the payment') country_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) #View.py def countyImportFromExcelPd(request): if request.method == 'POST' and request.FILES['countryList']: countryList = request.FILES['countryList'] fs = FileSystemStorage() filename = fs.save(countryList.name, countryList) uploaded_file_url = fs.url(filename) empexceldata = pd.read_excel(filename) dbframe = empexceldata for dbframe in dbframe.itertuples(): obj = Country.objects.create(country_iso2=dbframe.country_iso2, country_iso3=dbframe.country_iso3, country_name_EN=dbframe.country_name_EN, country_name_FR=dbframe.country_name_FR, country_name_DE=dbframe.country_name_DE, country_name_ES=dbframe.country_name_ES, country_comment=dbframe.country_comment ) obj.save() return render(request, 'students_management_app/country-import.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'country-import.html',{}) # url.py path('countyImportFromExcelPd/', views.countyImportFromExcelPd, name='county-import-ExcelPd'), -
TypeError: context must be a dict rather than str
I am newbie. I am currently learning django. I have a page with a meeting of goods: URLS.PY urlpatterns = [ path("productsHTML/<str:uuid>", productHTML, name = "productHTML"), path("productsHTML/", productsHTML, name = "productsHTML") ] VIEW.PY def productsHTML(request): all_products = {"products": Product.objects.all()} return render(request, "products.html",all_products) def productHTML(request, uuid): product = Product.objects.get(id = uuid) value = [product.name, product.category, product.marka, product.privod, product.loshad_sila, product.box_peredach, product.volume_dvigatel] values = {"values": value} return render(request, "product.html", uuid, values) PRODUCTS.HTML {% block content %} <h2>Продукты</h2> <hr> {%if products %} {% for product in products %} <p><b>Категоия: </b>{{ product.category}}</p> <p><b>Название: </b><a href="http://127.0.0.1:8000/productsHTML/{{ product.id }}">{{ product.name}}</a></p> <p><b>Цена: Бесплатно</p> <hr> {% endfor %} {% endif %} {% endblock %} PRODUCTS.HTML {% extends 'products.html' %} {% block title %}Продукт{% endblock %} {% block content %} {% if values %} {% for value in values %} <p><b>Категоия: </b>{{ value.category }}</p> <p><b>Название: </b>{{ value.name }}</p> <p><b>Марка: </b>{{ value.marka }}</p> <p><b>Привод: </b>{{ value.privod }}</p> <p><b>Лошадиные силы: </b>{{ value.loshad_sila }}</p> <p><b>Коробка передач: </b>{{ value.box_peredach }}</p> <p><b>Объём двигателя: </b>{{ value.volume_dvigatel }}</p> <p><b>Цена: Бесплатно</p> {% endfor %} <button>КУПИТЬ</button> {% endif %} {% endblock %} I need to click on the link contained in the product name to be redirected to the product page with the address http://127.0.0.1:8000/productsHTML/ product id. If needed, … -
installing chatterbot it raise spacy installation error in python- pip install chatterbot - not working
Ii have installed latest Redistributable Microsoft C++ and upgraded my pip but not resolved...anyone please give solution `pip install chatterbot` preshed/maps.cpp(181): fatal error C1083: Cannot open include file: 'longintrepr.h': No such file or directory **error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2 [end of output]** note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure Encountered error while trying to install package. preshed ` × pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─\> See above for output.` -
I am trying to upload a Image in django i am very new
TypeError at /admin/lessons/lesson/add/ expected str, bytes or os.PathLike object, not list Request Method:POSTRequest URL:http://127.0.0.1:8000/admin/lessons/lesson/add/Django Version:4.1.7Exception Type:TypeErrorException Value:expected str, bytes or os.PathLike object, not listException Location:/Users/mobyfashanu/opt/anaconda3/lib/python3.9/posixpath.py, line 375, in abspathRaised during:django.contrib.admin.options.add_viewPython Executable:/Users/mobyfashanu/Desktop/mobius/learning_manager/bin/pythonPython Version:3.9.12Python Path:['/Users/mobyfashanu/Desktop/mobius', '/Users/mobyfashanu/opt/anaconda3/lib/python39.zip', '/Users/mobyfashanu/opt/anaconda3/lib/python3.9', '/Users/mobyfashanu/opt/anaconda3/lib/python3.9/lib-dynload', '/Users/mobyfashanu/Desktop/mobius/learning_manager/lib/python3.9/site-packages']Server time:Sun, 05 Mar 2023 16:09:25 +0000 By the power of deduction i can tell the problem comes from these line of code but i am unsure def dic_path(instance, filename): return 'user_'+ str(instance.user.id)+'/'+filename class Lesson(models.Model): id = models.UUIDField(primary_key=True,editable=False,default=uuid.uuid4) photo = models.ImageField(upload_to=dic_path) name = models.CharField(max_length=200) desc = models.CharField(max_length=300)` -
The UnicodeDecodeError occurred while executing the runserver command
enter image description here What does the UnicodeDecodeError error mean and how to solve the problem? -
navbar not working in home page but it's working in all pages
i try to add navbar but my problem is the navbar not working in home page but it's working in all pages .. in home page i can press on button and open it but i can't close it , it's keep open , but in all pages it's work normally navbar.html : <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="{% url 'home' %}"><h2><big><i>Uni-Study</i></big></h2></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> </ul> <form id="search_form" action="{% url 'search' %}" method="GET" value="{{request.GET.q}}" class="form-inline"> <input id="search_box" type="text" name="q" placeholder=" Search For ... " style="color:black" class="form-control mr-sm-2"/> <input class="btn btn-outline-text-white my-2 my-sm-0" id="search_button" style="width: 100px;" type="submit" name="submit" value="Search"/> </form> </div> </nav> home.html : i did this in all pages and work perfect but in home page it's not work good <!-- navbar and search + buttons --> {% include 'website_primary_html_pages/navbar_search.html' %} -
Django override save method for resize image only works forn one function. Why is this happening?
I got those two functions in my Model but only the cover_photo one is working. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) profile_picture = models.ImageField(upload_to='users/profile_pictures', blank=True, null=True) cover_photo = models.ImageField(upload_to='users/cover_photos', blank=True, null=True) ... def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.profile_picture: img = Image.open(self.profile_picture.path) if img.height > 50 or img.width > 50: new_height = 100 new_width = int(new_height / img.height * img.width) img = img.resize((new_width, new_height)) img.save(self.profile_picture.path) def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.cover_photo: img = Image.open(self.cover_photo.path) if img.width > 100 or img.height > 100: new_width = 600 new_height = int(new_width / img.width * img.width) img = img.resize((new_height, new_width)) img.save(self.cover_photo.path) If i swap then, only the profile_picture works but the other one stops. Does any one have any idea why this happens? Is there a way to make both works. Thank you very much! -
I have 69 Heads in git. I don't see recent commits on reflog. How can I find recent commits?
My Problem in Git Bash is that the most recent version that I can find is Head@{0} and is 2 months old. When running recent commits the feed back stated that everything was up to date. Is there anywhere my recent commits might be? I looked into the history and cannot find commits that I made just last night. I had been trying git push to send my commits to Github but it did not work the last couple of times I tried. I pulled the file from Github and now my program is as it was 2 months ago. I have 69 Heads and cannot find any sha that contains new versions. I tried the Github desktop program and cannot find any recent commits there either. I did not have any branches going at the time. -
Django DRF on kubernetes and max concurrent requests tuning
I migrated a Django 4 DRF app running in a Docker container to kubernetes on OVH and I cannot figure out how to determine the max concurrent requests supported by a single replica (to later be able to increase that with more replicas/nodes) My configuration is the following 1 node : 16 core 3ghz / 60GB RAM Django / gunicorn gunicorn api.wsgi --workers=64 --timeout=900 --limit-request-line=0 --bind 0.0.0.0:8000 I first tried with a simple DRF function (no DB / no model / no serializer). Later it will database queries and a CPU demanding function. class BenchView(APIView): permission_classes = (AllowAny,) def get(self, request, format=None): return Response({"bench":"bench"},status=200) I would expect that with 16 cores, a such simple function and 64 workers I get the same response time for one request that for 64 requests launched in parallel but I get this kind of result using apache bench for example ab -n 64 -c 1 'https://server/api/bench/' 50% 96 66% 98 75% 99 80% 100 90% 103 95% 111 98% 120 99% 121 100% 121 (longest request) ab -n 64 -c 16 'https://server/api/bench/' 50% 127 66% 130 75% 133 80% 137 90% 141 95% 142 98% 145 99% 150 100% 150 (longest request) ab -n … -
javascript does not work in a Django crispy form
I want to create a client, with country, province, city selected based on 3 different models : class Country(models.Model): Country = models.CharField(max_length=100, unique=True) def __str__(self): return self.Country class Province(models.Model): province = models.CharField(max_length=100, unique=True) Country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='province', null=True) def __str__(self): return self.province class City(models.Model): city = models.CharField(max_length=100, unique=True) Province = models.ForeignKey(Province, on_delete=models.CASCADE, related_name='city', null=True) def __str__(self): return self.city When the user selects a country, province list is updated with country's province and same thing for cities. I create urls for that and code in my views.py: class GetProvincesView(View): def get(self, request, *args, **kwargs): country_id = request.GET.get('country_id') provinces = Province.objects.filter(Country_id=country_id) data = [{'id': province.id, 'name': province.province} for province in provinces] return JsonResponse(data, safe=False) class GetCitiesView(View): def get(self, request, *args, **kwargs): province_id = request.GET.get('province_id') cities = City.objects.filter(Province_id=province_id) data = [{'id': city.id, 'name': city.city} for city in cities] return JsonResponse(data, safe=False) My template is: <!DOCTYPE html> <html lang="fr"> {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h2>Ajouter un client</h2> <form method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Enregistrer</button> </form> {% endblock %} {% block scripts %} <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> $(document).ready(function() { console.log('Document ready'); // Code pour filtrer les provinces en fonction du pays … -
I was working on a project and get the error that : "(" was not closed and "{" was not closed even if I closed it
I was working on a project and get the error that : "(" was not closed and "{" was not closed even if I closed it from django.shortcuts import render from .models import * from django.http import JsonResponse # Create your views here. def get_hotel(request): try: hotel_objs=Hotel.objects.all() payload=[] for hotel_obj in hotel_objs: payload.append ({ 'hotel_name' : hotel obj.hotel_name, 'hotel_price' : hotel obj.hotel_price, 'hotel_description' : hotel obj.hotel_description 'banner_image' : banner obj.banner_image, }) return JsonResponse(payload, safe=False) except Exception as e: print(e) I am expecting that the error messagees that : "(" was not closed and "{" was not closed should not pop up -
Django Quiz App - Add timer efficiency for each question
I have create a quiz application on django. I have add timer for all question after submitting the quiz, timer will stopped and result will be displayed with total time but now I want to add timer for every question so that use can see there efficiency for particular question. Here is my view.py code- def home(request): if request.user.is_authenticated: if request.method == 'POST': questions=QuesModel.objects.filter(category=request.GET.get('id')) score=0 wrong=0 correct=0 total=0 for q in questions: total+=1 if q.ans == request.POST.get(q.question): score+=10 correct+=1 else: wrong+=1 percent = score/(total*10) *100 context = { 'score':score, 'time': request.POST.get('timer'), 'correct':correct, 'wrong':wrong, 'percent':percent, 'total':total } return render(request,'Quiz/result.html',context) else: questions=QuesModel.objects.filter(category=request.GET.get('id')) context = { 'questions':questions } return render(request,'Quiz/home.html',context) else: return redirect('login') Below is my template code ` {% extends 'Quiz/dependencies.html' %} {% block content %} {% load static %} <div class="container "> <h1><b> Welcome to Quiz</h1> <div align="right " id="displaytimer"><b>Timer: 0 seconds</b></div> <form method='post' action=''> {% csrf_token %} {% for q in questions%} <div class="form-group"> <label for="question">{{q.question}}</label> </div> <div class="form-check"> <div class="form-check"> <input class="form-check-input" type="radio" name="{{q.question }}" id="gridRadios1" value="option1"> <label class="form-check-label" for="gridRadios1"> {{q.op1}} </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="{{q.question}}" id="gridRadios2" value="option2"> <label class="form-check-label" for="gridRadios2"> {{q.op2}} </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="{{q.question}}" id="gridRadios1" value="option3"> <label class="form-check-label" for="gridRadios1"> {{q.op3}} … -
Django admin - building HTML page with 2,000 inlines is slow, while DB query is fast
Question in short: I have a model admin with tabular inlines. There are around 2,000 related records. Fetching them from the database takes only 1 ms, but then it takes 4-5 seconds to render them into an HTML page. What can I do to speed this up? Question in detail: I have the following (simplified) models: class Location(models.Model): name = models.CharField(max_length=128, unique=True) class Measurement(models.Model): decimal_settings = {'decimal_places': 1, 'max_digits': 8, 'null': True, 'blank': True, 'default': None} location = models.ForeignKey(Location, related_name='measurements', on_delete=models.CASCADE) day = models.DateField() # DB indexing is done using the unique_together with location temperature_avg = models.DecimalField(**decimal_settings) temperature_min = models.DecimalField(**decimal_settings) temperature_max = models.DecimalField(**decimal_settings) feels_like_temperature_avg = models.DecimalField(**decimal_settings) feels_like_temperature_min = models.DecimalField(**decimal_settings) feels_like_temperature_max = models.DecimalField(**decimal_settings) wind_speed = models.DecimalField(**decimal_settings) precipitation = models.DecimalField(**decimal_settings) precipitation_duration = models.DecimalField(**decimal_settings) class Meta: unique_together = ('day', 'location') I have created the following inlines on the Location admin: class MeasurementInline(TabularInline): model = Measurement fields = ('day', 'temperature_avg', 'temperature_min', 'temperature_max', 'feels_like_temperature_avg', 'feels_like_temperature_min', 'feels_like_temperature_max', 'wind_speed', 'precipitation', 'precipitation_duration') readonly_fields = fields extra = 0 show_change_link = False def has_add_permission(self, request, obj=None): return False When I open a Location in the admin panel, I get a nice-looking overview of all measurements. This takes however 4-5 seconds to load. I have installed Django Debug Toolbar to … -
I am getting this error " TypeError at /generate_pdf/10 expected str, bytes or os.PathLike object, not JpegImageFile"
I want to generate a pdf with content and uploaded images of each user uniquely in django but its throwing this error .This is the error message This is the code to generate pdf from django.shortcuts import render from django.http import HttpResponse , HttpResponseServerError from reportlab.pdfgen import canvas from reportlab.lib.units import inch from PIL import Image from io import BytesIO from django.core.files.base import ContentFile import tempfile import os def generate_pdf(request, pid): # Get the user object based on the user_id user = Reports.objects.get(id=pid) # Create a new PDF object response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = f'attachment; filename="{user.Title}.pdf"' # Create the PDF using ReportLab pdf = canvas.Canvas(response, pagesize=(8.5*inch, 11*inch)) # Open the uploaded image as an Image object try: image = Image.open(user.report_image) except Exception as e: print(f"Error opening image: {e}") return HttpResponseServerError("Error generating PDF") # Add the user's uploaded image to the PDF pdf.drawImage(image, 2*inch, 9.5*inch, width=3*inch, height=3*inch) # Add the user's content to the PDF pdf.setFont("Helvetica", 12) pdf.drawString(2*inch, 8*inch, user.Content) # Save the PDF and return it pdf.save() return response -
Django adds quotes in template to each TextField. How to get rid of them?
I have some TextFields in my MySQL Database, like: body = models.TextField(default = 'initial') When I call out it in my template doing this: <p class = "service_description"> {{ post.body }} </p> I get this: <p class = "service_description"> " This is the text from the database, but it is with 2 quotes and 2 spaces around itself. " </p> As you can see, it adds excess quotes around the text. I tried to add |safe to the post.body it doesn't help. I also tried to add {% autoescape off %} {{ post.body }} {% endautoescape %} it doesn't help as well. Please let me know, why do I get these excess quotes and how to remove them correctly without slicing? Thanks. -
How can I requiest API with Nginx, Vuejs in Public EC2 and Django in Private EC2
I have a question about infra setting with Nginx, Vuejs, Django. enter image description here This is Architecture. Nginx, Vuejs's dist/ in WS Django(Docker Container), Postgresql in Django Server and This is Nginx conf.d/default.conf That's all about Nginx configuration in default.conf. server { listen 80; server_name localhost; #access_log /var/log/nginx/host.access.log main; location / { root /usr/share/nginx/html; index index.html; } } And When I click button in UI, I expect the request to go to the Django server. axios.get(process.env.VUE_APP_BASE_API + 'app/test-action/', { headers: { 'Content-Type': 'application/json;charset=UTF-8-sig' }, } ).then(res => { var vm = this; console.log('ACCESS SUCCESS!!'); console.log('ACCESS RESPONSE::', res, typeof (res)); vm.message = res.data.message; }) .catch(function () { console.log('ACCESS FAILURE!!'); }); but, Nothing happened! I can get (failed)net::ERR_CONNECTION_TIMED_OUT response in Web Browser. how can I fix it? curl worked in Django Server. like curl [django_server_ip]:8000/app/test-action/?format=json also curl worked in WS. like curl [django_server_ip]:8000/app/test-action/?format=json I was able to get a response from server 2 above.