Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
On two related models, which one should contain the definition of the relationship?
First of all, yes: I've read Django's foreign key and many-to-many documentation, but I'm still not 100% clear on how to implement relationships on a practical level, especially regarding the hierarchy of the relationships. One-to-one I am aware of how to form one-to-one relationships. However, on a more conceptual level, which model should contain that reference to the other one? Let's say I have a Citizen, and a Passport. Now, it's obvious that one Citizen can only have a single Passport and viceversa, but, ideally, should the Citizen contain a field referencing his Passport, or should the Passport model contain a reference to the Citizen it belongs to? Many-to-many For the sake of simplicity, let's say I have a Person model and a Trip model (Trip as in going out on a trip somewhere). Many Persons can participate in a single Trip. Or in other words: a Person can participate in many Trips and in any single Trip, a lot of Persons can participate. This looks a like a many-to-many relationship, but, again, ideally, which model should contain the definition for the relationship, the Person with a trips field or the Trip with a participants field? And why? Does it … -
supervisor.config giving ERROR [unix_http_server]: command not found
I am using supervisor in my django project. Here is my supervisor.config file looks like [unix_http_server] file=/tmp/supervisor.sock [supervisord] logfile=/tmp/supervisord.log logfile_maxbytes=50MB logfile_backups=10 loglevel=info pidfile=/tmp/supervisord.pid nodaemon=false minfds=1024 minprocs=200 [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///tmp/supervisor.sock [program:run_django] environment=DJANGO_SETTINGS_MODULE=%(ENV_DJANGO_SETTINGS_MODULE) command=/home/ubuntu/www/project-venv/bin/gunicorn project.wsgi:application -w 1 -b 127.0.0.1:8000 -t 300 --max-requests=100 directory=/home/ubuntu/www/project/ user=ubuntu stdout_logfile=/home/ubuntu/www/project/logs/django_stdout.log stderr_logfile=/home/ubuntu/www/project/logs/django_stderr.log autorestart=true redirect_stderr=true But I am getting the following error I try to deploy onto AWS EC2 instance through CodeDeploy [stderr]/opt/codedeploy-agent/deployment-root/f57f7cd1-e8f9-457e-8a00-ae66d494c068/d-SYX2MO8SP/deployment-archive/supervisor/default.conf: line 1: [unix_http_server]: command not found [stderr]/opt/codedeploy-agent/deployment-root/f57f7cd1-e8f9-457e-8a00-ae66d494c068/d-SYX2MO8SP/deployment-archive/supervisor/default.conf: line 3: [supervisord]: command not found [stderr]/opt/codedeploy-agent/deployment-root/f57f7cd1-e8f9-457e-8a00-ae66d494c068/d-SYX2MO8SP/deployment-archive/supervisor/default.conf: line 13: [rpcinterface:supervisor]: command not found [stderr]/opt/codedeploy-agent/deployment-root/f57f7cd1-e8f9-457e-8a00-ae66d494c068/d-SYX2MO8SP/deployment-archive/supervisor/default.conf: line 14: supervisor.rpcinterface_factory: command not found [stderr]/opt/codedeploy-agent/deployment-root/f57f7cd1-e8f9-457e-8a00-ae66d494c068/d-SYX2MO8SP/deployment-archive/supervisor/default.conf: line 16: [supervisorctl]: command not found [stderr]/opt/codedeploy-agent/deployment-root/f57f7cd1-e8f9-457e-8a00-ae66d494c068/d-SYX2MO8SP/deployment-archive/supervisor/default.conf: line 19: [program:run_django]: command not found [stderr]/opt/codedeploy-agent/deployment-root/f57f7cd1-e8f9-457e-8a00-ae66d494c068/d-SYX2MO8SP/deployment-archive/supervisor/default.conf: line 20: syntax error near unexpected token (' [stderr]/opt/codedeploy-agent/deployment-root/f57f7cd1-e8f9-457e-8a00-ae66d494c068/d-SYX2MO8SP/deployment-archive/supervisor/default.conf: line 20: environment=DJANGO_SETTINGS_MODULE=%(ENV_DJANGO_SETTINGS_MODULE)' What did I miss here? -
Is there a way to autocomplete a field respective to another field?
template.html <div class="form-group col-sm-12 col-md-12"> <label for="id_amount_in_figure">Amount in figure:</label> <input type="number" name="amount_in_figure" id="id_amount_in_figure"> </div> <div class="form-group col-sm-12 col-md-12"> <label for="id_amount_in_word">Amount in word:</label> <input type="text" name="amount_in_word" id="id_amount_in_word"> </div> This is my code to convert number to words using python. def figures_to_words(figure, join=True): units = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] ens = ['eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] tens = ['ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] hundreds = ['thousand', 'lakh', 'crore'] words = [] if figure == 0: return '' else: figureStr = str(figure) # 232194622 figureStrLen = len(figureStr) # 9 thouLen = figureStrLen - 3 # 6 thou = figureStr[0:thouLen] # 232194 groups = (thouLen+1)//2 # 3 thouStr = thou.zfill(groups*2) # 232194 for i in range(0,groups*2,2): a, b = int(thouStr[i]), int(thouStr[i+1]) # i=0 a=2 b=3 # i=1 a=2 b=1 g = groups-(i//2+1) # g=2 g=1 j = g if (a>1) and (g==j): words.append(tens[a-1]) if b>=1: words.append(units[b-1]) words.append(hundreds[g]) elif a==1 and g==j: if b>=1: words.append(ens[b-1]) else: words.append(tens[a-1]) words.append(hundreds[g]) else: if b>=1: words.append(units[b-1]) words.append(hundreds[g]) j -= 1 huns = figureStr[-3:] hunsStrLen = len(huns) gro = (hunsStrLen + 2) // 3 huns = huns.zfill(gro*3) if len(huns) <= 3: h, t, u = int(huns[0]), int(huns[1]), … -
Django: Adding an instance of object to all ForeignKey related models
I have model Chamber: class Chamber(models.Model): chamber_name = models.CharField(max_length=100) And related model ChamberProperty: class ChamberProperty(models.Model): chamber = models.ForeignKey(Chamber, on_delete=models.CASCADE) property_name = models.CharField(max_length=50) property_value = models.CharField(max_length=100, default=None) Right now a Chamber can have many ChamberProperty. The requirements were just changed to make it so that if a ChamberProperty is added to a Chamber, it gets added to all future Chamber instances as well, with an empty property_value (default=None), so that the next time the form for creating a new Chamber instance is loaded, all previous ChamberProperty.property_name are loaded in the form, and empty. Example forms: First time a Chamber instance is created: Chamber.chamber_name: Foo ChamberProperty.property_name: Bar ChamberProperty.property_value: Baz Second time a Chamber instance is created: Chamber.chamber_name: Qux ChamberProperty.property_name: Bar # Old property, retain the name ChamberProperty.property_value: None # Old property, value empty ChamberProperty.property_name: Quux # New property, added by a button ChamberProperty.property_value: 700 # New property, value filled with input box Third time a Chamber instance is created: Chamber.chamber_name: Corge ChamberProperty.property_name: Bar # Old property, retain the name ChamberProperty.property_value: None # Old property, value empty ChamberProperty.property_name: Quux # Old property, retain the name ChamberProperty.property_value: None # Old property, value empty ChamberProperty.property_name: Ouier # New property, added by a button ChamberProperty.property_value: Grault … -
Where does user-uploaded content go in my AWS S3 storage?
I've set up my AWS S3 storage for my Django project. My static folder in my S3 Bucket has all my static files. However where do the files which would usually go in media go? i.e files uploaded from users? -
Django rest-framework; show different content to authetificated and anonymous users
I try to implement rest_framework for Django 2. I have a URL that should show diffrent content for authentificated users. Anonymous users just will get a limited view, authentificated will see everything. In the documentation I can only methods that will deny everything, but not a if else clause. Basicly I try something like this: class StoryViewSet(viewsets.ModelViewSet): if IsAuthenticated == True: queryset = Story.objects.all() else: queryset = Story.objects.filter(story_is_save=True) serializer_class = StorySerializer Obviously IsAuthenticated is not a True/False statement i can query. Any ideas how I could do this easily? Thanks -
django customizing admin interface
i have added ADD SUPPORT USER button to django admin interface like this by overriding admin change_list template. when i click ADD USER it takes me to 127.0.0.1:8000/admin/auth/user/add . if i click ADD SUPPORT USER button it should take me to 127.0.0.1:8000/admin/auth/user/add_support_user rather than 127.0.0.1:8000/add_support_user. however i get error like this . how do i achieve this? URLS.PY url(r"^add_support_user/", AddSupportUserView.as_view(), name = 'support_user'), CHANGE_LIST.HTML {% extends "admin/change_list.html" %} {% block object-tools-items %} {{ block.super }} <li> <a href="/admin/auth/user/add_support_user/" class="grp-state-focus addlink">Add Support User</a> </li> {% endblock %} TREE templates ├── add_support_user.html ├── admin │ └── auth │ └── user │ └── change_list.html └── index.html -
Django reading pdf files content
I'm trying to find a plugin that reads text from PDF files. I found an old post about this issue and the answer was to use the following plugin : pdfminer pluggin However, this does not support python 3. Any suggestions ? -
Django 2.0: combine path and re_path got NoReverseMatch error
Using path in project's urls.py, and using re_path in app's urls.py, I got the NoReverseMatch error, my project's urls.py: from django.contrib import admin from django.urls import path, include, re_path urlpatterns = [ path('user/', include('user.urls', namespace='user')) ] My app's urls.py: urlpatterns = [ re_path('activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/', views.activate_account, name='activate'), ] I can't get the correct url, the error message: django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments '{'uidb64': b'Mjc', 'token': '4tv-d4250012f57297ad82a6'}' not found. 1 pattern(s) tried: ['user\\/activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/'] -
Django Form won't display errors
I am trying to diplay error messages for my registration page. But unfortunetly it does not work at all. When I submit, it just goes to the login page. Here is my register.hmtl {% load widget_tweaks %} <form method="post"> {% csrf_token %} {{ form.as_p }} <div style="margin-top: 1em;"> <button class="btn btn-success btn-sm" type="submit">Konto erstellen</button> <a style="margin-left: 1em;" href="{% url 'accounts:login' %}" id="cancel" name="cancel" class="btn btn-default">Zurück</button></a> </div> </form> </div> </div> {% endblock %} And this is my forms.py (RegistrationForm) class RegistrationForm(UserCreationForm): username = forms.CharField(max_length=30, required=True, widget=forms.TextInput( attrs={ 'class': 'form-control', 'type': 'text', 'name': 'username', 'autofocus': 'autofocus' } ) ) first_name = forms.CharField(max_length=30, required=False, widget=forms.TextInput( attrs={ 'class': 'form-control', 'type': 'text', 'name': 'first_name', } ) ) last_name = forms.CharField(max_length=30, required=False, widget=forms.TextInput( attrs={ 'class': 'form-control', 'type': 'text', 'name': 'last_name', } ) ) email = forms.EmailField(max_length=30, required=True, widget=forms.TextInput( attrs={ 'class': 'form-control', 'type': 'email', 'name': 'email', } ) ) password1 = forms.CharField(label=("Passwort*"), required=True, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'type': 'password', 'name': 'password1', } ) ) password2 = forms.CharField(label=("Passwort bestaetigen*"), required=True, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'type': 'password', 'name': 'password2', } ) ) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) def clean_username(self): existing = User.objects.filter(username__iexact=self.cleaned_data['username']) if existing.exists(): raise forms.ValidationError(("A user with that … -
Django user model username (unique=False)
I have seen many of the solution but none of it seems to be answering the question. My user model is using AbstractUser right now. Is there a way to make username(unique = False) Since i wanted to allow user to ba able to have duplication of same username, as the login im am using is by email address and password -
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