Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form - JQuery - chained fields - verification fails (is_valid function)
In my Django form I have three fields that are linked to each other (similar to the trio country- state-city which is often given as an example on the web). Visually it works thanks to jQuery scripting. The #id_division field interacts with #id_section which interacts with #id_cellule which interacts with #id_superieur. {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block css %} {% endblock css %} {% block title %} <title>Edit user</title> {% endblock title %} {% block toolbar %} {% endblock toolbar %} {% block content %} <br> <form method="POST" class="bootstrap4" id="id-StaffForm" data-sections-url="{% url 'ajax_load_sections' %}" data-cellules-url="{% url 'ajax_load_cellules' %}" data-superieurs-url="{% url 'ajax_load_superieurs' %}" novalidate> {% csrf_token %} {% crispy staff_form %} </form> {% endblock content %} {% block script %} <script> var sections_url = $("#id-StaffForm").attr("data-sections-url"); var cellules_url = $("#id-StaffForm").attr("data-cellules-url"); var superieurs_url = $("#id-StaffForm").attr("data-superieurs-url"); var divisionId = $("#id_division").val(); var sectionId = $("#id_section").val(); var celluleId = $("#id_cellule").val(); $('#id_division').change(function () { divisionId = $(this).val(); $("#id_section").html(''); // initialize an AJAX request for SECTION $.ajax({ // set the url of the request url: sections_url, // add the division id to the GET parameters data: { 'division': divisionId }, // `data` is the return of the `load_sections` view function … -
Django Chache - Update when model changed
I can't seem to find any tutorial on how to do this. So, I basically want to add caching to my Django project. I made a blog view, that should be cached and updated only if the model got changed since last caching. How do I do this? -
Django submit form when browser is refreshed for multiple form
There is a lot of similar question. But my problem is slightly different. In a view, I am using multiple forms, for that, I am using formset and normal form.here is my view: class CreateInvoice(TemplateView): template_name = 'product/create_invoice.html' product_list = Product.objects.get_all_product() ItemFormSet = formset_factory(ItemForm, formset=BaseItemFormSet, extra=0) def get_context_data(self, **kwargs): if 'items' not in kwargs: kwargs['items'] = self.ItemFormSet() if 'order' not in kwargs: kwargs['order'] = OrderForm() kwargs['product_list'] = self.product_list return super().get_context_data(**kwargs) def post(self, request): item_formset = self.ItemFormSet(request.POST) order_form = OrderForm(request.POST) if order_form.is_valid() and item_formset.is_valid(): order = order_form.cleaned_data items = item_formset.cleaned_data order['sold_by'] = request.user order_id = Order.objects.crate_new_order(order=order, items=items) return HttpResponseRedirect(self.render_to_response(self.get_context_data(pos_invoice=generate_pos_invoice(), order_id=order_id))) else: return HttpResponseRedirect(self.render_to_response(self.get_context_data(items=item_formset, order=order_form,))) If forms are not valid then I need to render the same page with error messages. If forms are valid then also need to render the same page with the HTML receipt string and the extra data. But here the problem is if the browser is refreshed (like pres crtl+f5) then the same forms are submitted again. From googling I came to know that this problem is created for I am using render instead of a redirect. Here is the link of the question from where I came to know this: Django form submit again on refresh … -
What is the best way to use other models as dynamic fields in django?
I'm working on an app that basically functions like a gradebook + online exam service. In an analog gradebook, or in one on a spreadsheet, teachers typically have a row entry for each student. Then, they make a new column for every exam, and fill in all the students' grades for that exam. So I want to be able to add and remove exams at will, and also to show the user things like "all student grades for this exam" or "all exam grades for this student". Each exam model is built from a list of (ManyToMany) Question models. Ideally, I'd also like to be able to track individual questions the same way I do exams: get a list of which students got them right, etc. Is there a best or standard way to do these things? ManyToManyFields seem a little awkward to me and I was wondering if I was missing something. -
url getting doubled when opening a link from the home page.(django)
On clicking the 2nd item in the list it opens the events.html page but the url shows: http://127.0.0.1:8000/events/events/ instead of http://127.0.0.1:8000/events Home page code: <li><a href="#">HOME</a></li> <li><a href="{% url 'events' %}">EVENTS</a></li> <li><a href="#">REGISTERED TEAMS</a></li> <li><a href="#">CONTACT US</a></li> Urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home_page, name='home_page'), path('hackathon_register/',views.hackathon_register,name='hackathon_register'), path('events/',views.events,name='events') ] views.py def events(request): return render(request,'testapp/events.html',{}) -
Replace white space with hyphens in Django URL
I saw that a lot of websites (including stackoverflow) will have the title of the questions/articles in the URL with hyphens and I am trying to achieve the same for a small blog app using Django, however, so far I have been having 0 success. My models.py look as follow: class Post(models.Model): title = models.CharField(max_length=255, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() def __str__(self): return self.title + '|' + str(self.author) Defining the URL as: urlpatterns = [ # re_path(r'^post/(?P<title>[\w\-]+)/$', PostView.as_view(), name='post_details'), path('post/<slug:title>', PostView.as_view(), name='post_details'), ] and adding the following to the views.py: class PostView(DetailView): model = Post slug_field = slugify('title') slug_url_kwarg = slugify('title') template_name = 'post_details.html' resulted no success, as titles which have hyphens result a Page not found (404). As seen from the urls.py, I have tried both using a regular expression and the newer Django 2.0+ syntax and both giving the same result. Is my mistake in the URL definition or am I not introducing the slug correctly to the view? -
Django: How to automatically set correct media folder permissions?
I am running a Django application using Apache webserver. The media directory is located in /var/www/app/media/. Owner of that directory is www-data:www-data, so that Apache can read / write to it. The problem now is that when I run ./manage.py migrate and a new sub-folder in the media directory is created when I add a new FileField to a model, the owner of that directory is the user running that migrate command and I have to fix the owner of that new folder, otherwise Apache can't write to it and I am getting a Permission denied error. How can I set permissions to the folder /var/www/media/that user www-data can write to any new subfolder, even when that subfolder is created by another user ? -
I am a newbie please help i keep getting error You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path
i keep getting this message when i run "git push heroku master" remote: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. remote: ! Error while running '$ python manage.py collectstatic --noinput'. Settings.py import django_heroku 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/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '########################################' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'pytalk.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'pytalk.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/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/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE … -
I get an error when i run python manage.py
I've been using django for a while whitout having any issues, i don't really know what i did by mistake, but now, some errors pop up when i try to run my server or to migrate or to type whatever command that comes after python manage.py ... Im using django 3.0.5 ( should be the latest version ) , and python 3.8.2. the error actually comes from some files written by default like 'init.py' 'autoreloader.py' 'runserver.py' ... i think it must be a confusion between the used versions.. Any help please? -
django channels for one to one video call setup
django-channels is awesome tools for realtime application. Looking for guide on video calling feature. I've searched in google, but nothing found very helpful. -
XHR - ajax - djnago - the data sent is not appearing in the server
here is my ajax code $.ajax({ type: "GET", url: "/post_data/", data, headers: { "Content-Type": 'application/json', "X-CSRFToken": csrftoken // 'Content-Type': 'application/x-www-form-urlencoded', }, success: function (data, status, xhr) { $('.msg').html("<h2>Contact Form Submitted!</h2><P>" + data) }, error: function (jqXhr, textStatus, errorMessage) { $('p').append('Error:' + textStatus + ' :: ' + errorMessage); } }); the global scope has a variable "data". here is the data sent the python(django) url.py file from django.urls import path from django.conf.urls import url from . import views from django.views.decorators.csrf import requires_csrf_token from django.http import HttpResponse @requires_csrf_token def post(request): print(request.POST) print(request.GET) return HttpResponse("response from the server") urlpatterns = [ path("", views.post_data, name="home"), path('post_data/', post) ] my server's console logging ------------- What is the problem with my code? -
forking django-oscar views shows an error
I forked customer app , to add a tab in http://oscar/accounts/...(example products) to edit/show catalogue Views (Dashboard>Catalogue) Error that I get to use that view is django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I used views with the same method for payment checkout, but this one runs into errors. #yourappsfolder.customer.apps.py import oscar.apps.customer.apps as apps from oscar.apps.dashboard.catalogue import apps as dapps from django.views import generic from django.conf.urls import url from oscar.core.loading import get_class from .views import ProductListView class CustomerConfig(apps.CustomerConfig): name = 'yourappsfolder.customer' def ready(self): super().ready() self.extra_view =ProductListView def get_urls(self): urls = super().get_urls() urls += [ url(r'products/',self.extra_view.as_view(),name='Products'),] return self.post_process_urls(urls) This is the view I copied from oscar.apps.dashboard.catalogue #yourappsfolder.customer.views from django.shortcuts import render from django.http import HttpResponse # Create your views here. from django.views import generic from oscar.apps.dashboard.catalogue.views import ProductListView as UserProductListView class ProductListView(UserProductListView): def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx['form'] = self.form ctx['productclass_form'] = self.productclass_form_class() return ctx def get_description(self, form): if form.is_valid() and any(form.cleaned_data.values()): return _('Product search results') return _('Products') def get_table(self, **kwargs): if 'recently_edited' in self.request.GET: kwargs.update(dict(orderable=False)) table = super().get_table(**kwargs) table.caption = self.get_description(self.form) return table def get_table_pagination(self, table): return dict(per_page=20) def filter_queryset(self, queryset): """ Apply any filters to restrict the products that appear on the list """ return filter_products(queryset, self.request.user) def get_queryset(self): """ … -
POSTGRES 12.2 installer won't run on Windows
Downloaded PostgreSQL Version 12.2 (from https://www.enterprisedb.com/downloads/postgres-postgresql-downloads). When I run postgresql-12.2-2-windows-x64.exe, it shows Postgre logo for couple seconds and immediately disappears. Tried following and there is no change: Restarted laptop Tried previous version: 11.7 As I'm on employer issued laptop, stopped their firewall "Umbrella Roaming Client" from Services in Task Manager Found same issue reported on Microsoft community (https://answers.microsoft.com/en-us/windows/forum/all/postgres-101-installer-didnt-run/58a0d2d4-e681-4aba-95c1-111b476053d0), however the response listed there is of no help at all. Specs: Windows 10, x64 based PC -
How to get the field values as a dictionary
I have create a model Role as shown below. class Role(models.Model): role_name = models.CharField(max_length=255, unique=True, blank=False) I am trying to get the role_name of the record which has primary_key=2. So, far I have tried to do it like this - Role.objects.get(pk=2) But the problem with this is it returns the id of the instance i.e 2 which doesn't make sense as I already have it. So, I tried again using values and filter like this - Role.objects.values('role_name').filter(pk=2) Now, in this case it does return me the role_name but as an array of objects. As, the database table Role will always have one record I am expecting it to return a dictionary or just the value of it. -
how to check if Django is installed in anaconda?
C:\Users\JShaikh>py -m django --version 'py' is not recognized as an internal or external command, operable program or batch file. -
Angle Brackets in JSON
I am following the solution posted on: Sum database on location and time However, when I do a print(locations.values()) this is returned: ('Liberty City', <Location: 07:00 116 Liberty City 08:00 120 Liberty City ...>)]) What does the angle brackets (<>) means? And how can I access the values? -
Modified urlpatterns in django
I modified url in django, i can use tag {% url 'student-register' %} in template but when i call {% url 'student-reg' %} it return error reverse-not found, anyone can describe what happened ? this is my code : from django.urls import path, include from .views.home import * from .views.teacher import * urlpatterns = [ path('', ViewHomePage.as_view(), name='home'), path('logout', LogoutAccount.as_view(), name='logout'), path('teacher/', include(([ path('', ViewTeacherHome.as_view(), name='teacher'), path('student-register', ViewStudentRegister.as_view(), name='student-register'), ], 'exam'), namespace='teacher')), path('student/', include(([ path('', ViewTeacherHome.as_view(), name='student'), path('student-reg', ViewStudentRegister.as_view(), name='student-reg'), ], 'exam'), namespace='student')) ] -
Href not working when im logged in Django
I did the authentication system and when i'm logged in the Hyperlinks are not working anymore and when i put the cursor on it , it shows the correct path that it will be rendered to . When i change the URL from browser's URL bar it goes to the page i want... -
Django ClearableFileInput not rendering Properly
I am using cripsy forms Model class CadreAck(models.Model): cadre = models.ForeignKey('common.Cadre',on_delete=models.CASCADE,null=True,blank=True) dtg = models.DateTimeField(verbose_name='Datetime',null=True,blank=True) comments = models.TextField(null=True,blank=True) attachment = models.FileField(upload_to=cadre_ack_path,blank=True) Form class CadreAckForm(forms.ModelForm): class Meta: model = common_models.CadreAck exclude = ['dtg'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit')) self.helper.form_method = 'POST' Template {% extends "cadreportal/base.html" %} {% load crispy_forms_tags %} {% load render_table from django_tables2 %} {% load querystring from django_tables2 %} {% load bootstrap4 %} {% block content %} <h1> {{ header }} </h1><hr> {% if sub_header %} <h3>{{ sub_header }}</h3><hr> {% endif %} {% if sub_sub_header %} <h3>{{ sub_sub_header }}</h3><hr> {% endif %} {% if form%} <h3> {{ form_header }} </h3> {% crispy form %} {% endif %} {% endblock content %} The Choose file box is covering up the attachment upload and clear checkbox (See Snip) Output -
Django Celery worker received task but does not execute the task
I am trying to use Celery for background working of a website. Celery worker receives tasks from celery beat or python manage.py shell. But it does not proceed after Received task process. My code is as follows. task.py from __future__ import absolute_import, unicode_literals from celery import Celery, shared_task @shared_task def check(): print("I am checking execution") celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoSample.settings') app = Celery('DjangoSample') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() Celery worker log is like this. (venv) C:\Users\doo56\PycharmProjects\untitled1\DjangoSample>celery -A DjangoSample worker -l info -------------- celery@LAPTOP-ONN7RQ0R v4.4.2 (cliffs) --- ***** ----- -- ******* ---- Windows-10-10.0.17134-SP0 2020-04-14 22:11:33 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: DjangoSample:0x1a6600d6b48 - ** ---------- .> transport: redis://localhost:6379/0 - ** ---------- .> results: - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . catalog.tasks.check [2020-04-14 22:11:34,101: INFO/MainProcess] Connected to redis://localhost:6379/0 [2020-04-14 22:11:34,134: INFO/MainProcess] mingle: searching for neighbors [2020-04-14 22:11:35,240: INFO/MainProcess] mingle: all alone [2020-04-14 22:11:35,322: WARNING/MainProcess] c:\users\doo56\pycharmprojects\untitled1\venv\lib\site-packages\celery\fixups\django.py:203: UserWarning: Us ing settings.DEBUG leads to a memory leak, never use this setting in … -
How effectively extracts value from function (python) and pass to context (Django)
I have function in seperate django file function.py. My function consists of lenthy calculations whiuch i then pass to views. there are functions inside the main function a(). This is how to pass value ( this is shortest version to pass you idea os what i am trying to say). def a(): x=3 y=4 z=6 def b(): x1=x+1 return x1 def c(): y1=y+1 return y1 def d(): z1=z+1 return b(), c(), d() def home(request): abc=a() context={'value1':abc[0],'value2':abc[1],'value3':abc[2],} print(value1) This how i pass value. Is this efefctive way or there are more efficient ways to pass values form the function as as so far i manually have to pass to the context in views through indexing as i did. What is your recomendation to ease my work? -
I want to use inline for loop in the following way
anyone please correct me in writing for loop in Django template , see below code to understand what im trying to do {% for item in items and for quantity in quantities %} -
How to remove "No Password set" on my Django template for editing a profile
On my Django template when a user logs in and edits there profile I have this weird-looking message that reads "No password set. Raw passwords are not stored, so there is no way to see this user's password, but you can change the password using this form." How can I prevent this from displaying on my template? below is my code forms.py class EditProfileForm(UserChangeForm): member_id = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Member Id'})) first_name = forms.CharField(label='Firstname', required=False, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Firstname'})) last_name = forms.CharField(label='Lastname', required=False, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Lastname'})) email = forms.CharField(label='Email*', widget=forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Email'})) phone1 = forms.CharField(label='Phone Number 1*', widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Phone Number 1'})) phone2 = forms.CharField(label='Phone Number 2', required=False, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Phone Number 2'})) class Meta(): model = User fields = ('member_id', 'first_name', 'last_name', 'email', 'phone1', 'phone2') -
Use custom model method in custom django queryset
A custom Model queryset takes one of the model's field to make some calculations, but now I need to get that field through a custom model method where I make some adjustment's according to the request.user's timezone. The function takes user as a parameter. Here are some code snippets: queryset: break_time_start = F("machine_break_time__break_time_start") model function: def break_time_start_user(self, user) -> datetime.time: utc_time = self.break_time_start_utc.replace(tzinfo=self.timezone) date = datetime.datetime.combine(datetime.date.today(), utc_time) return localtime(date, user.timezone).time() How can I use this custom method in my custom queryset? -
Convert a python script which based on Paramiko into Django
I`ve put a place a python script that take as input: IP Address txt file (First Name Last Name MAC_Address) Boolean yes or no (would like to assign the main number to a receptionist or just to a static phone) Is it possible if someone can guide me how i can have this integrated into Django (ive already started a Django project but im not finding a way to model my python script into django ...do i just copy and paste into views.py or models.py ....) Thanks !