Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What are the implications of making SECRET_KEY public? [on hold]
I know the SECRET_KEY for a website made in Django. The owner of the site has accidentally made the settings.py public. How can this be exploited by malicious people? And how do I make the owner aware that this is a serious issue, without being persecuted? From Django's official documentation: The secret key is used for: All sessions if you are using any other session backend than django.contrib.sessions.backends.cache, or are using the default get_session_auth_hash(). All messages if you are using CookieStorage or FallbackStorage. All PasswordResetView tokens. Any usage of cryptographic signing, unless a different key is provided. -
nginx proxy causing error when response takes too long to reply
I have an nginx configuration that redirects to a Django rest service (Through gunicorn). Everything works correctly, but when the response is too big (takes more than 30s to respond) I'm getting a 503 service unavailable error. I am sure it is because of this issue because it works correctly on other requests, and only on specific requests where the response is too big (and fetching the request from a third party api) takes too long. Below is my nginx configuration : server { listen www.server.com:80; server_name www.server.com; client_max_body_size 200M; keepalive_timeout 300; location /server/ { proxy_pass http://127.0.0.1:8000/; proxy_connect_timeout 120s; proxy_read_timeout 300s; client_max_body_size 200M; } location / { root /var/www/html; index index.html index.htm; } } I am sure the issue is from Nginx and not gunicorn, because if i do a curl from inside the machine i get a response. Thanks, -
how to use variable data to use in template tag in Django template
In views.py file class home(TemplateView): template_name='article.html' def post(self,request): file_path = '/u/vinay/checking.py' args={'file_path':file_path} return render(request,self.template_name, args) In article.html file {% load static %} <a href="{% static '{{ file_path }}' %}" download ><button class="button button2">Download plan</button></a> But i'm getting no file as output from GUI. As i'm creating download link for that file in file_path location.So how do i render text from views to article.html -
How do you do multiple joins simultaneously in Django ORM?
Given a bunch of graphical maps, I need to query which maps a user has access to, either because he owns the map or because he has been granted 'membership' of it. There is a Map_desc (Map description) model, and for each object in Map_desc, potentially many Mapmembership objects. Because it will later be fed to ModelChoiceFields in templates, I need a single QuerySet that will return all the Map_desc objects that have related Mapmembership objects, plus all the Map_desc objects that have 'owner' set to the current user. It's a simple join, but surprisingly difficult to pull off in Django. models.py (simplified) class Map_desc(models.Model): owner = models.ForeignKey(User, null=False, on_delete=models.CASCADE) class Mapmember(models.Model): member = models.ForeignKey(User, null=False, on_delete=models.CASCADE) ofmap = models.ForeignKey(Map_desc, null=False, on_delete=models.CASCADE) What I tried first that didn't work (in semi-pseudo code): shared = Map_desc.objects.filter(id=mapmember_set.ofmap) then a second query to get the Maps owned: owned = Map_desc.objects.filter(owner=thisUser) and tying them together with accessiblemaps = chain(shared,owned) The problem is that because there are multiple Map_desc objects, mapmember_set is not actually available. It does work if you limit the query to just one Map_desc, using .first(), and this is what all the tutorials and SO questions I've found do. So I came … -
Django not properly cleaning out test database
Every time I run ./manage.py test and the tests run, the db.sqlite3 gets a little larger. This is concerning; anyone know what might cause this? The file is about 500mb right now, and growing. The test case file extends class UploadFiles(LiveServerTestCase): And is using chrome driver with selenium -
Python- Django Tasypie - How to implement polling for requests that take a lot of time
My Tastypie rest API has a function that takes a lot of time to complete. How can I implement a polling mechanism with the client so that the request doesn't time out. Can you provide me an example or point me to material that I can use. -
Bootstrap modal doesnt show with location.href
I want the Bootstrap modal to pop up first and I will get some data from it and with that data I want to go a href location. function callModal(curr){ var currele = curr.id; alert(currele); switch (currele){ case "add_resource": { $("#myModal").modal('show'); window.location.href="add/resource"; break; } } } <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2>Modal Example</h2> <!-- Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Modal Header</h4> </div> <div class="modal-body"> <p>Some text in the modal.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> <div> <a href="#" onClick= "callModal(this)" id = "add_resource" >add resouce</a><br> </div> </body> </html> The issue is : only the href is being called, not the modal If I remove the href call , then the modal is getting called fine, but together its not getting called. ** In the Code snippet , you can ignore the undefined href location error -
Python Django - Why does Django make 2 calls to the DB for one request
For the below code I noticed that the backend is makeing 2 calls to the DB. userApps = CustomerUserMapping.objects.filter(user=user).values_list('customer__applicationName', flat=True) This results in [07/Feb/2018 12:51:30] DEBUG [django.db.backends:90] (0.004) SELECT "core_customers"."applicationName" FROM "core_customer_user_mapping" INNER JOIN "core_customers" ON ("core_customer_user_mapping"."customer_id" = "core_customers"."customerId") WHERE "core_customer_user_mapping"."user_id" = 'xxx' ORDER BY "core_customer_user_mapping"."user_id" ASC, "core_customers"."customerName" ASC, "core_customers"."customerId" ASC LIMIT 21; args=('xxx',) [07/Feb/2018 12:51:30] DEBUG [django.db.backends:90] (0.000) SELECT "core_customers"."applicationName" FROM "core_customer_user_mapping" INNER JOIN "core_customers" ON ("core_customer_user_mapping"."customer_id" = "core_customers"."customerId") WHERE "core_customer_user_mapping"."user_id" = 'xxx' ORDER BY "core_customer_user_mapping"."user_id" ASC, "core_customers"."customerName" ASC, "core_customers"."customerId" ASC; args=('xxx',) Can anyone provide a explanation for this. Or tell me what I am doing wrong ? -
Convert String to JSON in python
I am receiving a response from a service in text format unfortunately I cannot ask them to send me in JSON format) below is the reponse: '{message: Successfully sent data for processing, execId: d03c96hg-4098-47b9-9e4b-3cb2c}' I want to either convert this to dict or json but I am unable to do so, as the string inside the '{ }' does not have single or double quotes. I have tried using json.loads(), json.dumps(), ast.literal() and also few other methods, but was not able to achieve the desired output. The output desired is: {'message': 'Successfully sent data for processing', 'execId' : 'd03c96hg-4098-47b9-9e4b-3cb2c' } -
How to convert JS date string into django datetime format?
I have a Bootstrap datepicker and on date selection I make an ajax call and send in the user selected date, I want to change the date of the object in the database, but I get this error from django: [u"'04/23/2018' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] How do I convert it to the specified format? This is my code: Template: $('#project_date').on('changeDate',function() { $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', data: { new_date: $('#project_date_input').val() }, success: function(data){ //do something } views.py def project_change_date(request, pk): data = dict() project = get_object_or_404(Project, pk=pk) project.end_date = request.GET.get('new_date') opp.save() -
Image not uploading in db django cbv
I am using class based views for a form but image is not uploading in db, not showing any errors. here is my models.py class ProductCreateModel(models.Model): user = models.ForeignKey('accounts.SellerProfileModel', related_name='product_seller', on_delete=models.CASCADE,editable=False) title = models.CharField(max_length=120) slug = models/.SlugField(max_length=255,unique=True,blank=True) description = models.TextField(max_length=250) orignal_price = models.DecimalField(decimal_places=2, max_digits=8) discount = models.DecimalField(decimal_places=2,max_digits=4) discount_price = models.DecimalField(decimal_places=2,max_digits=8) image1 = models.ImageField(upload_to=upload_image_path,blank=True,null=True) here is my forms.py from django import forms from .models import ProductCreateModel class ProductCreateForm(forms.ModelForm): class Meta: model = ProductCreateModel fields = '__all__' here is my views.py class ProductCreateView(views.LoginRequiredMixin,ActiveSellerOnlyMixin,generic.CreateView,): template_name = 'products/create_new_product.html' model = ProductCreateModel form_class = ProductCreateForm success_url = reverse_lazy('home') def form_valid(self, form): product = form.save(commit=False) user = get_current_user(self.request) image1 = form.cleaned_data['image1'] form.instance.user = request.user return super(ProductCreateView, self).form_valid(form) # product.save() Now the form is submitted successfully but image is empty. -
django rest framework autorization returns wrong status code
I am new to django. I have a project that mobiles can have interaction with server using a token. In settings.py I have: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'UPLOADED_FILES_USE_URL': False, 'DEFAULT_PAGINATION_CLASS': None, 'PAGE_SIZE': DEFAULT_PAGE_SIZE, # For views using PageNumberPagination } but when using postman I send a request with an invalid token, istead of 401 (unauthorized), 403 (forbidden) is returning. Is there anything special I can do to fix this? tnx -
Django: Proper way to display options to the user in this case
EDIT Why would you downvote this question? Is there any question on SO that answers this that would show i didn't try to find it or google has answer to it that I missed? Or this is not the proper place to ask such questions? This is a simple question asking for advice on how to display options keeping MY particular data structure in mind. Please mention the reason for downvote. ORIGINAL I am trying to make my first website. I am using Django for it. I need advice from you people regarding UI of a portion of my template. I have a doctor user who will have to choose his clinic timings. So he has to choose from 7 days of week. Each day will have three shifts(Morning, Afternoon, Evening). He may choose 1 or more days and then for each day he may choose 1 or more shifts and provide time for each shift. How should I go about making options available to him so that it is easier for him to choose days-shifts-time and at the same time not clutter the UI? One way is to display all 7 days then under each day display three shift … -
How to differentiate between two user who are using same logIn and SignUp form in django?
This is my user's models.py. class User(AbstractUser): is_company = models.BooleanField(default= False) REQUIRED_FIELDS = ['email'] class InternProfile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,related_name='intern_profile',primary_key=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): print('****', created) InternProfile.objects.get_or_create(user = instance) This is my Company's models.py. class CompanyProfile(models.Model): company = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,primary_key=True, related_name='company_profile') Now, I am using boolean field 'is_company'. If company will register to the site then value of 'is_company' will become True. So, how can achieve this using allauth? -
Should I use Celery for the task
I am doing a project which would be a terminal server monitor for the company. The website is for engineers within the company to search for terminal information and session information. Now I have almost finished it with PHP and Vue.js. But when I test it, there is a problem, because there is some large query in the database(like searching for total sessions), it would take about one minute when we open the URL(cause I would display the summary information when users open the URL, so it would not open until large query finished). Also, I would do the periodical query(check terminal server state every 30mins, if it fails, notifying the admins). So for these two tasks, it is a good fit to use Celery and Redis as a broker? I think if I use Celery, it would do the large query in the backend so it would not slow down the website, and Celery is also good for periodic query. Is it right? Also, Does anyone use Celery with PHP and PostgreSQL before? I find a link about Celery api for PHP, but I hardly see anyone using Celery with PHP, Should I change to Django? Thank you so … -
Django full text search: says unaccent does not exist
I am using Django 2.0 and postgresql 9.6 I have created and empty migration file in my app (articles) with the following content to add unaccent and trigram extensions # Generated by Django 2.0 on 2018-02-06 22:34 from django.db import migrations from django.contrib.postgres.operations import UnaccentExtension, TrigramExtension class Migration(migrations.Migration): dependencies = [ ('articles', '0012_auto_20180205_2234'), ] operations = [ UnaccentExtension(), TrigramExtension() ] Then i try to run the following query: from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector vector = SearchVector('title',config='unaccent', weight='A') + SearchVector('description',config='unaccent', weight='B') query = SearchQuery('india') Article.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.3).order_by('rank') ProgrammingError: text search configuration "unaccent" does not exist LINE 1: ...rticle"."qa_bool", ts_rank((setweight(to_tsvector('unaccent'... -
How to remove a field and set default value for a ModelForm in Django?
I have a ModelForm in my forms.py as follows: class ChoiceForm(forms.ModelForm): class Meta: model = Choice fields = ['choice_text', 'is_choice_correct'] labels = { 'choice_text': "", 'is_choice_correct': "" } widgets = { "choice_text": forms.Textarea(), "is_choice_correct": "", } Based on some conditions, I would like the is_correct_field, a boolean field to not display in the form and set default value for the field (because it is required) so that when I write form.save() in my views, there occurs no error. However, I don't want to hide the form field. To make it more clear, here's what I want to say. I submit the form with only choice_text in my form. The form does not contain the field is_choice_correct, either hidden or displayed. When I save the form with form.save(), I want the is_choice_correct to be True. -
Django: Redirect to different page if logged in in urls.py
I have this url: url(r'^signup/$', TemplateView.as_view(template_name='users/signup.html')), and I want the user to be redirected to a different url, if they try access this page and are already logged in. Is there anyway I can do this in the urls.py or will I have to write a view for it? -
Should my site be connecting to the websocket on *every* page, and not only on the pages requiring websockets?
I've implemented Django-Channels to use with a particular feature of the site--instant chat. The JS required as part of allowing channels is run on every page, and I'm wondering if this could potentially lead to any security holes. For example, here's the JS required by Channels. The socket connects and opens with every page, regardless of whether the user is using the chat feature or not. $(function () { // Correctly decide between ws:// and wss:// var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; var ws_path = ws_scheme + '://' + window.location.host + "/chat/stream/"; console.log("Connecting to " + ws_path); var socket = new ReconnectingWebSocket(ws_path); socket.onopen = function () { console.log("Connected to chat socket"); }; ... Is this acceptable? If not, how should I adjust? -
PostgreSql and Django How to store large data (6GB+) per entry or row
Recently, I'm working with one project (Django + PostgreSQL), I store record as normal text type after encode to base64. After awhile I came to realize that storing record that I store some record size is around 6GB which is over max-size of 1 GB in text of postgres. I try to search around and got some recommend of using BLOB in Postgres. I further research more in how to use it with sample ,but seem no answer. Anyone use to Experience it, really appreciate ? -
Accidental GET request before/after POST in Django + Ajax
I have made a simple Django + Ajax web app: The inline form in bootstrap has two controls: Input and a Button. When the user stops typing, the suggestions are shown and the user can select any one of them. After selecting and clicking on Search, it should show an alert with the "description". I get the alert only sometimes, but when I do, the url changes to: http://localhost:8000/?csrfmiddlewaretoken=CYTL3UgoNA8fcZQVZRftxsFEZk0wJHEt8je13lB02IhoGJmWS2GxrmILcwPgM9Bw Timelog: 08:32 - First try, gave no alert due to the output in the console 08:33 - Got the alert and the url changed in the browser How do I prevent the change in the url? And how to prevent the error: ConnectionAbortedError: [WinError 10053]? Python console output: [07/Feb/2018 08:32:49] "GET /boards/autocomplete/?q=Dummy HTTP/1.1" 200 27 [07/Feb/2018 08:32:52] "GET /boards/autocomplete/?q=Dummy%20Board HTTP/1.1" 200 27 [07/Feb/2018 08:32:52] "GET /?csrfmiddlewaretoken=iZ5IFGniIEiM78GqxYovvBHW9f0EvdbuOkqYF7IUXMrVBScrq9PzpvK3mrPoyF8x HTTP/1.1" 200 5385 [07/Feb/2018 08:32:53] "POST /boards/get-description/ HTTP/1.1" 200 15 Traceback (most recent call last): File "c:\users\90348325\python\Lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "c:\users\90348325\python\Lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "c:\users\90348325\python\Lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "c:\users\90348325\python\Lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "c:\users\90348325\python\Lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "c:\users\90348325\python\Lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "c:\users\90348325\python\Lib\socketserver.py", line … -
python remove ss from HH:MM:ss and display only HH:MM
I have an input string like this HH:MM:ss 01:22:00 I want to remove seconds (ss), so that it is only HH:MM 01:22 How can I achieve that in python ? -
How to handle already registered social user in frontend (django-rest-auth)?
I've been using django-rest-auth, which has been great for email signup flow. I've been trying to implement social login (via FB), and in the latest version, it seems if someone has already created an account via email, they just raise an error if that user tries to login via social. This comment is in the commit: # We have an account already signed up in a different flow + # with the same email address: raise an exception. + # This needs to be handled in the frontend. We can not just + # link up the accounts due to security constraints Couple of questions (posted this in the github issues as well): Why is this a security issue? Isn't the whole point of social authentication that you trust the OAuth provider (FB in this case)? Second, how is one supposed to handle this in the frontend? It's a common occurrence that people sign up for email first (often simply because a site or app adds social login later in the development cycle). It seems to me the only option this leaves me with is to tell the user "Sorry, you can only login with your email account." Or to … -
Can't I use images from lists in the same order?
Can't I use images from lists in the same order? I wrote in views.py import os import cv2 from pathlib import Path path1 = Path(__file__).parent path1 /= "../test1" path2 = Path(__file__).parent path2 /= "../test2" index_list =[] for i in path1.iterdir(): i = str(i) if i.split(".")[-1].lower() in {"jpeg", "jpg", "png"}: img = cv2.imread(i) if img is None: print("Couldn't open file %s" % i) else: index_list.append(img) index_list1 =[] for j in path2.iterdir(): j = str(j) if j.split(".")[-1].lower() in {"jpeg", "jpg", "png"}: img1 = cv2.imread(j) if img1 is None: print("Couldn't open file %s" % j) else: index_list1.append(img1) index = index_list[0] index1 = index_list1[0] In test1 & test2's folder,same images are in there.So I think index_list & index_list1 have same images in the same order.But when I access codes like index = index_list[0] & index1 = index_list1[0],index & index1 's variable have different images.I really cannot understand why such a thing happens.I wanna get same image in these 2 variable,so how can I fix this?What is wrong in my code? -
implementing Post/Redirect/Get pattern, Django Pagination Post method
Using django 2.0 When I click on the link to take me to page 2 of results it takes me to the original query page. Views.py def profile_advanced_show(request): q = filter() qlist = q count = q.count() paginator = Paginator(q, 5) page = request.GET.get('page') contacts = paginator.get_page(page) return render(request, 'saferdb/list.html', {'contacts': contacts}) class QueryView(ListView): template_name= 'saferdb/query.html' def post(self, request): return profile_advanced_show(request) URLS.py url(r'^$', views.index, name='index'), url(r'/(?P<page>\d+)/$', views.profile_advanced_show), url(r'^query/$', views.QueryView.as_view(), name='query'), I want my URLS.py to redirect everything that ends with /?page=2 to be handles by the profile_advanved_show method. I was trying to follow this response.