Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin - Conditionally show/hide fields
I have a very similar problem to what is described in this question. I have implemented the solution of multiple fieldsets and it works quite well. However, I run into a problem when I try to add fields that belong to multiple fieldsets: (admin.E012) There are duplicate field(s) in 'fieldsets[2][1]'. item_field2 is required in foo and bar, but not baz (hence it cannot be in the initial fieldset). I can see how this is an issue, but not sure of how to get around it. admin.py from django.contrib import admin @admin.register(Item) class ItemAdmin(admin.ModelAdmin): fieldsets = ( # This first fieldset is always displayed (None, { 'classes': ('item',), 'fields': ('item_type') # type is a select input with 'foo' and 'bar' options }), # Only one of the below fieldsets are displayed, depending on which item_type is chosen from the above select input (None, { 'classes': ('foo',), 'fields': ('item_field1, item_field2') }), (None, { 'classes': ('bar',), 'fields': ('item_field2, item_field3') }), (None, { 'classes': ('baz',), 'fields': ('item_field4') }) ) class Media: js = ('admin.js',) admin.js window.addEventListener('load', function() { (function($) { var selectField = $('#id_item_type') var foo = $('.foo'); var bar = $('.bar'); var baz = $('.baz'); function toggleVerified(value) { if (value === '1') { … -
Django Cannot make makemigrations
i am trying to makemigrations to uploadExcel but an error shows up that says ValueError: Could not find function wrapper in uploadExcel.models. this is the code I am using in my uploadExcel.models. from django.db import models import os def path_and_rename(path): def wrapper(instance, filename): ext = filename.split('.')[-1] if instance.pk: filename = '{}.{}'.format(instance.pk, ext) else: filename = '{}.{}'.format('data', ext) return os.path.join(path, filename) return wrapper class ExcelUploadModel(models.Model): file_name = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to=path_and_rename('test/')) uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.file_name def delete(self,*args, **kwargs): self.document.delete() super().delete(*args, **kwargs) any help will be very appreciated thank you best, -
Test server with Django returns different AJAX results than with Apache server
Right now I am learning how to do AJAX calls within my Django project. Right now I have a html page which makes a AJAX call to a page that returns a JSON response. My problem is that when I go to the ajax page, hosted by Apache, returning the response, the response is that of an old configuration of the site. When I use the test site with python manage.py runserver, the ajax value returns corresponds to what is defined in the views.py file. The ajax response from the site page via Apache is unresponsive to my changes to the code while the test server is. I do not understand why this is. This is reminiscent of a previous problem I encountered where there was a redirect in my url.py file which was unresponsive to changes in the same way. It did start to work and I thought it was because I cleared my browser history. That was not helpful in this case. This is my view which contains the AJAX response def validate_username(request): username = request.GET.get('username', None) data = { 'is_taken': User.objects.filter(username__iexact=username).exists() } if data['is_taken']: data['error_message'] = 'A user with this username already exists.' return JsonResponse(data) I know … -
Getting an error while trying to integrate django-postman in my project?
I had downloaded django-postman from Bitbucket and in my projects installed apps I had added postman and when I run from django.utils import six ImportError: cannot import name 'six' Getting this error please help me out Python version : Python 3.6.8 (default, Jan 14 2019, 11:02:34) Django Version : django.VERSION (3, 0, 1, 'final', 1) -
Validating _multiple_ inline objects at once and returning an error via add_error if it fails
There seems to be plenty of examples about validating a single model, but I am trying to validate across multiple models encapsulated in a TabularInline subclass using save_related on the parent. I am trying to add an error (under no conditions in the example, but that is to be changed) but I can never get the error to bubble up and return in a user friendly way, def save_related(self, request, form, formset, change): for forms in formset: for f in forms.forms: f.add_error(None, 'foo') The following code allow me to save all the objects in question despite trying to add errors to the form. I suspect at this point the models might have already been saved and thus the form validation is being ignored. I am trying to validate these models pre saving. -
How to pass instance of a model to another model in Django?
I'm trying to populate dbkey column from parent table on the form, where foreign table values are input. WHile providing a value I get the following error - "csg_ch_servers.DBParentCustomerKey" must be a "csg_ch_customer" instance. Could someone help me out? model.py class csg_ch_customer(models.Model): DBKey=models.AutoField(primary_key=True) CustomerName=models.CharField(max_length=100,unique=True) class Meta: db_table="csg_ch_customer" def __unicode__(self): return self.DBKey def __init__(self): return self.DBKey class csg_ch_servers(models.Model): DBKey=models.AutoField(primary_key=True) DBParentCustomerKey=models.ForeignKey(csg_ch_customer,on_delete=models.CASCADE) class Meta: db_table="csg_ch_servers" def __str__(self): return self.DBParentCustomerKey def __unicode__(self): return self.DBParentCustomerKey form.py class csg_ch_customer_form(forms.ModelForm): class Meta: model = models.csg_ch_customer fields = "__all__" class csg_ch_servers_form(forms.ModelForm): class Meta: model = models.csg_ch_servers fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['DBParentCustomerKey'].queryset = models.csg_ch_customer.objects.values_list('DBKey', flat=True) views.py def register_ser(request): form=Aforms.csg_ch_servers_form() if request.method == "POST": form=Aforms.csg_ch_servers_form(request.POST) if form.is_valid(): form.save() return redirect('Admin/NewServer.html') else: return render(request,'Admin/NewServer.html',{'form':form}) return render(request,'Admin/NewServer.html',{'form':form}) -
Query with two reverse relationships in Django
If I have these Django models: class ModelA(Model): pass class ModelB(Model): a = ForeignKey(ModelA, ...) d = ForeignKey(ModelD, ...) r = IntegerField() q = IntegerField() class ModelC(Model): a = ForeignKey(ModelA, ...) d = ForeignKey(ModelD, ...) r = IntegerField() class ModelD(Model): pass How can I do a Django ORM query equivalent to this: select ModelB.q, ModelA.id, ModelD.id from ModelA join ModelB on ModelB.a_id=ModelA.id left join ModelC on (ModelC.a_id=ModelB.a_id and ModelC.r=ModelB.r and ModelC.d_id=ModelB.d_id) join ModelD on ModelB.d_id=ModelD.id where ModelC.id is null I.e. get ModelBs whose fields don't match any ModelCs, where both ModelB and ModelC have foreign keys to two other models. -
how can I return all object's id and placed in my_result objects? [django]
when I submit this form always returns to me the value of id 1 only and when I tried to replace another value I wrote 2 has returned to me this value indeed. then I understood that this loop process doesn't work and I knew that because of (return). so, I need to know how can I return all object's id and placed in my_result objects views.py from django.shortcuts import render from .models import Section, Question, Result from django.http import HttpResponseNotFound def index(request): text = "this is from views of exam app!" return render(request, 'exam/index.html', {'text': text}) def section_list(request): try: sections = Section.objects.all() except: return HttpResponseNotFound("Error") return render(request, 'exam/section.html', {'portals': sections}) def my_question(request, q_id): sections = Section.objects.get(id=q_id) template_name = 'exam/question.html' try: answer = request.POST['answer'] for result in Result.objects.all(): result_id = result.result_question_id my_result = Result.objects.filter(id=result_id) return render(request, template_name, {'repr': repr(my_result)}) except: return render(request, template_name, {'sections': sections, 'error_message': 'You have to select one of the following answer'}) return render(request, template_name, {'sections': sections}) urls.py from . import views from django.urls import path from django.conf.urls import url app_name = "exam" urlpatterns = [ # /index/ path('', views.index, name="index"), # /index/section/ path('portal/', views.section_list, name="portal"), # /index/question/10/ path(r'question/<int:q_id>/', views.my_question, name="question"), ] models.py from django.db import models … -
AttributeError: module 'app.management.commands.api' has no attribute 'Command'
I have a file to fetch info from a API (UK Company House). To test I have import requests r = requests.get('https://api.companieshouse.gov.uk/company/00002065', auth=('xxxxx', '')) print(r.text) It works and produces the data, but then after the data I get the following error message AttributeError: module 'app.management.commands.api' has no attribute 'Command' Why is this and how do I resolve? -
django // Raw query must include the primary key
Python 3.6 Django 2.2.3 Mariadb I am developing a web program using Django that displays various statistics. Created "models.py" by "inspectdb" from an existing MariaDB database. I'm trying to use "Raw" queries because of mixed queries from many tables However, the following error occurs. django.db.models.query_utils.InvalidQuery: Raw query must include the primary key Mariadb tables # table : user uid(int(10), primary, auto_increment) email(varchar(100)) created_at(timestamp) # table : user_logs seq(int(11), primary, auto_increment) uid(int(10)) acct_type(tinyint(2)) log_type(varchar(20)) created_at(timestamp) #query SELECT years, months, sum(download) AS download, sum(countin) AS user_regist, sum(countout) AS user_login FROM ( SELECT YEAR(DATE_ADD(created_at, INTERVAL 9 HOUR)) AS years, MONTH(DATE_ADD(created_at, INTERVAL 9 HOUR)) AS months, count(1) AS `countin`,0 AS `countout`, 0 AS 'download' FROM user `in` WHERE ( DATE_ADD(created_at, INTERVAL 9 HOUR) >= '2019-09-01 00:00:00' AND DATE_ADD(created_at, INTERVAL 9 HOUR) < '2020-01-20 00:00:00') GROUP BY `years`, `months` UNION SELECT YEAR(DATE_ADD(created_at, INTERVAL 9 HOUR)) AS years, MONTH(DATE_ADD(created_at, INTERVAL 9 HOUR)) AS months, 0 `countin`, count(1) AS `countout`, 0 AS 'download' FROM user_logs `out` WHERE ( acct_type = 1 AND log_type = 'login' AND DATE_ADD(created_at, INTERVAL 9 HOUR) >= '2019-09-01 00:00:00' AND DATE_ADD(created_at, INTERVAL 9 HOUR) < '2020-01-20 00:00:00') GROUP BY `years`, `months` ) `regist_and_login_monthly` GROUP BY years, months; query resulit models.py class User(models.Model): uid … -
Is it worth dropping stale columns on a large data set?
I have a relatively large data set in a table with about 60 columns, of which about 20 have gone stale. I've found a few posts on dropping multiple columns and the performance of DROP COLUMN, but nothing on whether or not dropping a bunch of columns would result in a noticeable performance increase. Any insight as to whether or not something like this could a perceptible impact? -
Calling a Django view function from an angularJS frontend
I'm trying to call a simple function from the views.py of a django app named class. Basically, I want to click on a button and call the sayHi view function to make it print some text to the console. I've tried many suggested approaches I came accross, but I failed. What should I add to the corresponding HTML file .../templates/class/index.html to trigger said function? Maybe it would be easier to achieve by targeting sayHello() whithin ClassView? If yes, how? I already use a little bit of JQuery in my project. Anyway, here's the views.py: #class view class ClassView(viewsets.ModelViewset): ... def sayHello(): print('ClassView should print this to the console.') #function view def sayHi(): print('sayHi view should print this to the console.') here is routes.py (using the same Template and Controller for both views): angular.module('MyApplication') .config(function($stateProvider, $urlRouterProvider, $locationProvider){ $urlRouterProvider.otherwise('/'); $stateProvider .state('class', { url:'/class', templateUrl: "app/assets/templates/class/index.html", controller: "ClassIndexController" }) .state('hello', { url:'/class', templateUrl: "app/assets/templates/class/index.html", controller: "ClassIndexController" ... here's the snippets from urls.py ... router.register(r'class', ClassView) router.register(r'hello', sayHi, base_name='Hi') ... -
Django ListView is not paginating despite paginate_by being set
Django v3.0 View: class UnreadListView(ListView): """ View to show all unread feed items """ model = FeedItem template_name = 'rss/unread_feeds.html' paginate_by = 15 def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['unread_feeds'] = FeedItem.objects.filter( is_archived=False).order_by('-published') return context When I print if paginated in template it comes back as true. I am not sure how to proceed. -
Tempus Dominus Datepicker widget not cloning properly in Django Model Formset when using Dynamic Formset Library
I have a model formset set up using Django Dynamic Formset along with Crispy Forms and the Tempus Dominus datepicker library. It's a simple formset for users to add operating expense line entries -- date, category, description, and amount. My datepicker works correctly with a non-dynamic formset. However, when using dynamic formsets and a new form is added, the widget ends up targeting the last form in the formset that it was cloned from and not the current form (https://imgur.com/a/2GFYZ90). Instead of incrementing properly (i.e. form_3, form_4, form_5, etc.), it just refers to the last form of the formset (i.e. form_2) before the new ones are added. As a result, if I try to toggle the datepickers in any of the dynamically added forms, it just triggers the one in form_2. Regular text fields clone correctly without any problems. As you can see in lines 19-23 of opex.html, I'm attempting to implement the destroy and re-initialize functions as suggested by some older Stack Overflow posts (1, 2, and 3) but I'm a JS noob so I'm not sure how to proceed. models.py class OpEx(models.Model): GEN_EXP = 'GE' OFFICE_SUP = 'OS' NR_EXP = 'NR' CATEGORY_CHOICES = [ (GEN_EXP, 'General Expenses'), (OFFICE_SUP, … -
Django ImageField uploads image but clicking the link results in a 404 error
I have a Django installation with a BlogPost.image field: class BlogPost(models.Model): title = models.CharField(max_length=100) content = models.TextField() publishDate = models.DateTimeField('date published') author = models.ForeignKey(User,on_delete=models.PROTECT) image = models.ImageField(upload_to="images") The upload works correctly and the image is saved inside the images folder. But when I open django admin and edit the record, there is a currently link: Currently: images/JPEG-afbeelding.jpeg which points to: http://127.0.0.1:8000/admin/blog/blogpost/1/change/images/JPEG-afbeelding.jpeg When clicking the link, the following error shows up: Blog post with ID “1/change/images/JPEG-afbeelding.jpeg” doesn’t exist. Perhaps it was deleted? -
Update a Django object user accesses a specific URL
I'm working on a program that sends yes/no questions via an email to employees. I'd like to make it possible for them to 'respond' to the email by clicking a link that would then update a model object once that link is visited. I understand how to do this if they were to submit a form, but I don't quite understand how this could be done (if it can be done) via simply going to a URL. If someone could just point me in the right direction, it would be greatly appreciated. I'm relatively new to Django, so I apologize if I did not word this question correctly. -
Django: use ListView and a profile function view
I want to use a ListView I defined in an app (main) in a profile template that is defined by a function view in another app (users). I am using a profile.html template to show user info and activities and I want to use the ListView for activities in that template. project/users: views.py @login_required def profile_view(request): if request.POST: user_form = UserUpdateForm(request.POST, instance=request.user) if user_form.is_valid(): user_form.save() return redirect('profile') else: user_form = UserUpdateForm(instance=request.user) context = { 'user_form': user_form } return render(request, 'users/profile.html', context) urls.py: path('profile/', profile_view, name='profile') project/main: views.py: class ActListView(LoginRequiredMixin, ListView): model = Activities template_name = 'users/profile.html' ordering = ['-date_created'] # order by newest first context_object_name = 'activities' paginate_by = 5 profile.html sample: <div class="navItem1"> <p>{{user.firstname}} {{user.lastname}}</p> </div> <div class="navItem2"> {% for a in activities %} <p>{{ a.title }}, {{ a.date_created }} {% endfor %} </div> I am not sure how to do this. Should I create a new class view and combine there? How do I do this? -
We're sorry, but something went wrong. The issue has been logged for investigation. Please try again later
I'm new on django and i'm trying to install django on Cpanel. I have installed it but when i'm accessing url it giving me following error. "We're sorry, but something went wrong. The issue has been logged for investigation. Please try again later." -
Sens of running threaded function to check the condition every 1h ? DJANGO
i was wondering if there is a sens of running special function on spearate thread to check the specific query. If return is true then delete it. I'm not sure if this is the way to deal with things like that in django. I'm working on cinema online booking and i want to delete all objects of booking if have not been confirmed until 30min before movie starts. -
Performant Way To Select Most Recent Item Per Group In Django / Postgres
I have a query performance issue that I'm trying to solve in Django. Environment: Django 2.2 Python 3.6 Postgresql 11 Example Models: class Location(models.Model): name = models.CharField(max_length=256) # ... class VendingMachine(models.Model): location = models.ForeignKey("MyApp.Location", on_delete=models.CASCADE) name = models.CharField(max_length=8) # ... class Vend(models.Model): vending_machine = models.ForeignKey("MyApp.VendingMachine", on_delete=models.PROTECT) vend_start_time = models.DateTimeField(db_index=True) # ... I am trying to get a list of the most recent Vends per VendingMachine. There are a couple approaches I've taken, but they either don't quite work in the setup and requirements that I have, or take WAY too long to execute. Version 1: Vend.objects.filter(pk__in=Subquery(Vend.objects.order_by().values('vendingmachine__location__id', 'vendingmachine__id').annotate(max_id=Max('id')).values('max_id'))) This version is super fast. However, it only works if the Vend IDs are in chronological order. The data is inserted into the database in a random order, so this doesn't work. Version 2: Vend.objects.all().order_by('vendingmachine_id', '-vend_start_time').distinct('vendingmachine_id') This version takes 12-15 seconds to execute, and since since it is being run through a paginator, the query is executed twice (once for the count, the second time to get the objects and slicing), so the page takes about 30 seconds to load which is way too long. The other issue with this version is that the results can't be sorted (except in Python) once they … -
Counter animation for Django variable
I want to do one of those cool dashboard counter animations using my Django variables. My code isn't rendering any numbers yet so I'm doing something wrong. Something like this if what I'm after: Here's my code so far: <div class="row"> <div class="col-lg-3 col-sm-6"> <div class="card m-2 p-4"> <i class="counter-icon fa fa-users"></i> <h2 class="users-count"></h2> <h3 class="count-label">Users</h3> </div> </div> <div class="col-lg-3 col-sm-6"> <div class="card m-2 p-4"> <i class="counter-icon fa fa-handshake-o"></i> <h2 class="dealers-count"></h2> <h3 class="count-label">Dealers</h3> </div> </div> <div class="col-lg-3 col-sm-6"> <div class="card m-2 p-4"> <i class="counter-icon fa fa-address-card"></i> <h2 class="staff-count"></h2> <h3 class="count-label">Employees</h3> </div> </div> <div class="col-lg-3 col-sm-6"> <div class="card m-2 p-4"> <i class="counter-icon fa fa-eye"></i> <h2 class="visitors-count"></h2> <h3 class="count-label">Visitors Today</h3> </div> </div> </div> <script> document.addEventListener("DOMContentLoaded", () => { function counter(id, start, end, duration) { let obj = document.getElementsByClassName(id), current = start, range = end - start, visitors_range = 11 - start, increment = end > start ? 1 : -1, step = Math.abs(Math.floor(duration / range)), timer = setInterval(() => { current += increment; obj.textContent = current; if (current == end) { clearInterval(timer); } }, step); } counter("users-count", 0, {{users.count}}, 3000); counter("dealers-count", 100, {{dealers.count}}, 2500); counter("staff-count", 0, {{staff.count}}, 3000); counter("visitors-count", 0, {{visitors.count}}, 3000); }); </script> -
Editing django formsets: TypeError: argument of type 'HTML' is not iterable
I'm trying to learn how formsets work. Essentially I have a form 'Recording' and a form 'geo'. I want to have both forms render on a page, and submit with a single button. This is because depending on the url, i always want to render Recording but I sometimes want to render geo, and other times geo2. Currently I have the forms displaying correctly on a create view. Single submit button, the data is saved correctly. My problem is the edit view. In my edit view from views.py below when I pass instance = self.object into the context for geo_metadata, and I go to the edit view in the browser - the form is correctly populated with all existing data. However, when I try to submit from this edit view I get hit with: TypeError at /projects/1/recordings/16/edit/ argument of type 'HTML' is not iterable Request Method: POST Request URL: http://localhost:5000/recordings/16/edit/ Django Version: 2.2.9 Exception Type: TypeError Exception Value: argument of type 'HTML' is not iterable Exception Location: C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\crispy_forms\bootstrap.py in <genexpr>, line 235 Python Executable: C:\Users\user\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.1 Python Path: ['C:\\Development\\metadata webapp\\src', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\user\\AppData\\Roaming\\Python\\Python37\\site-packages', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages'] Server time: Wed, 22 Jan 2020 22:07:55 +0000 argument of type 'HTML' … -
Access unicode key of dictionary in Django Template with u''
I am using Django to build a app that pulls information using APIs, the APIs send back dictionary with unicode keys when print out it is: u'status', u'icd9_codes' So the problem is that when in template, I cannot access it, for example, using {{ appointment.status }} because it is unicode string with prefix like u', is there any solution for it? Thank you! -
Django Recaptcha returning assignment error
I am trying to implement Django Recaptcha using this package: https://github.com/praekelt/django-recaptcha This is my forms.py class SignupForm(forms.ModelForm): captcha = ReCaptchaField(widget=ReCaptchaV2Invisible) name = forms.CharField(widget=forms.TextInput) lastname = forms.CharField(widget=forms.TextInput) password = forms.CharField( widget=forms.PasswordInput) confirmpassword = forms.CharField( widget=forms.PasswordInput ) email = forms.EmailField( error_messages={ 'unique': pgettext_lazy( 'Registration error', 'This email has already been registered.')}) According to the documentation or as I saw it, this is all that is required. But the post request for the form doesn't work. I get this message under my server logs: UnboundLocalError: local variable 'redirect_url' referenced before assignment The error message refers back to my views.py code (redirect_url = LOGIN_URL) which is below: def signup(request): form = SignupForm(request.POST or None) if form.is_valid(): form.save(request) if settings.EMAIL_VERIFICATION_REQUIRED: msg = 'User has been created. Check your e-mail to verify your e-mail address.' messages.success(request, msg) redirect_url = LOGIN_URL else: password = form.cleaned_data.get('password') email = form.cleaned_data.get('email') user = auth.authenticate( request=request, email=email, password=password) if user: auth.login(request, user) messages.success(request, _('User has been created')) redirect_url = request.POST.get('next', settings.LOGIN_REDIRECT_URL) return redirect(redirect_url) ctx = {'form': form} return TemplateResponse(request, 'account/signup.html', ctx) I should add I have added my recapctcha keys to settings.py Any help is really appreciated. -
Get duplicates in a one-to-many relationship - Django
Let's say we have 3 models: # profile model class Profile(models.Model): first_name = models.CharField(max_length=100) # account model class Account(models.Model): profile = models.ForeignKey(Profile) account_number = EncryptedCharField(max_length=20, null=True, blank=True) # banana account model class BananaAccount(models.Model): bank_account = models.ForeignKey(Account, null=True, blank=True) Right now multiple BananaAccounts can share the same Account. How can I query, more precisely filter, for all BananaAccounts that have the same Account? I tried: BananaAccount.objects.values('bank_account').annotate(no_of_accounts=Count('bank_account')).filter(no_of_accounts__gt=1)