Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset interpolation for a previous / next instance function
Writing a dry function that returns either previous or next instances of a given instance. This function return previous instances: def previous(instance): try: return Picture.objects.filter(id__lt=instance.id).first() except Picture.DoesNotExist: return instance I want to create an abstracted function which returns either the previous or the next instance using an additional gt_or_lt argument. The problem lies in interpolating that argument into the filter(id__gt_or_lt). def seek_instance(gt_or_lt, instance): try: return Picture.objects.filter(id__gt_or_lt=instance.id).first() except Picture.DoesNotExist: return instance I've tried: return Picture.objects.filter(id__gt_or_lt = instance.id).first() seek_instance("gt", instance) return Picture.objects.filter(id__f"{gt_or_lt}" = instance.id).first() seek_instance("gt", instance) return Picture.objects.filter(f"{gt_or_lt}" = instance.id).first() return Picture.objects.filter(gt_or_lt = instance.id).first() seek("id__gt", instance) All fail with their respective errors. -
Django authentication using windows credentials
I want to make my app who its made in Django + Rest framework and front-end in React to login automatically using the domain active directory. I searched on the internet but I don`t find a complete solution how to do it. From what I read over the internet I need to config the Apache server and in django back-end to use python-ldap or something like this. Can anyone have a link or something or a solution? Thanks and sorry for my english ! -
How to fix reverse proxy nginx with shiny-server
I cannot get my shiny app to render javascript with django through my nginx reverse proxy. For example, dynamic graphs will not display but the HTML and CSS sliders will. Do I have my nginx config set up correctly? I am trying to display my shiny applications that are served via shiny server in the srv/shiny-server directory. I have been following along with this tutorial http://pawamoy.github.io/2018/03/15/django-auth-server-for-shiny/#try-it-with-a-dockerized-project . I have changed the shny-server.conf to listen on port 8100. I was wondering if anyone had any ideas of how to get the shiny app rendering correctly ? Thanks! Nginx Settings: # declare your Django app upstream djangoapp_server { server localhost:8000; } # declare your Shiny app upstream shinyapp_server { server localhost:8100; } # required for WebSockets map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; server_name localhost; client_max_body_size 100M; # normal requests go to Django location / { proxy_pass http://djangoapp_server; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://djangoapp_server; break; } } # "shiny" requests go to Shiny location ~ /shiny/.+ { rewrite ^/shiny/(.*)$ /$1 break; proxy_pass http://shinyapp_server; proxy_redirect http://shinyapp_server/ $scheme://$host/shiny/; # required for WebSockets proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; … -
How to group related models on django admin page
I'm new in Python and Django and I try to use ready admin module to manage my data. Let's say my models are following: class Action(models.Model): name = models.CharField(max_length=200) class Protocol(models.Model): name = models.CharField(max_length=200) class ProtRun(models.Model): prot = models.ForeignKey(Protocol) action = models.ForeignKey(Action) next_action = models.ForeignKey(Action) First, how can I display these structures. Assuming I have two protocols: P1 and P2 and I need to display actions grouped by protocol, something like this: P1 action = A1 action = A2 action = A7 P2 action = A3 action = A1 Second, when ProtRun are being defined, how can I default action based on next_action from the previous record? For example, when user tries to define fourth action for protocol P1, then action should be defaulted to A7, how can I do this in python and django. Thanks ;) -
Django Bootstrap link won't open modal
When I tap the add new task button I want the modal to open, and it does in the original bootstrap file but not when I put it into django. <div class="col-auto"> <button class="btn btn-round" data-toggle="#modal" data-target="#task-add-modal"> <i class="material-icons">add</i> </button> </div> <form class="modal fade" id="task-add-modal" tabindex="-1" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">New Task</h5> <button type="button" class="close btn btn-round" data-dismiss="modal" aria-label="Close"> <i class="material-icons">close</i> </button> </div> <!--end of modal head--> -
how to use __str__ with foreign key '__str__ returned non-string (type Product)'
while i try to __str__() method for a foreign it provide this error __str__ returned non-string (type Product) models.py class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE , null=True) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) pass def __str__(self): return self.product i also tried this def __str__(self): return self.product.product_name #product_name is a field from Product table the error will provide is __str__ returned non-string (type QuerySet) how to represent it , thanks for reply ! -
I Want to store the form data to the database
I want store the form data into database ('subject_code' is the table name or model name) but when I press the submit button its throwing an error the error is TypeError at /subjectnamewithcode/ _wrapped_view() missing 1 required positional argument: 'request' please help me. this is my view.py from django.conf.urls import url, include from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import User from django.contrib.auth.decorators import login_required from django.views.generic import TemplateView from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. from .models import signupform, Universityname, facultyhours, subject_code, class_number def home(request): count=User.objects.count() return render(request, 'home.html', { 'count':count }) def subjectnamewithcode(request): subject_name=request.POST["subjectname"] subject_id=request.POST["subjectcode"] subjectnamewithcodedb=subject_code(subject_name = subject_name, subject_id = subject_id) subjectnamewithcodedb.save() return render(request, 'createtimetable/subjects_code.html') this is my model.py from django.db import models # Create your models here. class signupform(models.Model): usernamedb=models.CharField(max_length=250) passworddb=models.CharField(max_length=250) emaildb=models.CharField(max_length=250) class Universityname(models.Model): university_name=models.CharField(max_length=250) Department_name=models.CharField(max_length=250) Department_id=models.CharField(max_length=250) class facultyhours(models.Model): faculty_name=models.CharField(max_length=250) faculty_unique_name=models.CharField(max_length=250) faculty_total_hours_in_a_week=models.CharField(max_length=250) class subject_code(models.Model): subject_name=models.CharField(max_length=250) subject_id=models.CharField(max_length=250) class class_number(models.Model): class_name=models.CharField(max_length=250) class_number=models.CharField(max_length=250) this is my urls.py from django.contrib import admin from django.urls import path, include from mysite.core import views urlpatterns = [ path('', views.home, name='home'), path('signup/', views.signup, name='signup'), path('secret/',views.secret_page, name='secret' ), path('secret2/', views.SecretPage.as_view(), name='secret2'), path('accounts/', include('django.contrib.auth.urls')), path('University_names/', views.University_names, name='University_names'), path('universityNames_store_in_database/', views.universityNames_store_in_database, name='universityNames_store_in_database'), path('faculty_hours/', views.faculty_hours, name='faculty_hours'), path('map_faculty_with_hours/', views.map_faculty_with_hours, name='map_faculty_with_hours'), path('subject_code/', … -
Why am I getting this error (AttributeError: 'NoneType' object has no attribute 'split') while site is running very well?
I'm learning Django for the couple of months. At present I'm working on a demo project which is about teachers. After working some days I can't move for the limitation of my programming knowledge. Suddenly I discovered that there is an Error (AttributeError: 'NoneType' object has no attribute 'split') on the console but I can't figure out when it happened. Though my site is running very well with the development server but this problem is also running in the background. I'm using Django 2.2.4 python 3.6, and Postgresql 11.0 on Ubuntu 18.04. Can you guys please help me to get rid of this problem? Thanks in advance! I have searched on the web for the solution but could not find out any proper solution. Please guys check the error bellow. python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 04, 2019 - 16:28:55 Django version 2.2.4, using settings 'teacher_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [04/Sep/2019 16:31:05] "GET / HTTP/1.1" 200 6092 [04/Sep/2019 16:31:05] "GET /static/css/all_pass.css HTTP/1.1" 200 17 [04/Sep/2019 16:31:05] "GET /static/css/style.css HTTP/1.1" 200 12488 [04/Sep/2019 16:31:05] "GET /static/css/navbar.css HTTP/1.1" 200 567 [04/Sep/2019 16:31:05] … -
Django - inspectdb - the "models.FileField" are displayed as "models.CharField"
For some reason i want to check the Db as created with Django . I run command = python manage.py inspectdb > inspectdb.txt I get to see = models.CharField in place of the expected = models.FileField , whereas the models.py has the correct models.FileField also the Db surely has a models.FileField as am able to store Files = .csv , in this case correctly. My Question - Why would inspectdb , show the model field differently , how to learn more about this ? Linked Question - https://stackoverflow.com/a/48739612/4928635 -
DJANGO list indices must be integers or slices, not str
Views.py : def reserversalle(request , id): form= ReserverSalle(request.POST or None) object = models.authentifier.objects.get(id=id) allreservertion = models.Resasalle.objects.all() print(allreservertion) print(object) if form.is_valid(): for allreservertion in allreservertion: print(allreservertion) if(allreservertion.nomsalle == form.cleaned_data['nomsalle'] ) : print("nom des salles égaux") if( allreservertion.datedebut == form.cleaned_data['datedebut']) : print("meme date") if(allreservertion.heuredebut == form.changed_data['heuredebut']): print("meme heure début") return render(request,'registration/plan.html') print("gooddd") reserver = models.Resasalle() reserver.nomsalle = form.cleaned_data['nomsalle'] reserver.motifresa = form.cleaned_data['motifresa'] reserver.datedebut = form.cleaned_data['datedebut'] reserver.heuredebut = form.cleaned_data['heuredebut'] reserver.heurefin = form.cleaned_data['heurefin'] reserver.authentifier = object reserver.save() context= { 'form' : form , } return render(request,'registration/reserversalle.html', context) models.py : class authentifier(models.Model): matricule =models.CharField(max_length=254, blank=True, null=True) password = models.CharField(max_length=254, blank=True, null=True) nom =models.CharField(max_length=254, blank=True, null=True) prenom=models.CharField(max_length=254, blank=True, null=True) statut = models.CharField(max_length=254, blank=True, null=True) class Resasalle(models.Model): idrs = models.AutoField(primary_key=True) nomsalle = models.CharField(max_length=254, blank=True, null=True) motifresa = models.CharField(max_length=254, blank=True, null=True) datedebut = models.DateField(blank=True, null=True) heuredebut = models.TimeField(blank=True, null=True) heurefin = models.TimeField(blank=True, null=True) authentifier = models.ForeignKey(authentifier,on_delete=models.CASCADE , default="") forms.py : class ReserverSalle(forms.Form): nomsalle = forms.CharField(required=True , widget=forms.TextInput) motifresa = forms.CharField(required=True , widget=forms.TextInput) datedebut = forms.DateField( initial="2019-06-21", widget=forms.SelectDateWidget(years=YEARS)) heuredebut = forms.TimeField( initial='00:00:00') heurefin = forms.TimeField( initial='00:00:00') when i try to trigger the second condition : if(allreservertion.heuredebut == form.changed_data['heuredebut']): i resolves this error : list indices must be integers or slices, not str i need some help please and some solution -
How can I convert an entry using Django in a dictionnary?
I would like to convert this : a = User.objects.first() in a I precise there is three fields the id, the name of the users and the age. I would like instead of typing a.name typing a["name"]. Could you help me please ? Thank you ! -
Django get_field returns None
This is actually related to an earlier question I asked. I went through the traceback and Django's source code and I think I found out what's happening. Here's the traceback - File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 790, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 808, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1243, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1269, in _add_q allow_joins=allow_joins, split_subq=split_subq, File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1155, in build_filter value, lookups, used_joins = self.prepare_lookup_value(value, lookups, can_reuse, allow_joins) File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1005, in prepare_lookup_value value = value.resolve_expression(self, reuse=can_reuse, allow_joins=allow_joins) File "/usr/local/lib/python2.7/dist-packages/django/db/models/expressions.py", line 466, in resolve_expression return query.resolve_ref(self.name, allow_joins, reuse, summarize) File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1464, in resolve_ref self.get_initial_alias(), reuse) File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1405, in setup_joins names, opts, allow_many, fail_on_missing=True) File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1330, in names_to_path "Choices are: %s" % (name, ", ".join(available))) This is the piece of source code where Django fails - def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False): path, names_with_path = [], [] for pos, name in enumerate(names): cur_names_with_path = (name, []) if name == 'pk': name = opts.pk.name field = None try: field = opts.get_field(name) except FieldDoesNotExist: if name in self.annotation_select: field = self.annotation_select[name].output_field if … -
Single table vs Table per user
I am creating backend for a messaging application. I want it to be mostly a web app so would have to store the list of people with whom a user chats and all the messages in the server. However, I also wanted to have the ability to extend it and use the same backend for a mobile app. So I was thinking of having a separate database or table for every user and only open the connection to it when a user connects to the backend using WebSocket. However, according to this post, it seems that in most cases, it is better to have a single table and have many to one relation. So what would be the best choice in my usage? Also, how can I go about implementing that in Django? -
Django Dynamic filtering for ListView not working
Filtering ListView Hi, I am trying to follow the documentation but I just get a page not found using this system. This is what they say to do: # urls.py from django.urls import path from books.views import PublisherBookList urlpatterns = [ path('books/<publisher>/', PublisherBookList.as_view()), ] # views.py from django.shortcuts import get_object_or_404 from django.views.generic import ListView from books.models import Book, Publisher class PublisherBookList(ListView): template_name = 'books/books_by_publisher.html' def get_queryset(self): self.publisher = get_object_or_404(Publisher, name=self.kwargs['publisher']) return Book.objects.filter(publisher=self.publisher) And here is my version. url path('<area>', ProjectListView.as_view(), name='project-list'), views.py class ProjectListView(ListView): model = Project def get_queryset(self): self.area = get_object_or_404(Area, name=self.kwargs['area']) return Project.objects.filter(area=self.area) Model is commented out as it does not appear in the documentation version. I am using the template name that ListView gives. I can add models if necessary, but there is little different from the ones in the documentation. What am I doing wrong, or is the Documentation not accurate? -
How to perform completion query with django_elasticsearch_dsl
I'm trying to perform Completion with django-elasticsearch-dsl. So i created the following document: @registry.register_document class QuestionDocument(Document): name = fields.TextField( attr='title', fields={ 'suggest': fields.Completion(), } ) class Index: name = 'questions' class Django: model = QuestionModel fields = ['text', 'title'] And to perform completion with elasticsearch: matched_questions = list(QuestionDocument.search().suggest("suggestions", word, completion={'field': 'name.suggest'}).execute()) But the following exception occurs saying that no mapping exists for name.suggest: elasticsearch.exceptions.RequestError: RequestError(400, 'search_phase_execution_exception', 'no mapping found for field [name.suggest]') What am i doing wrong here? Is my approach correct or should i be doing this in a complete different way? -
Failing to run migrations: TypeError: expected str, bytes or os.PathLike object, not NoneType
I'm trying to run migrations inside the Django container but I get the following error when I run the commands i.e python manage.py makemigrations also migrate is not working. How do I resolve this? -
django KeyError on live, works on station with pycharm
Ok so, following code "talks" to the same restapi from live host and from pycharm editor on local venv. What is weird, follwoing code works from manage.py runserver launched by pycharm on local venv but does not work on live host with apache+django. views.py def host_tst_online(request): abc_hosts = Host.objects.all() tsthost = Host.objects.filter(abcenv='tst').order_by('abchostname') tsthostonline = [] arr = [] for xyz in tsthost: try: requests.get( 'https://{}:6666/abc/api/v1/about'.format(xyz), verify='/cert/cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxx'}, timeout=1 ) tsthostonline.append(xyz) except (ConnectionError, ConnectTimeout) as e: print(e) response = "No response" if request.method == 'POST': send_form = SendersFormO(request.POST) recv_form = ReceiversFormO(request.POST) if send_form.is_valid(): abcsend = send_form.cleaned_data.get('abcsend') send_form = SendersFormO() for eee in tsthostonline: response = requests.get( 'https://{}:6666/abc/api/v1/objects/abcsend?id={}'.format(eee, abcsend), verify='/cert/cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxx'}, ).json() for key in response['data']: arr.append(key) context = {'response': response, 'arr': arr, 'send_form': send_form, 'tsthostonline': tsthostonline} return render(request, 'app/json_nest_send_online.html', context) if recv_form.is_valid(): abcrecv = recv_form.cleaned_data.get('abcrecv') recv_form = ReceiversFormO() for eee in tsthostonline: response = requests.get( 'https://{}:6666/abc/api/v1/objects/abcrecv?id={}'.format(eee, abcrecv), verify='/cert/cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxx'}, ).json() for key in response['data']: arr.append(key) context = {'response': response, 'arr': arr, 'recv_form': recv_form, 'tsthostonline': tsthostonline} return render(request, 'app/json_nest_recv_online.html', context) else: send_form = SendersFormO() recv_form = ReceiversFormO() context = {'response': response, 'send_form': send_form, 'recv_form': recv_form, 'abc_hosts': abc_hosts, 'tsthost': tsthost} return … -
Scheduling django command with kubernetes cronjobs
I am trying to schedule a django command with kubernetes cronjobs my cron job yaml file looks like this: apiVersion: batch/v1beta1 kind: CronJob metadata: name: dostuff namespace: development spec: schedule: "*/1 * * * *" jobTemplate: spec: template: spec: containers: - name: dostuff image: "gcr.io/my_project/app:stg_onlycronimage" command: ["python /usr/src/app/manage.py dostuff"] env: - name: DATABASE_HOST value: 127.0.0.1 - name: DATABASE_USER valueFrom: secretKeyRef: name: literal-token key: user - name: DATABASE_PASSWORD valueFrom: secretKeyRef: name: literal-token key: password restartPolicy: OnFailure and my docker file looks like this: FROM python:3.7 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /usr/src/app WORKDIR /usr/src/app ADD requirements.txt /usr/src/app/requirements.txt RUN pip install -r requirements.txt ADD ./ /usr/src/app ENV PORT 8080 EXPOSE 8080 RUN rm -rf staticfiles RUN python ./manage.py collectstatic --noinput CMD gunicorn app.wsgi 0.0.0.0:8080 So basically I am using the same Dockerfile (Image) for my cron which I am using to run my application and the application is working fine. But when I am deploying my cron job by command kubectl apply -f cronjob.yaml cron does not work and container keeps on crashing. In the logs I see container_linux.go:247: starting container process caused "exec: \"python /usr/src/app/manage.py dostuff\": stat python /usr/src/app/manage.py dostuff: no such file or directory" I've tried changing to different basic … -
How to define phone number in forms and template error getting:django.template.exceptions.TemplateDoesNotExist: phone_field/phone_widget.html?
How to define phone number field in forms.py and template i tried but getting error:django.template.exceptions.TemplateDoesNotExist: phone_field/phone_widget.html models.py from phone_field import PhoneField phone = PhoneField(blank=True, help_text='Contact phone number') -
Django-admin executing, but no project is created in the virual directory
I have django and anaconda installed on a company system running comodo AV. upon running the command "django-admin startproject appone" it runs and no folders or app is created in the virtual environment. -
Django model inheritance: access to child object from parent queryset
I'm have some models in my django project like these: class Product(models.Model): name = models.Charfield(max_length=20) available = models.BooleanField(default=True) class Tea(Product): image = models.ImageField(upload_to='products/tea') class Coffee(Product): image = models.ImageField(upload_to='products/coffee') In my ListView I'm have queryset which get me 5 available products: Product.objects.filter(available=True)[:5] In my template I would like render image from Tea/Coffee, how i can access from Product queryset to Tea/Coffee child object? {% for product in products %} {{ product.????.image.url }} {% endfor %} -
How to send a file from Django to Gmail?
There is a feedback`` form in which the user can write atextmessage and attach thefile`. This form is sent to managers by mail (gmail, for example). Is there any way to make this file come to mail in its normal form (in a preview, for example) so that you can immediately see or download it? For now, I'm just sending a file link in the message. -
Why Celery tasks don't work asynchronously?
I am trying to run asynchronously basic debug_task from celery but it runs always synchronously. I have created a new project with django-cookiecutter template. I made sure that redis is working and all env variables are valid. I launch celery, and when it is ready to receive tasks, I launch the console (shell_plus) and invoke the task asynchronously. In [1]: from project.taskapp.celery import debug_task In [2]: debug_task.delay() Request: <Context: {'id': '87b4d96e-9708-4ab2-873e-0118b30f7a6b', 'retries': 0, 'is_eager': True, 'logfile': None, 'loglevel': 0, 'hostname': 'hostname', 'callbacks': None, 'errbacks': None, 'headers': None, 'delivery_info': {'is_eager': True}, 'args': (), 'called_directly': False, 'kwargs': {}}> Out[2]: <EagerResult: 87b4d96e-9708-4ab2-873e-0118b30f7a6b> As you can see param is_eager == True -> so it worked sync. Also I tried to call task as debug_task.apply_async() Here are setting from cookiecutter template for celery: import os from celery import Celery from django.apps import apps, AppConfig from django.conf import settings if not settings.configured: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') class CeleryAppConfig(AppConfig): name = 'project.taskapp' verbose_name = 'Celery Config' def ready(self): installed_apps = [app_config.name for app_config in apps.get_app_configs()] app.autodiscover_tasks(lambda: installed_apps, force=True) @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') -
Django Models: TypeError: tuple indices must be integers or slices, not str
My application is developed using Python3, Django and PostgreSQL. When I tried to execute the following query select * from rio_question where question similar to '%(General|ledger)%' and project_id =1 I'm getting the error TypeError: tuple indices must be integers or slices, not str I'm executing the query in following way. questions = Question.objects.raw(sql_query.format(query, projectId)) serializer = QuestionSerializer(list(questions), many=True) Any help in resolving following issue is highly appreciated. -
How it is possible to hide a field from a form based on the value of another field
I am trying to hide a boolean field(is_completed) from my form if another field(is_invoiced) is True, in other words when the check box is checked. my model looks like: class Woo_Orders(models.Model): is_invoiced = models.BooleanField("Invoiced?",default=False) is_completed = models.BooleanField("Completed?",default=False) Inside the form I guess I have to call the def clean_is_invoiced function something like the below snippet. def clean_is_invoiced(self): is_invoiced = self.cleaned_data['is_invoiced'] if is_invoiced==False: #hide the is_completed return is_invoiced But how can I hide the is_completed button?