Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - can not see subpages
Hi I have specific problem. I have the page. The page can be edited only by superuser. This page have subpages. Every single subpage have an owner - user who can edit his subpage. On the page I have menu - to display the subpages. {% show_menu 1 100 0 100 "menu.html" %} When i'm not login or login by superuser I see the menu - subpages. But when I'm login by usual user - owner of the one subpage I cant see the menu - so I can't go into my own page. How can I resolve this proble. Thank you for help. -
trying to make django pagination for sorted models
I am struggling with this for few weeks now, and I can't figure out a solution so please advice me. I have four models bound by a foreign key in this order: Faculty > Department > StudyProgramme > Courses. I created pagination and search for all of my courses. Now I want to set up pagination for courses that belong to a specific faculty. Example: Let's say my pagination is 1 course per page. In my faculties I have a total of 3 courses. Two of them belong to Informatics faculty and 1 of them belongs to Medicine faculty. Then pagination for Informatics faculty will have 2 pages of 1 course and pagination for Medicine faculty will have 1 page of 1 course. This is what I want to achieve. But I don't know how to make pagination depending on number of courses from each faculty. Please advice me, I'm really stuck here. def index(request): query_list = Course.objects.all() query = request.GET.get('q') if query: query_list = query_list.filter(Q(name__icontains=query)) paginator = Paginator(query_list, 1) page = request.GET.get('page') try: courses = paginator.page(page) except PageNotAnInteger: courses = paginator.page(1) except EmptyPage: courses = paginator.page(paginator.num_pages) for fac in Faculty.objects.all(): for dep in Department.objects.all(): if dep.faculty == fac: for … -
Receiving True boolean value for Django unit tests instead of False
I'm doing some unit tests for my Django database and I keep getting a True value instead of the False I expected to get because that entry isn't in my database: import requests from django.test import TestCase from convoapp.models import InputInfo class InputInfoTestCase(TestCase): def setUp(self): #valid entry InputInfo.objects.create(name="Skywalker", conversation_id='1', message_body='I am a Jedi, like my father before me') #invalid entry - missing 'name' field InputInfo.objects.create(conversation_id='4', message_body="No, I am your Father") #invalid entry - integer entered instead of string InputInfo.objects.create(name='Leia', conversation_id=3, message_body='You are a little short') def test_for_valid_entries(self): luke = InputInfo.objects.get(name='Skywalker') self.assertTrue(bool(luke), True) def test_for_invalid_entries(self): vader = InputInfo.objects.get(conversation_id='4') #invalid because of non-strong entry for conversation_id #leia = InputInfo.objects.get(name='Leia') self.assertFalse(bool(vader)) I get the error: Traceback (most recent call last): File "C:\Users\ELITEBOOK\documents\github\challenge\convoapp\tests.py", line 25, in test_for_invalid_entries self.assertFalse(bool(vader)) AssertionError: True is not false Why is vaderreturning True? I assume it's because of InputInfo.objects.create(conversation_id='4', message_body="No, I am your Father"), is it because the entry is temporarily created? Because after the test ends it's not in my database -
Django sending email and get the recipient email from html input field
I have a django method to send an email. currently the email recipient is hardcoded in the code, how can I create a dynamically where on submit a field from html page it will immediately get the recipient email and execute the method Html <input id="recipient_email" type="email"> view.py from django.core.mail import EmailMultiAlternatives def send_email(subject, text_content, html_content, to): to = 'test_to@gmail.com' from_email = 'test_from@gmail.com' subject = 'New Project Created' text_content = 'A Test' html_content = """ <h3 style="color: #0b9ac4>email received!</h3> """ email_body = html_content msg = EmailMultiAlternatives(subject, text_content, from_email, to) msg.attach_alternative(email_body, "text/html") msg.send() -
Django query which work faster "between" or __gte, __lte
I need to find data for one month so which query work faster "between" OR "__gte" and "__lte" ? -
How to have a Ajax timer that counts down and then runs a view function when it hits zero?
I have a view function like so: def myview(request): user = request.user duration = 5 context = { 'duration':duration, 'username':username, } return render(request,'template.html',context) And then I have a template Like so: <html> <head> </head> <body> <p><span id='counter'></span></p> <script> $(document).ready(function(){ duration = 5 while (duration > 0) { $('#counter').empty(); $('#counter').text('{{duration}}').delay(1000); duration = duration - 1; }else{ // run Django view function } ); </script> </body> </html> Is there a way I could have it to where a view function would run when duration hit zero and if so how would I do it. I know I would probably need AJAX, but I can't seem to see how to get it to work with Django. -
Django REST API : Create object from python file
I'm looking for developping Django REST API from my web application and I would like to try creating object through the API. Mainly if my process is well-implemented. I'm using a python file in order to make that. This is my file : import requests url = 'http://localhost:8000/Api/identification/create/' data = { "Etat": "Vivant", "Civilite": "Monsieur", "Nom": "creation", "Prenom": "via-api", "Sexe": "Masculin", "Statut": "Célibataire", "DateNaissance": "1991-11-23", "VilleNaissance": "STRASBOURG", "PaysNaissance": "FR", "Nationalite1": "FRANCAISE", "Nationalite2": "", "Profession": "Journaliste", "Adresse": "12, rue des fleurs", "Ville": "STRASBOURG", "Zip": 67000, "Pays": "FR", "Mail": "", "Telephone": "", "Image": "http://localhost:8000/media/pictures/HH_Hh_19212-00001-979812-2_ShUDIk8.jpg", "CarteIdentite": "http://localhost:8000/media/Carte_Identite/carte_ID_lzpOI41_WOnC9WH.gif" } response = requests.post(url, data=data) print (response.text) I'm confusing if I have to use post or put, but anyway, I don't overcome to create my object. If I make the process directly through the API, it works, but not with a pythonic file. Any idea ? -
what to learn next after learning python basics to get job
I have learned python basics and started django but whenever I see a job post it mention various skills such as AWS . I feel demotivated how much and what should I learn to get a job . so can any one gone through same situation can guide me -
Loading django user groups from json
Is there a way to initialize a django project with user-group permissions from json. I am looking for methods like python manage.py loaddata user_groups.json -
link to apidoc files into comments (django)
I have some experience with django, and I added apidoc into my project, and how you know apidoc can take a lot of place in the code, I mean when you write it into comments, and are there any ways to copy all apidoc codes into one file and then add all of them by some links, for example something like decorators? See code below for more information: @http.json_response() @http.requires_token() @esf.session_required() @http.required_session_params(['iin', 'tin']) @http.required_request_params(['invoice_draft_id']) @http.has_permission(CREATE_REGULAR) @http.check_company() @csrf_exempt def delete_invoice_draft(request): """ @api {post} /invoices/delete_invoice_draft/ delete invoice draft @apiName delete_invoice_draft @apiGroup Document @apiDescription Удаление invoice_draft @apiHeader {String} Auth-Token Auth-Token @apiParam {String} invoice_draft_id id документа @apiParam {String} is_failed "true" or "false" @apiSuccess {Json} result Json with code @apiSuccessExample {json} Success-Response:HTTP/1.1 200 OK { "code": 0 } """ if request.POST.get("is_failed", "false").lower() == "true": response = proxy.delete_failed_invoice(request.session["iin"], request.session["tin"], request.POST['invoice_draft_id']) else: response = proxy.delete_invoice_draft(request.session["iin"], request.session["tin"], request.POST['invoice_draft_id']) if response.status.code != pb.ResponseStatus.OK: return http.code_response(codes.SEND_ERROR, message=response.status.message) return http.ok_response() This is how it's look with apidoc code, and I want to do something like this: @http.json_response() @http.requires_token() @esf.session_required() @http.required_session_params(['iin', 'tin']) @http.required_request_params(['invoice_draft_id']) @http.has_permission(CREATE_REGULAR) @http.check_company() @csrf_exempt def delete_invoice_draft(request): """ @apidoc file links """ if request.POST.get("is_failed", "false").lower() == "true": response = proxy.delete_failed_invoice(request.session["iin"], request.session["tin"], request.POST['invoice_draft_id']) else: response = proxy.delete_invoice_draft(request.session["iin"], request.session["tin"], request.POST['invoice_draft_id']) if response.status.code != … -
pagination in Django not working as expected, need a special query
I have 4 models bound to each other by foreign keys. The order is: Faculty > Department > StudyProgramme > Courses. I created pagination and search for all of my courses and now I want to do the same, but only for the specific courses of a faculty. (e.g. Sugery belongs to Medicine faculty and not to Arts faculty). I want pagination for courses of each of my faculties. I don't know how to build the query like that. Please have a look: @login_required def index(request): query_list = Course.objects.all() query = request.GET.get('q') if query: query_list = query_list.filter(Q(name__icontains=query)) paginator = Paginator(query_list, 1) page = request.GET.get('page') try: courses = paginator.page(page) except PageNotAnInteger: courses = paginator.page(1) except EmptyPage: courses = paginator.page(paginator.num_pages) context = { 'courses': courses, 'courses2': Course.objects.all(), 'faculties': Faculty.objects.all(), 'departments': Department.objects.all(), 'studies': StudyProgramme.objects.all(), 'teachers': Teacher.objects.all() } return render(request, 'courses/index.html', context) {% for faculty in faculties %} <div id="fac_{{ faculty.pk }}_tab" style="display:none;"> <h3> {{ faculty.name }} courses</h3> <ul> {% for department in faculty.department_set.all %} {% for study in studies %} {% if study.department == department %} {% for course in courses2 %} {% if course.study_programme == study %} <li> <a class="first" href={{ course.slug }}>{{ course.name }}</a> </li> {% endif %} {% endfor %} … -
Django - Connect to Hive2 server
with a Django application am trying to connect to hive2 server as below: settings.py when "python manage.py inspectdb > webapp/models.py" is run to update models.py with classes for data objects of tables I get an error as below: django.core.exceptions.ImproperlyConfigured: 'django.db.backends.hive2' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' After going through the Django docs here I understand that only above database servers are supported by Django however would like to know if there is any way of accessing HIVE2 server in Django, I have a python standalone script which is able to connect to hive2 server and print results in shell as below, is there any way of coupling Django and this script so I can show my table to user in a front-end: dbconnect.py from impala.dbapi import connect import pandas as pd conn = connect(host='prd1-cluster-lb01', port=0001, auth_mechanism='PLAIN', user="xxxxxx", password="yyyyy") query = "select * from table1 limit 5" cur = conn.cursor() try: cur.execute(query) rows = cur.fetchmany(1000) for row in rows: print (row) -
Confused by middleware execution process, DJANGO
Suppose I have the following class, as inspired by the Django documentation: class SimpleMiddleware(object): def __ init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): return None When reading Daniel Rubio's book 'Beginning Django', he explains that the order of execution is: __ init __ method triggered (on server startup) __ call __ method triggered (on every request) If declared, process_view() method triggered View method starts with self.get_response(request) statement in __ call __ What exactly does "__ call __ method triggered (on every request)" mean? Does not 'triggering' the __ call __ method actually trigger 'self.get_respone(request)' automatically, thus calling either another middleware or a class? The Django documentation states that: process_view() is called just before Django calls the view.` To me, this would have to mean that Django checks if the instance of the 'SimpleMiddleware' class contains a method 'process_view()' and then triggers that, before moving on to calling the __ call __() method, which 'calls the view'? Otherwise, if the __ call __ method is triggered immediately, won't 'process_view()' be missed since the __ call __ method calls the view (or the next middleware)? Could someone please help me … -
How do I query the length of a Django ArrayField?
I have an ArrayField in a model, I'm trying to annotate the length of this field ( so far without any luck) F('field_name__len') won't work since join is not allowed inside F(). Even ModelName.objets.values('field_name__len') is not working Any idea? I'm using django 1.11 -
Getting csrfmiddleware token in url
I am getting csrf token in the url after submitting my form like this. http://127.0.0.1:8000/detail/?csrfmiddlewaretoken=lqvoeSG32IcodLTFksWEU1NPQ9XCmHybwmzMKEuPzxDN1e73B0JORpAGOcGGxsjH&symbol=FLWS After making a GET request to view, the url is showing the csrf token in the url. /views.py def search(request): if(request.method=='GET'): form=searchform(request.GET) if(form.is_valid()): id=request.GET['symbol'] data=company.objects.filter(Symbol=id) form=searchform() return render(request, 'list-company.html',{"data":data,"form":form}) /urls.py from django.contrib import admin from django.urls import path from csv2db.views import Company,search urlpatterns = [ path('admin/', admin.site.urls), path('company/',Company,name='company-details'), path('detail/',search,name='search') ] form in HTML file {% block content %} <form method="get" action="{% url 'search' %}"> {% csrf_token %} {{ form.as_ul}} <button type="Submit">Submit</button> </form> -
How can I delete specific song and also edit song info from my album list without using DeleteView in python Django ? Please help me
models.py This is my view file with Album and Song Classes. class Album(models.Model): artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=250) album_logo = models.FileField() def __str__(self): return self.album_title + '-' + self.artist class Song(models.Model): song = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length =10) song_title = models.CharField(max_length=250) #is_favorite = models.BooleanField(default=False) def __str__(self): return self.song_title views.py This is my views file for Deleting Song def delete_songs(request, album_id): if request.method == "GET": -
Creating a dynamic query system in django
I'm trying to create a query system in django, which will ask question to the user to narrow down a database to get a specific record based on the inputs. The problem I'm having is how to make it so that the question it is asking changes. Currently the database consists of chemicals, and the question are based on a set of properties that are already stored. For example, the system should ask "What is the solublity?" or "What is the boiling point?". Any help is appreciated. -
TypeError: "Unicode-objects must be encoded before hashing" error when using AWS signing Process for Python
I'm validating my AWS keys for S3 storage for my Django project. So I'm following the official walkthrough here. I've pasted the first part (Using GET with an Authorization Header (Python)) into my AWS conf.py file (which is imported into my settings.py). However the walkthrough is in Python 2.7 and my project is running off Python 3.5. Therefore I'm getting this error: payload_hash = hashlib.sha256('').hexdigest() TypeError: Unicode-objects must be encoded before hashing Any idea how I can fix this? -
Django with nginx connection error
I'm just making webserver with django. Now, I want to publish Django by uwsgi+Nginx, So I read some documents(http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html). While following that doc, I met some errors. When I connect to mydomain.com:8000, It throws 502 Bad Gateway error. (Actually, when I worked, changed mydomain.com to real domain that I have) After error, /var/log/nginx/error.log is in below. 2018/02/20 14:56:15 [error] 7548#7548: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.30.1.254, server: mydomain.com, request: "GET / HTTP/1.1", upstream: "uwsgi://127.0.0.1:8001", host: "mydomain.com:8000" ^C This is my configure files. [project_rest.conf] upstream django { # server unix:///path/to/your/mysite/mysite.sock; # for a file socket server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000 # the domain name it will serve for server_name .mydomain.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /home/app/project_rest/media; } location /static { alias /home/app/project_rest/static; } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/app/project_rest/uwsgi_params; # the uwsgi_params file you installed } … -
want to run multiple commands with single script
I am creating a single script for setup and running whole Django project. I mentioned three commands in script. which executed one on one.... commands subprocess.run(args=['nohup', 'airflow', 'scheduler']) subprocess.run(args=['nohup', 'airflow', 'webserver']) subprocess.run(args=['python', 'manage.py', 'runserver']) I used nohup for airflow webserver and scheduler to runs on background all three command runs one by one as per requirement but the problem is when airflow scheduler runs the script stops at point. is there any command or somthing i can used to run all the commands in single script with stop points -
Pip install non-conda package returns blank in anaconda prompt
I am trying to install a django package using the Anaconda prompt. As instructed by the documentations, I use "pip install (package-name)". However, every time I use pip install, it returns nothing ( blank on the next line). I've also tried "conda install (package-name)" and it could not find the package. If this is not the best method to install django packages with anaconda, could you suggest another way? Thanks! conda: 4.3.30-py35hec795fb_0 conda-env: 2.6.0-0 pip: 8.1.2-py35_0 conda environments : root -
Creating a Django user model with groups and group admins
I'm creating django website with users and groups... I'm trying to give users an option to leave a group...or A group admin can add and more so remove a user...Just like a WhatsApp group operates...How can one achieve this?? -
Python manage.py runserver running, but site cant be reached
I recently pushed a Django application into a docker container. I SSH'd into that container using docker run -it locally, and tried to run 'python manage.py runserver'. It shows the command is running Performing system checks... System check identified no issues (0 silenced). kdlkjFebruary 20, 2018 - 04:54:28 Django version 1.11.6, using settings 'settings.base' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But when I go to http://127.0.0.1:8000, it says the site can't be reached. -
Facing issues with HttpResponseRedirect in Django
I am creating a basic login functionality for the user.If the login is successful I am redirecting the user to my index page which I have hardcoded in HttpResponseRedirect. But once I click the login Button its saying, TypeError at /Login/ login() takes 1 positional argument but 2 were given index page in urls.py id defined as below, url(r'^$',views.index,name='index'), Below is the code for my index view and login view: def index(request): return render(request,'authentication_app/index.html') def login(request): if request.method=='POST': username=request.POST.get('name') password=request.POST.get('password') user = authenticate(username=username,password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect('/') else: return HttpResponse('Your Account has become Invalid') else: print('Someone tried to login with wrong credentials:{0},{1}'.format(username,password)) return HttpResponse('Username and Password mismatch.Please enter valid credentials') else: return render(request,'authentication_app/login.html',{}) -
Why i cannot start service web?
Help me with this error please. ERROR: for web Cannot start service web: driver failed programming external connectivity on endpoint semestral_dj01 (335d0ad4599512f3228b4ed0bd1bfed96f54af57cff4a553d88635f80ac2e26c): Bind for 0.0.0.0:8000 failed: port is already allocated ERROR: Encountered errors while bringing up the project.enter image description here