Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting val() of last checkbox checked by a user
I am building an application that allows users to choose pizza toppings by checking/unchecking checkboxes. The maximum I would like them to be able to select is 3 checkboxes. Once they select 4, I would like to send an alert to the user and deselect the last_checked checkbox. I have tried the following code to access the value of the most recent checked checkbox: $("#Pizza #id_toppings").change(function() { var last_checked = $("#Pizza #id_toppings input[name='toppings']:checked").val() alert("The checkbox: '" + last_checked + "' changed"); }); Unfortunately, this only returns the value of the lowest checked box. Any ideas how I can get it to return the last_checked box? Example form is below. <form action="/cart/" method="post" id="Pizza"> <input type="hidden" name="csrfmiddlewaretoken" value="hmgXKE0ximQjeAvhcSpLPa4WvL7dtUHW76D41WAgxMyzoBzTpzjeAMVuA99P3kSD"> <input type="hidden" value="Pizza" name="menu_item" id="menu_item" /> <p><label for="id_style">Style:</label> <select name="style" required id="id_style"> <option value="" selected>---------</option> <option value="1">Regular</option> <option value="2">Sicilian</option> </select></p> <p><label for="id_size">Size:</label> <select name="size" required id="id_size"> <option value="" selected>---------</option> <option value="1">Small</option> <option value="2">Large</option> </select></p> <p><label for="id_is_special">Gluten Free Dough:</label> <input type="checkbox" name="is_special" id="id_is_special"></p> <p><label for="id_num_toppings">Number of Toppings:</label> <input type="number" name="num_toppings" required id="id_num_toppings"></p> <p><label>Toppings:</label> <ul id="id_toppings"> <li><label for="id_toppings_0"><input type="checkbox" name="toppings" value="1" id="id_toppings_0"> Pepperoni</label> </li> <li><label for="id_toppings_1"><input type="checkbox" name="toppings" value="2" id="id_toppings_1"> Sausage</label> </li> <li><label for="id_toppings_2"><input type="checkbox" name="toppings" value="3" id="id_toppings_2"> Mushrooms</label> </li> <li><label for="id_toppings_3"><input type="checkbox" name="toppings" value="4" … -
Django different USERNAME field for registration and for login
I want to have a USERNAME_FIELD for registration of my users (lets say this field is the country ID) and another one for login (internal id). My process is as follows: User registers with name, email and COUNTRY_ID (as username_field) aswell with a password. Next, an admin validates this information and confirms the registration of this user and an automatic internal ID is assigned. The user is then informed (via email) of this action and can therefore login with this internal id. Is it possible then to have a different USERNAME_FIELD for registration and for login? -
Django + Scrapy multi scrappers architecture
Recently I took over Django project whose one component is Scrapy scrappers(a lot of - core functionality). Scrappers have direct access to Django model, but in my opinion is not the best idea (mixed responsibilities - django rather should act as a web app, not also scrappers, isn't it?). For example after such split scrappers could be run serverless, saving money and being spawned only when needed. I see it at least as separate component in the architecture. But if I would separate scrappers from Django website then I would need to populate DB there as well - and change in model either in Django webapp or in scraping app would require change in second app to adjust. I haven't seen really articles about splitting those apps. What are the best practices here? Is it worth splitting it? How would you organise deployment to cloud solution(e.g. AWS)? Thank you -
How to use the shell with Django environement in Eclipse after modification of my application?
I'm trying to use the shell with Django environement in Eclipse but every time I modify a class in my application I need to restard the shell to take changes into account. If I import the new class the shell doesn't see the change. Am'I missing something? -
When i loop over a folder that contains images, after a create mutation i get printed same images instead of different ones
I made a small program that sends dota2 api heroes and their primary attribute to my posgreSQL database. Also i did for the images that i scraped. Images are in media/images folder that contians all dota2 hero images (around 116 i think). I iterated over images and here is what i got -- https://prnt.sc/qn378i It loops over images in all files in that folder (I used os.walk() function). It prints all images of zeus icon.png instead of looping all names of images. code: import requests import json import os API_URL = 'http://127.0.0.1:8000' if __name__ == '__main__': r = requests.get("https://api.opendota.com/api/heroes") all_heroes_info = json.loads(r.content.decode('UTF-8')) for root, dirs, files in os.walk("../../media/images/", topdown=False): for image in files: pass image = image.lower() for hero_info in all_heroes_info: name = hero_info['localized_name'] hero_type = hero_info['primary_attr'] mutation_create_hero = ''' mutation ($name: String!, $heroType: String!, $image: String!) { createHero(name: $name, heroType: $heroType, image: $image) { name image } } ''' variables = {'name': name, 'heroType': hero_type, 'image': image} print(image) # localhost_api_response = requests.post( # '{}/graphql/'.format(API_URL), # json={ # 'query': mutation_create_hero, # 'variables': variables # } # ) But here is the problem When i actually delete all the # and run the program my postgreSQL db is filled with this … -
Where to run collectstatic when deploying django app to heroku using docker?
I am deploying a Django app to Heroku using Docker. When I put RUN manage.py collectstatic --noinput in the Dockerfile, it fails because there value set for the environment variable DJANGO_SECRET_KEY. My understanding is that this is because config vars aren't available during build time. When I run collectstatic as a release command, it works without error, and successfully copies the static files. However, when I hit the app url, it returns a 500 error because the static files can't be found. I believe this is because the release command is run as a dyno on an ephemeral filesystem, and the copied files are therefore not found. It seems to be a catch-22. Putting collectstatic in the Dockerfile fails because there are no config variables available, but putting it as a release command fails because only file changes from the build phase are saved? What to do? Here are my collectstatic settings in settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] ... STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_STORAGE = 'backend.storage.WhiteNoiseStaticFilesStorage' Dockerfile # Pull base image FROM python:3.7-slim # Set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory RUN … -
How to facilitate communication between different web application?
im trying to link up 2 different projects. I wish to be able to send out a key information to the other existing webapplication , which will then be captured in the other project's database , and the programme will then regenerate a key which will be synced back into my system to be displayed. The first programme is done using python django , and the second project is done using c# , is there a way to accomplish this? Here is some of my code: class SalesProject(models.Model): sales_status= ( ('p1','Phase 1'), ('p2','Phase 2'), ('p3','Phase 3'), ('p4','Phase 4'), ) type_of_sales = ( ('nc','non-commodities'), ('co','Commodities') ) status = ( ('active', 'Active'), ('completed', 'Completed'), ('inactive', 'Inactive') ) sales_project_id = models.AutoField(primary_key=True) sales_project_name = models.CharField(max_length=100) salesExtra = models.ManyToManyField('SalesExtra', blank=True) customer_information = models.ManyToManyField('CustomerInformation') sales_project_status = models.CharField(max_length = 10 , default = 'p1', choices = sales_status) sales_type = models.CharField(max_length = 10 , choices = type_of_sales) sales_project_starting_date = models.DateTimeField(auto_now = True) sales_project_closing_date = models.DateTimeField(default=timezone.now, blank=True, null=True) moq = models.IntegerField(default=50) status = models.CharField(max_length=10, choices = status, default = 'active') quotation_id = models.CharField(max_length=20,default=Null) The whole idea is to use the django rest framework and ajax . An instance will be created using a form that will lock in key … -
Filter Creation Date By Time Range
Im trying to filter my first two IF statement to only show the created_at records from 8 am to 10 am for todays current date. Here is my views.py. How do i add this to my IF statement ? Thanks views.py def Student_Progress(request, studentpsid): if request.method == "GET": date = datetime.date.today() # Calculates Points on Student Progress Page academic = K8Points.objects.values_list('academic', flat=True).filter( student_name_id=studentpsid).filter(date=date) behavior = K8Points.objects.values_list('behavior', flat=True).filter( student_name_id=studentpsid).filter(date=date) my_class_id = request.session['my_class_id'] academic_total = 0 behav_total = 0 for score in academic: academic_total += int(score) for score in behavior: behav_total += int(score) grand_total = academic_total + behav_total counseling = Student.objects.values_list( 'counseling_goal', flat=True).get(studentpsid=studentpsid) studentid = Student.objects.get(studentpsid=studentpsid) k8obj = K8Points.objects.filter( student_name_id=studentpsid, date=date).order_by('time_frame') # Checks To See If a Student Gets Morning Recess if grand_total >= 20 and K8Points.objects.filter(time_frame=1).filter(date=date) and K8Points.objects.filter(time_frame=2).filter(date=date) and K8Points.objects.filter(time_frame=3).filter(date=date): morning_recess = "YES" context = ({'studentid': studentid, 'date': date, 'counseling': counseling, 'grand_total': grand_total, 'academic_total': academic_total, 'behav_total': behav_total, 'k8obj': k8obj, 'my_class_id': my_class_id, 'morning_recess': morning_recess}) return render(request, 'points/student_progress.html', context) if grand_total <= 20 and K8Points.objects.filter(time_frame=1) and K8Points.objects.filter(time_frame=2) and K8Points.objects.filter(time_frame=3).filter(date=date): morning_recess = "NO" context = ({'studentid': studentid, 'date': date, 'counseling': counseling, 'grand_total': grand_total, 'academic_total': academic_total, 'behav_total': behav_total, 'k8obj': k8obj, 'my_class_id': my_class_id, 'morning_recess': morning_recess}) return render(request, 'points/student_progress.html', context) else: context = ({'studentid': studentid, 'date': date, … -
How to configure reordering order_with_respect_to items in the Django admin?
I am trying to use the order_with_respect_to Django Meta option and reorder items in the admin. I found https://github.com/bfirsh/django-ordered-model but they doesn't seem to use the native Django API for it. Do you know does one add this reorder functionality to the Django admin? -
How to get site settings in a django project converted to wagtail
I have a django site onto which I have added wagtail following these instructions. I have set up Social Media setting using these instructions I have sucessfully added details on the admin page ad I can return and edit these details However I cannot access them in a template If I display {{settings.site_settings.SiteSettings.facebook}} I get '' (tested using {% if settings.site_settings.SiteSettings.facebook == '' ...) However {{settings.site_settings.SiteSettings}} returns None and {{settings.site_settings}} returns SettingsModuleProxy(site_settings) What am I doing wrong? -
Django Filter icontains count slow on TextField()
response_title = models.TextField(null=True,blank=True) response_status_code = models.IntegerField(null=True,blank=True) response_body = models.TextField(null=True,blank=True) recently I have been facing a slow performance for my site so Here's my observation from Django shell, I have 32k entries in my model & performing with icontains is slow compared to contains also count on icontains query took 4 seconds whereas count on contain took 0.3 seconds. type of data I'm storing in response_body is Raw response body. from .models import Response_Dataset >>> Response_Dataset.objects.count() ## 0.1 sec 32289 >> Response_Dataset.objects.filter(response_body__icontains='hack') ## 0.4 seconds >>> x = Response_Dataset.objects.filter(response_body__icontains='hack') >>> x.count() ### 4 seconds 65 >>> x = Response_Dataset.objects.filter(response_body__contains='a') ### 0.2 seconds >>> x.count() ### 0.3 seconds 23857 Performing with icontains on any other field beside the response_body is extremely fast such as on response_title or response_status_code -
Django ORA-03113 error using multithreading
I have a system that basically starts threads from the main processes, several parameters are passed to those threads, I need to access the DataBase to fetch those parameters. So the code basically is: from procs import Processor from multiprocessing import Pool active = True while active: parameters = Parameters.objects.all() processor = Processor() django.db.connections.close_all() pool = Pool(processes=12) pool.starmap(processor.proces, parameters) pool.close() pool.join() pool.terminate() active = int(Parameters.objects.get(dsc='is_active').value) When I try to get the 'is_active' active parameter after the pools ends the processing I get the ORA-03113 error. django.db.utils.OperationalError: ORA-03113: end-of-file on communication channel on connection closing -
Default Apache displaying instead of homepage
I am having issues trying to deploy my site,.I am still new in both Django , their is a tutorial I have been following on how to deploy the site, Everything works fine except it renders the default Apache page instead of my site when I restart the server. Here is my project directory Alias /static /home/brian/src/static Require all granted Alias /media /home/brian/src/media Require all granted Require all granted WSGIScriptAlias / /home/brian/src/src/wsgi.py WSGIDaemonProcess django_app python-path=/home/brian/src python-home=/home/brian/src/venv WSGIProcessGroup django_app -
Reply to Inputted Email Django
I have a contact form in my website and Its working but in my email setup, I'm using a static email and wish to use the email that was typed in the email field instead. The data grabbed from the form looks like this {'from_email': 'example@gmail.com', 'subject': 'Hello World', 'message': 'asdasdasd'} My imports in my view.py file from django.http import HttpResponse from django.shortcuts import render from django.views import View from django.http import JsonResponse from django.conf import settings from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from .forms import ContactForm from django.core.mail import EmailMessage The class view looks like this class ContactMe(View): template = "contact.html" context = { 'form': ContactForm() } def get(self, request): print("getting form") return render(request, self.template, self.context) def post(self, request): form = ContactForm(request.POST) def __init__(self): self.mailSender = mailSender() Mail = POST Mail.MailSender.send_mail() if form.is_valid(): data = form.cleaned_data print(data) send_mail(data['subject'], data['message'], settings.EMAIL_HOST_USER, data['from_email']) next = request.POST.get('next', '/') return HttpResponseRedirect(next)` the data['from_email'] was set to my email ['example@gmail.com'] and I changed it to the label name in the data that it gets ('from_email') It works 100% with a static email instead of the variable form_email but using form_email gives an error TypeError: "to" … -
Django assignes the same position to multiple uploaded files ( possible race condition ?)
Problem When a file is being uploaded, the Django backend assigns a position to a file. The problem here is though, that the moment I upload multiple files, the backend assigns the same position to different files. As I am quite new in creating a Django backend, I'm at a loss here, because I tried to fix it in a few ways I found on this site or the documentation. I may have missed a few things, or made mistakes in my approach, but would appreciate every possible solution to this problem. Tried Fixes -putting the assignment of the position into a subquery in the creation query -using atomic transaction -updating the asset after the creation Code The creation of the asset happens in the post function of the View: class UploadView(APIView): parser_classes = (MultiPartParser, FormParser) def post( self, request, entity_name, entity_id, category=None, ): [...] # Check if the information are existing # Create a new asset asset = Asset.objects.create( content_type=content_type, content_object=content_object, object_id=entity_id, file_obj=file, field_name=field_name if field_name else None, category=category or '', # # position = xyz, <= the assignment of the position while creating the asset # original_filename=request.GET.get('original_filename', ''), created_by=request.user) # Return new asset return Response(AssetSerializer(asset).data, status=201) -
Error: spawn ENOTDIR, when selecting python interpreter in VS Code
I have created django project and virtualenv into same folder as opening-up vscode does not display the virtual environment in which the django project is using. now if I select interpreter for the project I get -
Installing Django MicroPyramid / Django-CRM
Good day. This is more of an observation as to a technical question. We are a small sales company of about 5 sales people. We in need of an automated solution in terms of a CRM. We have manual business processes - for instance (lead) e-mail from website or facebook campaigns are forwarded by manager via normal e-mail to salesperson. Manager has no view of how many quotes were sent per lead -apart from sales people doing an excel spreadsheet. Would Django CRM be the solution? Does anyone have an example of how they have used it in their company? -
Formatter that works on django templates
Is there an automatic formatter that works out of the box for Django templates? It doesn't have to format the stuff inside the django tags as long as it maintains indentation. -
join() argument must be str or bytes, not 'int'
def edit_device(request, pk, model, cls): item = get_object_or_404(model, pk=pk) if request.method == "POST": form = cls(request.POST,instance=item) if form.is_valid(): form.save() return redirect('index') else: form = cls(instance = item) return render(request,'organization/edit_item.html',{'form':form}) def edit_laptop(request, pk): return render(request, pk, Laptop, LaptopForm) -
Django: TypeError: __init__() takes 1 positional argument but 2 were given
To understand how form and view work in Django I made a new project and I insert the code that I found in documentation below the "Generic editing views" of Django. Every time I try to run the code I have the error __init__() takes 1 positional argument but 2 were given. I read many time the documentation and code and I didn't find error This is the code I insert. The project is created from scratch. in forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField() message = forms.CharField(widget=forms.Textarea) def send_email(self): # send email using the self.cleaned_data dictionary pass in models.py class Author(models.Model): name = models.CharField(max_length=200) def get_absolute_url(self): return reverse('author-detail', kwargs={'pk': self.pk}) in views.py class ContactView(FormView): template_name = 'contact.html' form_class = ContactForm success_url = '/thanks/' def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.send_email() return super().form_valid(form) in urls.py from .views import ContactView urlpatterns = [ path('admin/', admin.site.urls), path('aa/', ContactView, name='contatto'), ] in contact.html <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Send message"> </form> I also tried to insert via admin page a record, so there is a record in the table. I looking … -
Django not rendering form fields
I looked at similar questions but they do not seem to apply. I have a very simple django form which does not show on the website, I only see the Submit button. Here are the relevant files: models.py from django.db import models from django.urls import reverse import uuid # Create your models here. class Job(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) job_name = models.CharField(max_length=200) #One to many relationship requires on_delete email = models.EmailField() def __str__(self): return self.job_name forms.py from django import forms class JobForm(forms.Form): job_name = forms.CharField(max_length=200) email = forms.EmailField() views.py from django.shortcuts import render from django.views.generic import TemplateView from .forms import JobForm from .models import Job class HomePageView(TemplateView): template_name = 'index.html' class SubmitPageView(TemplateView): template_name = 'submit.html' def submit_job(request): # Retrieve post by id if request.method == 'POST': # Form was submitted form = JobForm(request.POST) if form.is_valid(): #Form fields passed validation #If the form is valid, we retrieve the validated data accessing #form.cleaned_data. This attribute is a dictionary of form fields and their values. cd = form.cleaned_data my_model = Job() my_model.job_name = cd.get('job_name') my_model.email = cd.get('email') # Save the job to the database my_model.save() else: form = JobForm() return render(request, SubmitPageView(), {'form': form}) And in my template I have <form … -
How to import registered filters from one Django view to another?
I have a Django project with multiple modules. I want to reuse filters I have created. E.g. code: main/views.py from django.template.defaulttags import register @register.filter def get_item(dictionary, key): return dictionary.get(key) @register.filter def get_range(value): return range(value) (How) Can I import and use these filters (w/o cut and paste) in secondary/views.py? -
Python int too large to convert to SQLite INTEGER?
OverflowError at /Cart/0ac4e6e6-2538-40e3-9a6a-f98eec939c5f Python int too large to convert to SQLite INTEGER Request Method: GET Request URL: http://127.0.0.1:8000/Cart/0ac4e6e6-2538-40e3-9a6a-f98eec939c5f Django Version: 3.0.2 Exception Type: OverflowError Exception Value: Python int too large to convert to SQLite INTEGER Exception Location: /usr/local/lib/python3.7/dist-packages/django/db/backends/sqlite3/operations.py in _quote_params_for_last_executed_query, line 141 Python Executable: /root/EeshaTechnology/venv/bin/python Python Version: 3.7.3 Python Path: ['/root/EeshaTechnology/Fonia', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/root/EeshaTechnology/venv/lib/python3.7/site-packages', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages', '/usr/lib/python3.7/dist-packages'] Server time: Mon, 13 Jan 2020 13:03:05 +0000 -
celery/rabbitmq within a docker container works fine unless docker run is called with -d
I have a container running a django/rabbitmq/celery server. On the same machine I am running a client django/celery/rabbitmq instance. If I run it with: docker run -v ~/dir:/host_directory --mount source=django-uploads,target=/uploads -it --name serverside_worker_container --privileged --entrypoint '/bin/bash' worker_image_name:latest -c "source /host_directory/setup.sh && export USE_CELERY_LOGGING=1 && source run_serverside_worker_staging.sh && /bin/bash" It connects fine. However, if I add -d to the docker run call, Celery/rabbitmq never connects - ie, I get constant output like this: Trying again in 20.00 seconds... Anyone have any ideas? [Some details, put at the end for readability of main post: Command to run server: docker run -d --network host --mount source=django-uploads,target=/uploads --name server_container -it --entrypoint '/bin/bash' --privileged image_name:latest -c "source run_server_staging.sh" Worker command including -d: , like this: docker run -d -v ~/dir:/host_directory --mount source=django-uploads,target=/uploads -it --name serverside_worker_container --privileged --entrypoint '/bin/bash' worker_image_name:latest -c "source /host_directory/setup.sh && export USE_CELERY_LOGGING=1 && source run_serverside_worker_staging.sh && /bin/bash" ] -
Wagtail/Django: Query filter to return only the pages the user has acess/permissions?
I'm going through the documentation at: http://docs.wagtail.io/en/v2.7.1/reference/pages/queryset_reference.html. Is there a filter to return only the pages the user has access to? I can only see public() and not_public(). I have some pages which privacy is set to Private (accessible to users in specific groups). And would like to exclude them from the query results.