Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Conditional logic for crispy form
I've a form and I wanted to know how I was supposed to hide the field "conditionnalWeb" until the user choose "Web application" for the typeOfTheproject field? I've made my research online but I absolutely don't know how to proceed... Any help would be nice :) from django import forms from configurator import models from crispy_forms.helper import FormHelper from .models import TypeOfProgram, Language, Framework, Database class ConfiguratorForm(forms.Form): helper = FormHelper() helper.form_show_labels = False queryOfProject = TypeOfProgram.objects.values_list('name') queryOfFramework = Framework.objects.values_list('name','version') queryOfDatabase = Database.objects.values_list('name','version') listFramework = [] listProject = [] conditionnalWeb=[] listFramework=[((q[0],q[1]),q[0]+" version "+q[1])for q in queryOfFramework] listProject=[(q[0],q[0])for q in queryOfProject] listDatabase = [((q[0],q[1]),q[0]+" version "+q[1])for q in queryOfDatabase] typeOfTheproject = forms.ChoiceField(choices = listProject) conditionnalWeb = forms.ChoiceField (choices = [('nothing', '----'),("Only Backend","Only Backend"),("Only Frontend","Only Frontend")]) wantedFramework = forms.MultipleChoiceField(choices = listFramework) wantedDatabase = forms.MultipleChoiceField(choices = listDatabase) Thank you :) -
Django: AJAX code needed for dependent dropdowns
Since I'm new to Django and have absolutely no knowledge of JS/AJAX, I'm trying to code in the most simple possible way dependent dropdowns. I managed to get my dropdowns populated with values from my database (data_immo). Now I need to have the second dropdown updated after user selection in the first one. Here is my home.html file with the two dropdowns (regions and departements): <select name="regions" id="regions"> {% for item in query_results_dict %} <option value={{ item.nom_reg }}>{{ item.nom_reg }}</option> {% endfor %} </select> <select name="departements" id="departements"> {% for item in departements %} <option val="{{ item.insee_dep }}"> {{ item.insee_dep }} </option> {% endfor %} </select> views.py: def MyView(request): query_results = data_immo.objects.all() regions = data_immo.objects.values_list("nom_reg", flat=True).distinct() departements = data_immo.objects.values_list("insee_dep", flat=True).distinct() query_results_dict = { 'query_results': query_results, 'regions': regions, 'departements': departements, } return render(request,'home.html', query_results_dict) My understanding is that I need to retrieve the selected value from the "regions" dropdown and use an onChange function to trigger an action that will use that variable and inspect the db so only matching depatements are selected. Unfortunately I don't know how to proceed. I know there are a few examples out there, but none of them were really satisfying, and those I tried failed due … -
Correctly serving manifest.json via Django's gunicorn
I have a Django web app that utilizes an nginx reverse proxy with a gunicorn application server (upstream). My nginx logs are filling up with errors like these: 2020/03/03 22:51:57 [error] 9605#9605: *162393 upstream sent too big header while reading response header from upstream, client: 168.155.46.104, server: example.com, request: "GET /static/img/favicons/manifest.json HTTP/2.0", upstream: "http://unix:/home/ubuntu/app/myproj/gunicorn.sock:/static/img/favicons/manifest.json", host: "example.com", referrer: "https://example.com/signup/create-pass/new/6d756265726e2d3131/18/" I'm assuming gunicorn was unable to serve manifest.json. This shouldn't have happened. I've created manifest.json and placed it in the relevant location. Using the Favicon checker at https://realfavicongenerator.net/ shows me this error: The Web App Manifest at https://example/com/static/img/favicons/site.webmanifest cannot be downloaded. If I hit that url directly in the brower, I end up seeing a 502 Bad Gateway error. How can I fix this? -
The best way to optimize an API returning a large list of records in django rest framework
I have an endpoint returning a list of 8000 records I have integrated it with an angular material application but the issue is that the list on the client-side is taking some time to load. Which options or suggestions can I utilize to optimize the loading of the records faster? view class PermitListAPIView(generics.ListAPIView): permission_classes = [AllowAny] def get(self,request,format=None): qs = IssuedPermit.objects.all() serializer = IssuedPermitSerializer(qs, many=True) # list_ = [json.loads(x.serialize_business()) for x in qs] return Response(data={"success": True, "msg": "success", "data":serializer.data}) -
django.core.exceptions.FieldError: Unknown field(s) (number) specified for User
I am new to Django, I tried to create a new models forms but while running my server i got this error: (The form should add a "number" to the Profile database) Thanks for helping (The form should add a "number" to the Profile database) Thanks for helping File "C:\Users\xxx\PycharmProjects\web_lead_app\venv\lib\site-packages\django\forms\models.py", line 266, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (number) specified for User views.py from .forms import UserRegisterForm, ProfileUpdateForm, UserUpdateForm from django.contrib.auth.decorators import login_required @login_required() def profile(request): u_form = UserUpdateForm() p_form = ProfileUpdateForm() context = { "u_form": u_form, "p_form": p_form } return render(request, "users/profile.html", context) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ["email", "number"] class ProfileUpdateForm(forms.ModelForm): number = forms.CharField(max_length=100) class Meta: model = Profile fields = ["number"] models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) number = models.CharField(max_length=100) def __str__(self): return f"{self.user.username} Profile" -
django with celery raise No module named 'kombu' when runserver
I made a website with django and I use celery for asynchronous task, when I run: ./manage.py runserver I got the error: Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/core/management/base.py", line 341, in run_from_argv connections.close_all() File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/db/utils.py", line 225, in close_all for alias in self: File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/db/utils.py", line 219, in __iter__ return iter(self.databases) File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/db/utils.py", line 153, in databases self._databases = settings.DATABASES File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/home/rouizi/OC_project13/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/rouizi/OC_project13/car_rental/__init__.py", … -
How to import .uff pipe delimited text file to Django database?
I have a .uff file that contains multiple lines of pipe-delimited text. I have created a Django model and would like to extract relevant information from the text file and import it to my SQLite database. How can I access the information from a .uff file? -
Prop being mutated (in django templates and Vue.js with CDN)
I have a small django project and frontend is coded with Vue.js via CDN. So it has only one server for django. And vue is placed into django templates. DRF is the source of web apis. Django 2.2.10, DRF 3.11.0 and vue gets the latest from CDN. Vuetify (again from CDN) gives material UI design with v-app-bar, v-navigation-drawer and v-footer. Also Vuetify's v-data-table is used for two datasets. (countries and their cities) I can show the data when the page first responded. HOWEVER, when the drawer is closed with a button click or when the 'rows per page' of v-data-table has changed, data disappears. I should refresh the page to get it back. error is: [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "tableData" found in ---> <LocCountry> <VContent> <VApp> <Root> list page: {% extends 'locations/index.html' %} {% load static%} {% block content %} <loc-country></loc-country> {% endblock %}{% block extrascript %} <script> Vue.component("loc-country", { props: ["tableData"], template: ` <v-data-table :headers="headers" :items="tableData" class="elevation-1"></v-data-table> `, data() { return { // tableData: null, loading: true, errored: false, headers: … -
Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) tried: ['update_order\\/(?P<pk>[^/]+)\\/$']
I guess there is some error in updateorder function, but I cannot find it. When I am clicking on the update button in dashboard.html it gives an error saying that Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) tried: ['update_order\/(?P[^/]+)\/$'] views.py from django.shortcuts import render, redirect from django.http import HttpResponse from accounts.models import * from accounts.forms import OrderForm # Create your views here. def home(request): customers = Customer.objects.all() orders = Order.objects.all() total_customers = customers.count() total_orders = orders.count() pending = orders.filter(status='Pending').count() delivered = orders.filter(status='Delivered').count() context = {'customers':customers, 'orders':orders, 'pending':pending, 'delivered':delivered, 'total_customers':total_customers, 'total_orders':total_orders} return render(request, 'accounts/dashboard.html', context) def products(request): products = Product.objects.all() return render(request, 'accounts/products.html', {'products':products}) def customer(request, pk): customers = Customer.objects.get(id=pk) orders = Order.objects.all() orders_counts = orders.count() context = {'customers':customers, 'orders':orders, 'orders_counts':orders_counts} return render(request, 'accounts/customer.html', context) def createorder(request): form = OrderForm if request.method=='POST': form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request, 'accounts/order_form.html', context) def updateorder(request, pk): orders = Order.objects.get(id = pk) form = OrderForm(instance = orders) context = {'form':form} return render(request, 'accounts/order_form.html', context) > Blockquote urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name = 'home'), path('products/', views.products, name = 'products'), path('customer/<str:pk>/', views.customer, name = 'customer'), path('create_order/', views.createorder, … -
How to configure IPN paypal for live transaction in django
It works for sandbox but it's not works for live transaction. I don't have idea how to configure for live transaction. Please help me I am searching solution for this problem from last 3 days. def process_payment(request): domain=request.session.get('domain_name') key = request.session.get('key') keystore=request.session.get('keystore') flag=request.session.get('flag') emails=str(request.user) strings= key+" "+emails+" "+keystore+" "+str(flag) host = request.get_host() paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, 'amount': '19.00', 'item_name': 'Order', 'invoice': domain, 'currency_code': 'USD', 'custom':strings, 'notify_url': 'http://{}{}'.format(host,reverse('paypal-ipn')), 'return_url': 'http://{}{}'.format(host, reverse('payment_done')), 'cancel_return': 'http://{}{}'.format(host,reverse('payment_cancelled')), } form = PayPalPaymentsForm(initial=paypal_dict) return render(request, 'payment/process.html', {'form':form}) -
In Django, how to know which button was pressed?
Here is my html, I have two buttons, one for accepting and the other for rejecting the request. In my view, I need to know which button was pressed along with the email of the applicant (tutor_application.tutor.chalkslateuser.email). I tried many solutions but to no avail. {% for tutor_application in tutor_application_list %} <div class="card" style="width: 15rem;"> <img src="{{ tutor_application.tutor.picture.url }}" class="card-img-top" > <div class="card-body"> <h5 class="card-title"> {{ tutor_application.tutor.chalkslate_user.first_name }} {{ tutor_application.tutor.chalkslate_user.last_name }} </h5> <h6 class="card-subtitle mb-2 text-muted">{{ tutor_application.note }}</h6> <h6 class="card-subtitle mb-2 text-muted">{{ tutor_application.posted }}</h6> </div> <a class="btn btn-outline-success" role="button" type="submit"> Accept </a> <a class="btn btn-outline-danger" href="#" role="button"> Reject </a> </div> {% endfor %} -
format output not working anymore in new version of django
def render(self, name, value, attrs=None, renderer=None): if not value: value = [ x for x in self.widgets] rendered_widgets = [ x.render('%s_%d' % (name,i), value[i]) for i,x in enumerate(self.widgets) ] context = {'fields': rendered_widgets} return render_to_string('tifact/widgets/newdevicewidget.html', context) I am migrating from django 1.8 to django 2.2 , and MY below code i am trying to mgirate it above. THe issue I have, the textinput are coming filled with data. I dont want to touch them. JUst display as they were created.SOmeone help. def format_output(self, rendered_widgets): # formats the fields to be displayed horizontally context = {'fields': rendered_widgets} return render_to_string('tifact/widgets/newdevicewidget.html', context) -
How to add two url's together in de {% static %} tag in django
Does somebody know if it is possible to add following two strings together, so that django reads it as one url. Django: src="{% static 'post_it/media/post_images/' + '{{ post.image_name }}' %}" Thanks -
Django subquery outerref('id') You might need to add explicit type casts
I'm using postgresql. i write subquery in subquery i want to apply filter on id of parent table with field of child table. but it shows error query: orders = Order.objects.filter(user=request.user, status='P') albums = models.Album.objects.annotate(purchased_status=Subquery(orders.values('id').filter(item_id=OuterRef('id'))[:1])) Error django.db.utils.ProgrammingError: operator does not exist: character varying = integer LINE 1: ...atus" = 'P' AND U0."user_id" = 1 AND U0."item_id" = "bookcen... HINT: No operator matches the given name and argument types. You might need to add explicit type casts. if i apply filter on any of field other then id it work fine. this error fix if i will add id for parent table as foreign key in child table but don't want to do this. issue if because OuterRef('id') return reference id not just integer value like 1 or 2 is there any way with which OuterRef('id') can return integer value of id. -
Django admin change_view does not pass extra_context to html
I'm looking for quite some time now to get extra_context passed to the html of the admin change view. The rendered change form only shows the H tags. I've checked my data up till it gets returned and all seems ok. It just will not be passed forward. Strangely I don't get any errors on indexing in html page. Does somebody spot a mistake? admin.py class CustomerAdmin(admin.ModelAdmin): list_display = ("name", "company", "country", "invoice_currency") search_fields = ["name", "company", "country"] list_filter = (TotalInvoiceOver1kFilter,) actions = [get_all_customers_invoices,] change_form_template = 'admin/crm/change_form.html' def change_view(self, request, object_id, form_url='', extra_context=None): extra = extra_context or {} extra['last_three_inv'] = Invoice.objects \ .filter(inv_customer=object_id) \ .order_by('-inv_date')[0:3] extra['total_amount_12_months'] = Invoice.objects \ .filter(inv_customer=object_id) \ .aggregate(Sum('inv_amount')) return super(CustomerAdmin, self).change_view( request, object_id, form_url, extra_context=extra_context, ) change_form.html <!DOCTYPE html> {% extends "admin/change_form.html" %} {% block form_top %} <h2>Last 3 invoices:</h2> {% for invoice in extra_context.last_three_inv %} {{invoice.inv_number}} {% endfor %} <h2>Total amount past 12 months:</h2> {{extra_context.total_amount_12_months.inv_amount__sum}} {% endblock %} -
default context for all pages Django
I was wondering if there's any way of sending a default context for all pages in django, such as user is always passed to the template regardless of other context, for my particular case i want to send context for navbar such as category and sub category to all pages without having to send in all the views. TIA -
How to read contents of zip file in memory on a file upload in python?
I have a zip file that I receive when the user uploads a file. The zip essentially contains a json file which I want to read and process without having to create the zip file first, then unzipping it and then reading the content of the inner file. Currently I only the longer process which is something like below import json import zipfile @csrf_exempt def get_zip(request): try: if request.method == "POST": try: client_file = request.FILES['file'] file_path = "/some/path/" # first dump the zip file to a directory with open(file_path + '%s' % client_file.name, 'wb+') as dest: for chunk in client_file.chunks(): dest.write(chunk) # unzip the zip file to the same directory with zipfile.ZipFile(file_path + client_file.name, 'r') as zip_ref: zip_ref.extractall(file_path) # at this point we get a json file from the zip say `test.json` # read the json file content with open(file_path + "test.json", "r") as fo: json_content = json.load(fo) doSomething(json_content) return HttpResponse(0) except Exception as e: return HttpResponse(1) As you can see, this involves 3 steps to finally get the content from the zip file into memory. What I want is get the content of the zip file and load directly into memory. I did find some similar questions in stack … -
Custom Django User Model Setup from Existing (Drupal) Database Table
I’m working on a project to replace a Drupal 6 application, and am trying to figure out how to use its MySQL ‘users’ table to create my Django user models for authentication. Both apps are housed on the same server so I have easy access to the db. The Drupal ‘users’ database is still actively used for a greater application from which my project is a subset, so I am not able to restructure it, and I’m hoping to avoid requiring separate accounts for my app since it is all part of the same ecosystem/has existing users. I can't just copy the existing users to a new table as people will continue to make accounts on the Drupal system. I’ve researched AbstractUser and AbstractBaseUser, but have not found a way to assign columns from an existing table to the username and password variables. All of the custom user model solutions seem to assume that the user database is starting fresh, and takes care of assigning, storing, and saving usernames and passwords behind the scenes. I’m considering using a standard User model, checking unrecognized usernames and passwords against the Drupal User db, and creating a new Django user on the first … -
Debug a background django request (show local variables)
Here's my setting: 2 Django services (A and B) run in production using gunicorn+nginx. The user logs into service A and adds an object entry then clicks submit which generates an XHR request (1) Service A recieves the request (1) and publishes in background the new object to service B. (request 2 When B recieves and handles the request (2), the error occurs. Both the services have DEBUG = True and logging level set to 'DEBUG'. To debug the error, I need to access values of local variables in the error's stack trace. I can't in the browser because I am far from the faulty service (XHR then a background process request to a remote service). The console prints stack trace but without local variables. Is there a simple way to achieve the result I want ? Regards -
how to implement user manager to create custom user using AbstractUser class?
im trying to make my own custom user model with AbstractUser class class CustomUser(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) def __str__(self): return self.username class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) def __str__(self): return self.user.username but when i create new account the password field wont been encrypted it show only a plain text ! i think i should use BaseUserManager but i dont have any idea to make it thanks , regards .. -
Getting a query set between a range of dates Django
I'm trying to return a list of items in between 2 different dates, a date in the past and the current time using a queryset. The error I'm getting is TypeError: an integer is required (got type str) views.py import datetime import pytz first_date = "2020-01-01 19:17:35.909424" last_date = timezone.now() I don't want anything returned that has a date in the future Here is the filter in the query .filter(hide_sentance_until=(date(first_date), date(last_date))) This is the full queryset, but it's the above filter causing he issue zip_flash_sentances = model.objects.filter(show_sentance=True).filter(hide_sentance_until=(date(first_date), date(last_date))).order_by("?").filter(username_id = user_id_fk).values_list('sentance_eng', 'sentance_esp', 'id').first() I thought it might be a comparison problem with dates but here is my model field models.py hide_sentance_until = models.DateTimeField(default=datetime.now(), blank=True) Thanks -
How to Import a bootstrap template in django, static function not working ;-;
I am trying to import a bootstrap template into my django app using the static function to render all of the static elements in to the app but it does not seem to work, I have followed the tutorial on the django homepage but it still doesn't work.The name of my template is inbox.html. Here is the code for my settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'p2(ljol9n-6g_#=!lb!c@z_#3u#2b8*hj4=^ou7!)=7q^r^sz9' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'CollectMail.apps.CollectMailConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'guardian', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Emails.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Emails.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, … -
'learning_logs' is not a registered namespace
I have been seeing the following error. How can I solve it? Error: 'learning_logs' is not a registered namespace urls.py """Defines URL pattern for learning_logs""" from django.conf.urls import url from . import views app_name = 'learning_log' urlpatterns = [ #Home page url(r'^$', views.index, name='index'), url(r'^topics/$', views.topics, name='topics'), ]``` #base.html '''<p> <a href="{% url 'learning_logs:index' %}">Learning Log</a> - <a href="{% url 'learning_logs:topics' %}">Topics</a> </p> {% block content %}{%endblock content %} -
Download to client browser using youtube_dl
How can I use youtube_DL to download directly to a clients browser instead of my project file with python django -
Django not installing
I am trying to instal Django on my new mac. I am not able to do so. Please advice. I also tried sudo commmands, but this only installs with python 2 and not 3