Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django multiple formsets mutltiple FKs
If I have the following models: class Test(models.Model): name = models.CharField() class Case(models.Model): test = models.ForeignKey(Test) name = models.CharField() I want to create the following: For however many Test instances, I need to show Case formsets that will save related to Test (only so that many cases' can be added at one time). So for example, if there are 2 Test's, I may have 2 Case's each. When hitting save, the Case's need to be saved related to the appropriate Test. I can generate the formsets fine, and also only render the correct amount of forms per Test instance, but I have no way of knowing what the value of "test" should be when it comes to validation of the formsets. I hope that makes sense. -
Django form should remain same after submit button clicked
i am making stopwords removal api with using django.when i submit user text input fairly getting output but text area not visible after getting output.my requirement is below output is displaying input should remain same. below code as u can see in image snapshots is the text area is invisible.so it shoul be visible views.py from django.shortcuts import render,redirect,HttpResponse from django.views.generic.edit import FormView from .forms import ReportForm from django.views import View import spacy import pdb nlp = spacy.load('en_core_web_sm') class stopwordsremoval(FormView): template_name = 'report.html' form_class = ReportForm def form_valid(self, form): document1 = ((form.cleaned_data.get('text'))) return redirect('report_details', document1) class ReportDetails(View): def get(self,request,document1): word_lemma = [] #pdb.set_trace() for word in (nlp(document1)): a = (word.is_stop, word.text) word_lemma.append(a) searchedData = (word_lemma) return render(request, 'report.html', {'naturallanguageprocessing': searchedData}) forms.py from django import forms class ReportForm(forms.Form): text = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 100})) report.html {% extends 'base.html' %} {% block content %} <h1>StopWordsRemoval</h1> <div> <form action = "" method = "post" > {% csrf_token %} {{ form.as_p}} <button type="submit">stopwordsremoval</button> </div> <div > <ul> <li>{{ naturallanguageprocessing }}</li> [![enter image description here][1]][1]</ul> <a href="{% url 'stopwordsremoval' %}" </a> <style> div { width: 1000px; border: 5px solid green; padding: 10px; margin: 10px; } </style> </div> </div> {% endblock %} [![this is the user … -
Changing and saving the data gives Integrity error
I get Integrity with the below defined model.It occurs when I make changes and save the data again from the django admin. The error is triggered by obj.save() . The error is as follows: Exception Type: IntegrityError at /admin/users/data/1/change/ Exception Value: UNIQUE constraint failed: users_data.id How can I make this right. class Data(models.Model): author = models.ForeignKey(User, null=True, editable=False, on_delete=models.CASCADE) address = models.CharField(max_length=300,blank=True,null=True,help_text=("enter the address")) contact = models.IntegerField(blank=True,null=True,help_text=("enter the contact")) username = models.CharField(max_length=100,blank=True,null=True,help_text=("enter the username")) password = models.CharField(max_length=100,blank=True,null=True,help_text=("enter the strong password")) creation_date = models.DateTimeField(editable=False,null=True) last_modified = models.DateTimeField(editable=False,null=True) def save(self,*args, **kwargs): if not self.creation_date: self.creation_date = timezone.now() self.last_modified = timezone.now() return super(Data, self).save(self,*args, **kwargs) def __str__(self): return (self.username) @receiver(post_save,sender=Data) def datasaver(sender, instance, **kwargs): address = instance.address contact = instance.contact username = instance.username user_password = instance.password class CustomAdmin(admin.ModelAdmin): search_fields = ('first_name', 'email', 'username', ) def save_model(self, request, obj, form, change): obj.author = request.user obj.password = '' obj.save() def get_queryset(self, request): qs = super(CustomAdmin, self).get_queryset(request) if request.user.is_superuser: return qs return qs.filter(author=request.user) -
Django overriden login_required to check if user.email is complete
This is my overridan login_required def my_login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_decorator = user_passes_test( lambda u: u.is_authenticated, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator Here is my function @my_login_required def user_profile(request): return render(request, 'user-profile.html') If user has continued with facebook I must redirect him to the complete_registration_page I don't take user's email because usually people on facebook are using some old email and it's not their active account so I don't take their email from FB, they must enter is manually , their address too, but how am i supposed to do that? -
how to convert sql query to django queryset?
i have two tables like categories and items in models items has foreign key of categories,here we have 4 categories and 12 items where each category has 3 items how to write a query set to get query set to get items with same category i know how to write Sql query (select * from category where category_id =1;). how to write it in d'jango query set. -
Django rest API vs Django views
I am building a project where I have 2 approaches to follow - Either I can create APIs for all operations and call them from my frontend which is in Angular. Or I can use normal Django views and template. Question: what is the best approach to follow and what is the performance impact of them? -
I've issue in setting up Django with Apache using mod_wsgi
I've tried so much and feels i'm stuck and not getting anywhere Apache is giving an error which is ModuleNotFoundError: No module named 'wearpretty.settings' I'm using python 3.6, Django2.1, apache2, libapache2-mod-wsgi-py3 Below are the files which are being used in this. wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ["DJANGO_SETTINGS_MODULE"] = "wearpretty.settings" application = get_wsgi_application() virtualhost.conf <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName lhwearpretty.com ServerAlias www.lhwearpretty.com DocumentRoot /var/www/myprojects/wearpretty/wearpretty/wearpretty <Directory /var/www/myprojects/wearpretty/wearpretty/wearpretty> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess lhwearpretty.com python-home=/var/www/myprojects/wearpretty/venv python-path=/var/www/myprojects/wearpretty WSGIProcessGroup lhwearpretty.com WSGIScriptAlias / /var/www/myprojects/wearpretty/wearpretty/wearpretty/wsgi.py Alias /static/ /var/www/myprojects/wearpretty/wearpretty/static/ <Directory /var/www/myprojects/wearpretty/wearpretty/static> Require all granted </Directory> </VirtualHost> -
Django CBV : create functions in the same class
I'm working on a new project based on Django Class Based View and I would like to get advices in order to factorize an important post function. I'm pretty new with this concept. My post function looks like this : def post(self, request, *args, **kwargs): form = self.form_class() query_document = None query_document_updated = None query_omcl = None query_document_count = None if "UpdateDocument" in request.POST: checkbox_id = request.POST['DocumentChoice'] checkbox_id_minus_1 = int(checkbox_id) - 1 query_document_updated = Document.objects.get(id=checkbox_id) OMCL_CODE = query_document_updated.omcl.code SRC_FILENAME = query_document_updated.src_filename FILENAME, file_extension = os.path.splitext(SRC_FILENAME) CATEGORY = query_document_updated.category if CATEGORY == "ANNUAL": CATEGORY = "ANNUAL_REPORT" # Get the new year selected by user year = self.request.POST.get('q1year') # Create the new document title updated by the new year new_document_title = f"{year}_{CATEGORY}_{OMCL_CODE}" + " - " + f"{SRC_FILENAME}" # Create the new document file updated by the new year new_document_file = "omcl_docs/" + f"{OMCL_CODE}" + "/" + \ f"{year}_{CATEGORY}_{OMCL_CODE}_{checkbox_id_minus_1}{file_extension}" context = { 'form': form, 'query_omcl' : query_omcl, 'query_document': query_document, 'query_document_updated': query_document_updated, 'query_document_count' : query_document_count } return render(request, self.template_name, context) I would like to create two new functions : new_document_title and new_document_file and call both functions in post How I can do that? Create both functions after post and pass variables in arguments … -
Uncaught TypeError: $.ajax is not a function L.TileLayer.BetterWMS function
Hello guys I'm trying to display an onclick popup for my wms but I get this error Uncaught TypeError: $.ajax is not a function. I followed the instructions and downloaded jquery-3.3.1.js from this site: http://jquery.com/%20download/#jquery and pasted it in my static folder together with L.TileLayer.BetterWMS.js wich is located at the same directory but I still cannot se the atributes of the line layer. This is my code: index.html {% extends 'workorders/base.html' %} {% block jumbotron2 %} <div class="jumbotron"> <h1>Navbar example</h1> <p class="lead">This example is a quick exercise to illustrate how the top-aligned navbar works. As you scroll, this navbar remains in its original position and moves with the rest of the page.</p> <a class="btn btn-lg btn-primary" href="../../components/navbar/" role="button">View navbar docs &raquo;</a> </div> {% endblock %} {% block content %} <!DOCTYPE html> <html> {% load static %} {% load leaflet_tags %} <head> {% leaflet_js %} {% leaflet_css %} <title>Map</title> <style type="text/css"> #gis {width: 100%;height:600px;} </style> <style type="text/css"> #map { width: 100%;height:600px; } </style> <link rel="stylesheet" type="text/css" href="{% static 'dist/leaflet-groupedlayercontrol/leaflet.groupedlayercontrol.min.css' %}"> <script type="text/javascript" src="{% static 'dist/leaflet.ajax.js' %}" > </script> <script type="text/javascript" src="{% static 'dist/leaflet-groupedlayercontrol/leaflet.groupedlayercontrol.min.js' %}" > </script> <script type="text/javascript" src="{% static 'L.TileLayer.BetterWMS.js' %}" > </script> </head> <body> <div id="map"></div> <script type="text/javascript" src="{% … -
get ids group by range django
I have: Model: id = PrimaryKey() value = IntegerField() I would like to get list of ids group by value range between 1-7 and 8-30 and >30. What would be the efficient way to do so? Or shall I write query for each range like: one= Model.objects.filter(value__gt=0,value__lte=7).values_list(id) two= Model.objects.filter(value__gt=7,value__lte=30).values_list(id) three= Model.objects.filter(value__gt=30).values_list(id) ... can I do so via aggregate Count? I want minimum database transactions. -
Serving media files on S3 for saleor
I have used saleor,django store and hosted it on google cloud, It is working fine. Now what I wanted to do is to host media files on S3 bucket. I have created a bucket and tried some tutorials but no success. I could not find any complete step by step guide for this. If anyone can help me with this problem it will be helpful. AWS_ACCESS_KEY_ID = os.environ.get('accessid') AWS_SECRET_ACCESS_KEY = os.environ.get('accesskey') AWS_STORAGE_BUCKET_NAME = os.environ.get('testbucket') I followed this guide for saleor S3 integration: https://saleor.readthedocs.io/en/latest/deployment/s3.html Now here is the situation I have created the bucket and have AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY and AWS_STORAGE_BUCKET_NAME Can someone guide me from here how to serve media files on S3 for saleor -
Wagtail raises ValidationError on page update
On publishing updates to an existing wagtail page it raises a ValidationError with the message below. ValidationError({'live_revision': ['page revision instance with id 33 does not exist.']}) All other actions such as drafting, submitting for moderation all work okay. Only publishing the page with new updates raises the ValidationError effectively limiting the ability to update existing pages. -
Django: FileField, missing content_type
If I read the docs correctly, then the FileField in Django does not know the content_type of the file: https://docs.djangoproject.com/en/2.1/ref/models/fields/ I would like to store files in a Django application, but I want to query the content_type: Examples: list all objects which have a file with content_type "application/pdf" list all objects which have a file with content_type "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" What is the most django-like way to handle this? -
How to make coding online judge? [on hold]
I am trying to make online coding judge to host coding competitions in our college using django, python, can any one tell me how to compile and run user input i.e source code of c,c++ languages by any apis or any other method? i have tried Hackerearth apis but they are not working using python 3, if any one know how to solve this problem kindly post your answer in comments. Thanks. -
send data of different content-type in HttpResponse
I am new to Django, I am trying to send data of different content-type in HttpResponse function of Django but i am getting the error. I want to send the date with an image in HttpResponse. -
Why does Django not find my Docker-env variables?
I'm trying to do Django-project named dockerplayground with different configurations via Django-configurations. The goal is to set the configuration trough environmental variable during docker-build command. For some reason the Django-project can't find the env-variable when I start the container and uses default-value instead. Here are my files, the Django-project is a skeleton with empty app-skaffold made with "python manage.py startapp example" command. Dockerfile: FROM python:3.6 RUN apt-get update && apt-get upgrade -y && apt-get autoremove && apt-get autoclean RUN apt-get install -y \ libffi-dev \ libssl-dev \ default-libmysqlclient-dev \ libxml2-dev \ libxslt-dev \ libjpeg-dev \ libfreetype6-dev \ zlib1g-dev \ net-tools \ vim RUN echo openssl version ARG DJANGO_CONF_ARG ENV DJANGO_CONFIGURATION=$DJANGO_CONF_ARG RUN pip install pip --upgrade #https://github.com/circus-tent/circus/issues/1056 RUN pip install 'tornado==4.5.3' RUN pip install gunicorn circus ADD requirements.txt / RUN pip install -r requirements.txt ADD . / EXPOSE 8000 RUN chmod +x /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"] entrypoint.sh #!/bin/bash python manage.py makemigrations python manage.py migrate exec circusd circus.ini --log-level debug exec "$@"; circus.ini [circus] check_delay = 5 [watcher:gunicorn] cmd = /usr/local/bin/gunicorn args = -b 0.0.0.0:8000 -w 2 dockerplayground.wsgi numprocesses = 1 autostart = true max_retry = -1 priority = 500 requirements.txt Django==2.0.7 django-configurations dockerplayground/wsgi.py import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dockerplayground.settings") os.environ.setdefault('DJANGO_CONFIGURATION', "Dev") from configurations.wsgi import … -
i want know rank in django queryset
I have a product list model and would like to know the ranking of a specific price of this model. sorted_product_list = Product.objects.all().order_by('-price') my_product = {'id': 10, 'price': 20000} django has RowNum class but it is not support for mysql i have only one idea that use enumerate for rank, element in enumerate(sorted_product_list): if element.id == my_product.id: my_product_rank = rank Is there any other solution? -
Django python manage.py runserver outputs Performing system checks... then exits without error code, with mysqlclient
I've been trying to solve database problems with Django for a while, I gave up on using mysqlclient because it just wouldn't install properly, but with mysql-connector-python another bug appeared as discussed here. When trying to solve the mysqlclient problems another issue was encountered as discussed here. Now I've downgraded to python 3.5.2, using Django 2.0.3.0, mysqlclient 1.3.12, and mysql version 8.0.12. Now I get no error code, when I try to use python manage.py runserver this is what comes back from the terminal: (venv) D:\Program\LiquidMarket>python manage.py runserver Performing system checks... (venv) D:\Program\LiquidMarket> No error code, it just stops, any ideas on what I can do to fix this? -
How can I retrieve data from Django database and render it into HTML templates
I've working on a leave managing system. Where there's a Boolean field in the form, that acts as a select button in the admin panel. This is sign of approving or denying the leave for an employee. A string "Approved" / "Denied" should be shown in the html based on the Boolean field status. Now how do I work on this. Please look at my models.py, views.py and forms.py models.py from django.db import models from django.contrib.auth.models import User CHOICES = (('1','Earned Leave'),('2','Casual Leave'),('3','Sick Leave'),('4','Paid Leave')) class Leave(models.Model): name = models.CharField(max_length = 50) user = models.ForeignKey(User, on_delete = models.CASCADE, null =True) employee_ID = models.CharField(max_length = 20) department = models.CharField(max_length = 15) designation = models.CharField(max_length = 15) type_of_leave = models.CharField(max_length = 15, choices = CHOICES, default = None) from_date = models.DateField(help_text = 'mm/dd/yy') to_date = models.DateField(help_text = 'mm/dd/yy') reporting_manager = models.CharField(max_length = 50, default = None) reason = models.CharField(max_length= 180) accepted = models.BooleanField(('approval status'), default= False) def __str__(self): return self.name views.py from django.shortcuts import render from django.http import HttpResponse from .forms import LeaveRequestForm from django.views.generic import TemplateView from .models import Leave def leaveRequest(request): form_class = LeaveRequestForm if request.method == "POST": form = LeaveRequestForm(request.POST) if form.is_valid(): leave = form.save(commit = False) leave.user = … -
Django model will auto index pk and unique_together, how can I cancel it?
As far as I know, Django will auto index the "pk" and "unique" field... But Now, My Django version is 1.8, and I want to use brin index. but I can't find any way to migrate let my all index remove, then I can custom index by myself. thanks. -
Celery is not working as daemon
I am trying to use django and celery to automate the task and want to run celery as daemon. I copied the code for celeryd and celerybeat from its official documentation and put it inside the /etc/init.d/ folder. Below is the code of my celeryd file and I put it inside the etc/default' folder. The code in the bold letters is commented code. CELERY_BIN="/home/user/.local/bin/celery" Name of nodes to start, here we have a single node CELERYD_NODES="worker" or we could have three nodes: CELERYD_NODES="w1 w2 w3" Where to chdir at start. CELERYD_CHDIR="/home/user/django_project" CELERY_APP="django_project" How to call "manage.py celeryd_multi" CELERYD_MULTI="$CELERYD_CHDIR/django_project/manage.py celeryd_multi" Extra arguments to celeryd CELERYD_OPTS="--time-limit 300 --concurrency=8" Name of the celery config module. CELERY_CONFIG_MODULE="celeryconfig" %n will be replaced with the nodename. CELERYD_LOG_FILE="/var/log/celery/%n%I.log" CELERYD_PID_FILE="/var/run/celery/%n.pid" Workers should run as an unprivileged user. CELERYD_USER="user" CELERYD_GROUP="user" Name of the projects settings module. export DJANGO_SETTINGS_MODULE="settings" beat settings CELERYBEAT_OPTS="--scheduler django_celery_beat.schedulers:DatabaseScheduler" CELERYBEAT_LOG_FILE="/var/log/celery/celeryBeat.log" CELERYBEAT_PID_FILE="/var/run/celery/celeryBeat.pid" If enabled pid and log directories will be created if missing, and owned by the userid/group configured. CELERY_CREATE_DIRS=1 I started the celeryd using "sudo /etc/init.d/celeryd/ start" command. I started the celerybeat using "sudo /etc/init.d/celerybeat/ start" command. When I checked the status of celery and celerybeat it is showing celery init v10.1. Using config script: /etc/default/celeryd … -
Url mapping in django 2.0
so moving from Django 1.9 to Django 2 is not so smooth for me. I have struck in the URL patterns. Django 2.0 uses path instead of URL, How to convert these URL patterns to Django 2.0 compatible? url(r'^post/(?<pk>\d+)$',)views.PostDetailView.as_view(), name ='post_detail'), url('account/login/', views.login, name ='login') Thanks -
celery flower doesn't show workers menu and graph in monitor
I run a celery flower on my server. But i can't able to see the workers menu and when i click on worker name it's always loading but doesn't redirect anyware. And Monitor doesn't show any graphs. -
Django Autocomplete Formfield based on dict values
I have a modelform that I want to populate with autocomplete values from another model. The models look like this. class Company(models.Model): short_name = models.CharField(default=" ", help_text=_('eg. RT'), max_length=5) full_name = models.CharField(default=" ", help_text=_('eg.Revision Textiles Inc.'), max_length=100) class Booking(models.Model): date = models.DateTimeField(_('Booking date'), blank=True, null=True) company = models.ForeignKey(Company, related_name='book_company', null=True, blank=True, on_delete=models.CASCADE) When I am creating a Booking, I want to create a Company object, if the company doesn't exist - if it does, then I just want to assign it as the foreignkey in the view. So in the form, I am using text input fields instead of drop down selects, and using autocomplete javascript to create a list of autofill values of companies that already exist, & then checking in the view if the text input, matches the name of an existing company. The form looks like this. class CreateBookingForm(ModelForm): check_shortname = forms.CharField(label = "Short Name", max_length = 10, required = True,) check_company = forms.CharField(label = "Full Name", max_length = 100, required = True,) def __init__(self, *args, **kwargs): super(CreateBookingForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'booking-form' self.helper.add_input(Submit('submit', 'Create Booking')) class Meta: model = Booking fields = ['check_shortname','check_company','date',] The HTML & Javascript look like this... {% block add_to_header … -
Django mysqlclient backend produces django.db.utils.OperationalError: (2059, <NULL>) in Windows
I'm trying to get my Django project running on a Windows 10 computer and it throws a very unspecific error when trying to establish a datbase connection. In this SO-post the problem was with the authentication, but in that post details about the error is displayed instead of <\NULL> which gives very little to go on. The entire error looks like this: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000018C3B8761E0> Traceback (most recent call last): File "D:\Program\LiquidMarket\venv\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "D:\Program\LiquidMarket\venv\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "D:\Program\LiquidMarket\venv\lib\site-packages\django\db\backends\mysql\base.py", line 236, in get_new_connection return Database.connect(**conn_params) File "D:\Program\LiquidMarket\venv\lib\site-packages\MySQLdb\__init__.py", line 85, in Connect return Connection(*args, **kwargs) File "D:\Program\LiquidMarket\venv\lib\site-packages\MySQLdb\connections.py", line 204, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2059, <NULL>) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\Program\LiquidMarket\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "D:\Program\LiquidMarket\venv\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "D:\Program\LiquidMarket\venv\lib\site-packages\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "D:\Program\LiquidMarket\venv\lib\site-packages\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "D:\Program\LiquidMarket\venv\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "D:\Program\LiquidMarket\venv\lib\site-packages\django\core\checks\model_checks.py", line 27, in check_all_models errors.extend(model.check(**kwargs)) File "D:\Program\LiquidMarket\venv\lib\site-packages\django\db\models\base.py", line 1200, in check errors.extend(cls._check_fields(**kwargs)) File "D:\Program\LiquidMarket\venv\lib\site-packages\django\db\models\base.py", line 1272, in _check_fields errors.extend(field.check(**kwargs)) File "D:\Program\LiquidMarket\venv\lib\site-packages\django\db\models\fields\__init__.py", …