Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is Django-REST-framework stateless?
According to REST API principles: Stateless – Each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client. But django-rest-framework stores tokens in database (in authtoken_token table) and I delete a token to logout a user.If token is stored in server,is it really stateless? Or am I understanding it wrong? Thanks for answering! -
How can i host my django project on my computer and access it from anywhere in the world?
Is there any way to make my computer as a host for my django project and i can access my django project from anywhere in the world?3 -
How to display Instagram Profile Information in a Django Template
I have a model given below: class Listing(models.Model): account_name = models.ForeignKey(Account, on_delete=models.CASCADE, verbose_name='Account Name', null=True, blank=True) profile_username = models.CharField('Username', unique=True, max_length=200) class Meta: verbose_name = 'Listing' verbose_name_plural = 'Listings' def __str__(self): return self.profile_username profile_username is Instagram username. So the profile URL is like "https://www.instagram.com/cabinwellnessclinic/". What would be the steps to display the profile from the URL in a Django template? Any help would be much appreciated. -
I can't cut of image using "crop" of "pillow"
Question about django. Posted image from form was saved and cut it using "crop" of "pillow" then resize and save. the program was no problem in local, but it was not cuted as specified after deployed on vps (When I upload 5 images, the one or two images was not cuted as specified) . I just only deployed data of git. I don't understand the cause. Could you tell me, if you know the cause. Code print(int(x)) print(int(y)) print(int(w)) print(int(h)) pp = ImageTable.objects.filter(sort_id = st.sort_id) print(pp[count-1].image) im = Image.open('media/' + str(pp[count-1].image)) #'str(pp[count-1].image)' is for example like 'images/test.png' images path xx = int(x) + int(w) yy = int(y) + int(h) im = im.crop((int(x), int(y), int(xx), int(yy))) im.resize(size=(200, 200), resample=Image.BOX).save('media/' + str(pp[count-1].image)) I Tried About the code above. the code is looped by for function and upload five images. it upload different images for each loop because of count is plus 1 every loop. I confirmed x,y,w,h was as specified value by using print debug. Supplementary information I hardly changed, but I changed database to postgresql from db.sqlite3. Is this relevant. -
How to redirect a user to a different page if he's logging in for the first time after registration in django?
I have created a Getting Started page to which I have to send the users if they are logging in for the first time after registration. I also referred to this question but didn't understand anything If not I have to redirect them to the Home page. I have set the LOGIN_REDIRECT_URL to 'home' in settings.py I have not tried anything yet because I have no idea about how I should do it. Please assume a simple html for both the pages with an <h1> tag containing their respective names -
Posting form data with axios (Vuejs) to django forms.py and then to 3rd party service
As the subject reads above I'm trying to post the fields in a form. each field is bound with v-model and set in export default I can do a submit and then it does a post but when it hits Django it sends hardcoded data to the 3rd party service if I remove the hardcoded data in the payload the 3rd party service bombs out. but if I leave the hard coded data I get a response. views.py from django.views.generic import TemplateView from django.views.decorators.cache import never_cache from rest_framework import viewsets from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .forms import DjangoForm import requests # Serve Vue Application index_view = never_cache(TemplateView.as_view(template_name='index.html')) class TestRest(APIView): def get(self, reqeust, format=None): thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print("GET request received") return Response(thisdict) def post(self, request, format=None): print("POST request received") url = "http://localhost:8080/" payload = "{\r\n \"prefix\":\"thanks dude\",\r\n \"length\":\"100\",\r\n \"temperature\":\"0.7\",\r\n \"top_k\":\"40\"\r\n}" headers = { 'Content-Type': 'application/json' } response = requests.request("POST", url, headers=headers, data=payload) return Response(response.text, status=status.HTTP_200_OK) def store_doPost(request): if request.method == 'POST': doPost = doPost(request.POST) Django_Form = DjangoForm(request.POST, request.FILES) if Django_Form.is_valid(): required_document_form.save() forms.py from rest_framework import serializers from django.db import models from django … -
How to build a nested comment system in django without django-mptt or any other library?
I'm working a blog in django and want to build a nested comment system but I don't want to use any library to achieve it.i want to know how big companies like instagram build comment section in python . I feel like I'm only learning to use libraries not learning to code. -
required with a concept of django user authentication and permissions
i am designing a project on online registration of students for an educational institution. Now that institution is having several schools registered under it. The School has a school id code and school name. Now i want a generalised login system for the school where they have their school id code as their login id and a standard password trend like school_ind@institution and as a second level authentication a sms based otp. Now when the school logs in it can register students for the exam and while registering the school id shown in school choices of student is the only the school id with which login has been done and in list view only students of that particular school shows up. the school login shud have the crud right for that schools student. how to implement this . -
No Access to files in S3 from Centos7 website on EC2
First time using AWS S3 here. I've been trying to figure this out the entire week but I just can't get my Django + NGINX site to display both my CSS and uploaded images from S3. I'm probably missing something but I just don't know exactly. I've looked into this, this, and this but I'm still unable to get things running. I have a Bucket Policy and a CORS Config in my bucket maybe you can take a look. What I have so far: My site works fine only without any CSS or other static files like images CSS and image file URLs are correct. They all direct to my S3 bucket. Image uploading has no problem saving to S3 To test, accessing each CSS/image manually from the browser returns the standard AccessDenied page from S3 I have an IAM role with the AmazonS3FullAccess policy applied to my EC2 instance All public access is blocked in my bucket My Bucket Policy For testing purposes, I created a user with AmazonS3FullAccess along with the role. Not sure if that's necessary... { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": [ "arn:aws:iam::<NUMBERS>:role/<MYEC2ROLE>", "arn:aws:iam::<NUMBERS>:role/<MYUSER>", ] }, "Action": "s3:*", "Resource": [ "arn:aws:s3:::<MYBUCKET>", … -
Editing of django form with primary key fields
I have a django model form for which I allowed partial form save since its a long form. Now I want the user to come back and complete the form later. There is one hindrance however that my database cannot accept duplicate entries with same primary key. So should I remove primary key in my database to solve this or is there another way to make it possible? Suggestions please. -
Django + gunicorn + nginx + supervisor -> upstream request timeout
As I mentioned in the title we use Django + gunicorn + nginx + supervisor set for our API. We have the followings configurations: nginx: server { listen 9003 default_server; server_name localhost; client_max_body_size 20G; proxy_connect_timeout 300; proxy_send_timeout 300; proxy_read_timeout 300; send_timeout 300; client_body_timeout 300; location / { proxy_pass http://unix:/tmp/app.sock; proxy_set_header Host $host; proxy_connect_timeout 300; proxy_send_timeout 300; proxy_read_timeout 300; send_timeout 300; client_body_timeout 300; } } supervisor: [program:app-gunicorn] command = gunicorn --bind unix:/tmp/app.sock app.wsgi:application --workers 2 --timeout 300 --threads 100 stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 stderr_logfile=/dev/stderr stderr_logfile_maxbytes=0 When the request taking more than ~ 15 seconds I get: response: upstream request timeout status: 504 Gateway Timeout timings: Request Timing Blocked: 0 ms DNS Resolution: 0 ms Connecting: 0 ms TLS Setup: 0 ms Sending: 0 ms Waiting: 15.12 s Receiving: 0 ms I would like to increase the timeout limit but as I can see at my configuration it is already set up to 300s. Any ideas what could help me? Cheers! PS. Locally, Django is handling requests that take longer than 15 seconds, so it is not a Django issue. -
leading and trailing flower braces in python
there was some piece of code where leading and trailing flower braces. But I can't find it. read_file = False file_extension = None if not use_meta_driver: _, file_extension = os.path.splitext(name) (status_obj, conf_file_path) = get_config_file_path(name) if Status.is_vunet_status_success(status_obj) is False: LOGGER.error("Failed to find if the config file exists or not ") return (status_obj,None) # Check if we have cached entry if not CONFIGURATION_ENTRY.get(name, None): status_obj, mod_time = FileUtils.get_file_changed_time(conf_file_path) read_file = True else: # Check if the associated file has changed in between. status_obj, mod_time = FileUtils.get_file_changed_time(conf_file_path) if Status.is_vunet_status_success(status_obj) is False: LOGGER.error("Failed to get the last modified time of file %s", conf_file_path) # If file has changed, then we read it again if mod_time != LAST_MODIFIED_TIME.get(name, None): read_file = True if read_file: (status_obj, file_fp) = FileUtils.open_file(conf_file_path, "r") if Status.is_vunet_status_success(status_obj) is False: LOGGER.error("Failed to open config file %s", conf_file_path) return (status_obj, None) (status_obj, output_json_str) = FileUtils.read_data(file_fp) if Status.is_vunet_status_success(status_obj) is False: LOGGER.error("Failed to read config file %s", conf_file_path) FileUtils.close_file(file_fp) return (status_obj, None) status_obj = FileUtils.close_file(file_fp) # read the file # Note: We currently support only yml and json formats. if file_extension == ".yml": (status_obj, output_dict) = JsonUtils.convert_yaml_to_python_dict(output_json_str) else: (status_obj, output_dict) = JsonUtils.parse_json_data(output_json_str) if Status.is_vunet_status_success(status_obj) is False: LOGGER.error("Failed to parse configuration") return (status_obj, None) Can anyone … -
How do I keep my box element from distorting or getting out of shape when shown on different size browsers
I am new to this and I want to make a place to display products which I have successfully done however when it opens on a window that is not full screen it takes the shape of that window and distorts the product image etc how can I fix this <div class="row"> {% for product in products %} <div class="col-lg-4"> <img class="thumbnail" src="{{product.imageURL}}"> <div class="box-element product"> <p><light>{{product.name}}</light></p> <hr> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> <a class="btn btn-outline-success" href="#">View</a> <h4 style="display: inline-block; float: right"><light>${{product.price|floatformat:2}}</light></h4> </div> </div> {% endfor %} -
how to submit POST request to django using fetch in js and render a new template
I want to submit data using fetch and post as the method and after that use Django render template to return a new HTML page. Django receives the request but the user doesn't get the new HTML page! This the JS that I'm using fetch("/flightbuy", { method: 'POST',credentials: "same-origin", redirect: 'follow', headers: { "X-CSRFToken": csrftoken, } }) .then(response => { console.log(response) // HTTP 301 response }) .catch(function(err) { console.info(err + " url: " + url); }); And this is my views.py def flightbuy(request): print("received") return render(request, "index.html") how do I fix this? Thanks :) -
relation "weather_city" does not exist
When I push my django project to heroku I get "relation "weather_city" does not exist". weather is the name of the app and city is a model. models.py from django.db import models # Create your models here. class City(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Meta: verbose_name_plural = 'cities' -
How to do DB update in a single query in django when using an IF condition?
I have the following code - testcase = Table1.objects.filter(ID=id,serialno ='1234', condition='False').exists() if not testcase: c = Table1.objects.filter(ID=id,serialno ='1234').select_for_update().update(condition='True') Here, I am querying the same DB twice. Is there any way where I can do the filter exists and update in a single query? -
Implementing Many try statement for different models in Django
I have different models, but in my view, I want to create two try statement and reflect it in my template. Here's my code for easy understanding: Class summary (LoginRequiredMixin,View): Def get (self,*args,**kwargs): try: order=Homeorder.objects.get(user=self.request.user,ord=False) ord_men=Menorder.objects.get(user=self.request.user,ord=False) context={'object':ord, 'ord_men':ord_men} return render (self.request,'summary/summary.html',context) Except ObjectDoesNotExist: messages.error(self.request, "you've not yet order") return redirect ('/') And in my template, this is what I plan on doing {%for order in object.home_items.all %} {%for men_order in ord_men.men_items.all %} Is it possible?, Thanks -
I'm doing crud operations with vue js, axios and django restapi but i can't upload photo
I'm doing crud operations with vue js, axios and django restapi I can create an ad model. However, when I add a photo to the image of the Ad model, I'm getting an http 400 error. The interesting thing is that I created a separate model, serializer and view with only foreign key and image field and made the crud operations without any problems. I cannot create a model by uploading an image when the following list is available what could be the problem? ## Data ## profileData:{ image: null, title: "1q", description: "qqqq2qq", price: 200, square_meter: 200, number_of_rooms: 1, building_age: 1, floor: 0, number_of_floors: 2, number_of_bathrooms: 1, heating: 2, balcony_exists: false, using_status: 0, housing_shape: 2, status: 0, visibility: 0, frontal: [1], interior_feature: [1], exterior_feature: [1], locality: [1], transportation: [1], landscape: [1], suitable_for_disabled: [1] } method methods:{ advertiseCreate(){ return this.$store.dispatch('createAdvertiseDataActions',this.profileData) } } -
Django dynamic admin forms
I am having trouble with some django admin functionalities what I want to do is to have 2 fields in an admin page and I want to achieve this field_A field_B if field_A == "specific value": exclude = ("field_B",) else: fields = ("field_A","field_B") Please Help -
Data Toggle Information Passing
Hello I have django project where I list images and I want that if someone click on one image it gets bigger. It works that a new little window is appearing but because I am getting the image source via template tagging I was not able to pass the information to the window. I will post my template and hope that I was understandable. Thank you very much. html <div class="container"> <h1 style="text-align:center;">{{lecturer.lecturer}}</h1> <hr> {% for i in distribution%} <div class='img1'> <a data-toggle="modal" data-target="#exampleModalimg" href="#"> <img name="pic" src="{{ i.distribution.url }}"> --->I am clicking here </a> <p style="text-align:center;">{{i.lecture}} | {{i.semester}}</p> </div> {% endfor %} </div> <div class="modal fade" id="exampleModalimg" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-body"> <img name="pic" src="{{ i.distribution.url }}"> ---> but I could not pass i </div> </div> </div> </div> -
Django app's DB user failed authentication in AWS
Here is Django setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'rulings', 'USER': 'postgres', 'PASSWORD': '******', 'HOST': '', 'PORT': '', } } In AWS, when I run a server, an error message occurs. File "/home/app_admin/venv_ruling/lib64/python3.7/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: Peer authentication failed for user "postgres" How can I run the server with the user name of postgres?? When I use another user name it will run without a problem, but I want to use "postgres" as a user. -
How to collect a changing variable from a views.py function to the template without reloading in django
I am creating a chatbot using django and tflearn, I have to completed the code to some extent, i have been able to post data from the template to the views.py function ('home') using javascript, but the things is i can't collect the current output from the chatbot, it is always returning the first result not the current result, although in the console it print the actual result. This are my codes. Thank you views.py from django.shortcuts import render from django.http import JsonResponse, HttpResponse from .apps import chat # Create your views here. def home(request): result = request.POST.get("data") if result == None: result = 'hi' else: result = request.POST.get("data") print (str(result)) mycontent = chat(str(result)) context = {'mycontent':mycontent} print (mycontent) return render(request, 'alice/index.html', context ) index.html <div class="col-sm-3 col-sm-offset-4 frame"> <ul></ul> <div> <form method='POST' id ='post-form'> {% csrf_token %} <div class="msj-rta macro"> <div class="text text-r" style="background:whitesmoke !important" > <input class="mytext" id='data' name="next" placeholder="Type a message"/> </div> </div> <div style="padding:10px;"> <button id="button" type= 'submit' name="button" onclick="myFunction()">send</button> <script type="text/javascript"> function myFunction() { insertChat('me',document.getElementById("data").value, 0) insertChat('you', '{{mycontent}}', 0) } </script> </div> </form> </div> </div> </body> <script type='text/javascript' src="{% static 'js/main.js' %}"></script> </html> main.js var me = {}; me.avatar = "https://lh6.googleusercontent.com/-lr2nyjhhjXw/AAAAAAAAAAI/AAAAAAAARmE/MdtfUmC0M4s/photo.jpg?sz=48"; var you = {}; … -
Error: (1062, “Duplicate entry 'search-laft_cadaveres_cni_identificados' for key 'django_content_type_app_label_model_76bd3d3b_uniq'”)
if someone can do me a favor to help with this error, I would appreciate it very much, every time I run the command python manage.py migrate search to migrate my models I get this error although it performs well migrations to my database data: Error: (1062, "Duplicate entry 'search-laft_cadaveres_cni_identificados' for key 'django_content_type_app_label_model_76bd3d3b_uniq'") Thank you very much. -
Search results aren't printed in the website, only in the command line
so I added a new page to my website to search for 'people' items. The thing is, whenever I search for an item, the result shows in my command line but it's not printed in the website, the only thing that is are the tags but with the empty result, like this: Gender: Age: Eye color: Film: So the result of the query is not printed out. Why is this happening? This is my view: from django.shortcuts import render, HttpResponse from django.views.generic import ListView import requests def people(request): people = [] if request.method == 'POST': people_url = 'https://ghibliapi.herokuapp.com/people/' search_params = { 'people' : 'name', 'people' : 'gender', 'people' : 'age', 'people' : 'eye_color', 'q' : request.POST['search'] } r = requests.get(people_url, params=search_params) results = r.json() if len(results): for result in results: people_data = { 'Name' : result['name'], 'Gender': result['gender'], 'Age' : result['age'], 'Eye_Color' : result['eye_color'] } people.append(people_data) else: message = print("No results found") print(people) context = { 'people' : people } return render(request,'core/people.html', context) This is the html: {% load static %} <!DOCTYPE html> <html> <head> <title>Ghibli Studio | People</title> <link rel="stylesheet" href="{% static 'core/people.css' %}"> </head> <body> <div class=" header"> </div> <div class="wrap"> <form action='/people' method="POST"> {% csrf_token %} <div … -
Finished making a model in django, tested in the views and tried to save form data but didn't work
I tried making a model and a modelform and tested it in the views ... Source Code models.py class FileUploads(models.Model): FILE_TYPE_CHOICES = ( ('No file type selected ...', 'No file type selected ...'), ('Stylesheets', 'Stylesheets'), ('JavaScript', 'JavaScript'), ('Documents', 'Documents'), ('Images/Pictures', 'Images/Pictures'), ('Scripts', 'Scripts'), ) user = models.ForeignKey(Profile, on_delete=models.CASCADE, verbose_name="User Profile") file = models.FileField(upload_to='storage/files/', blank=False, null=False, validators=[ FileExtensionValidator([ # Image Files "tiff", "svg", "pdf", "raw", "webp", "gif", "heif", "heic", "psd", "ind", "indt", "indd", "png", "jpg", "jpeg", "jfif", "bmp", "dib", "pdf", "arw", "cr2", "nrw", "k25", "tif", "jfi", "jpe", "jif", "ai", "eps", "svgz" "jp2", "j2k", "jpf", "jpx", "jpm", "mj2" # Stylesheet Files "css", "less", "sass", "scss", # Scripts / JavaScript Files "py", "js", "ts", # Misc: (Microsoft Word) "docx", "txt", ]) ], verbose_name="File Path") file_name = models.CharField(max_length=50, default="File name needs to be provided!") file_type = models.CharField(max_length=25, choices=FILE_TYPE_CHOICES, default="no file type selected ...") created_at = models.DateTimeField(default=timezone.now) class Meta: verbose_name_plural = "File Uploads" views.py from django.shortcuts import render from .forms import FileUploadsForm from django.http import HttpResponseRedirect from user_profiles.models import Profile from django.contrib.auth.decorators import login_required @login_required def profile_view(request): user = request.user profile = Profile.objects.get(username=user) form = FileUploadsForm(request.POST or None, request.FILES or None, instance=profile) if request.method == "POST": if form.is_valid(): instance = form.save(commit=False) instance.person = request.user instance.comment_to …