Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework exception_handler returns ".accepted_renderer not set on Response"
I am trying to come up with a dynamic check for a Django Rest Framework Class Based View. I've written a decorator that takes some object to check and an exception to raise if that object matches some condition. In this example, the object is a hard-coded string. But in the real use case, it is dynamic and based on the request itself (something like resolve(request.path).kwargs.get("thing")). Here is some code: import functools from django.utils.decorators import method_decorator from rest_framework import generics from rest_framework.exceptions import APIException from rest_framework.views import exception_handler def check_thing(thing_to_check, exception_to_raise): def _decorator(view_func): @functools.wraps(view_func) def _wrapper(request, *args, **kwargs): if thing_to_check == "bad_thing": exception_response = exception_handler(exception_to_raise, {}) # DOES "exception_response" NEED TO HAVE ".accepted_renderer" SET ? return exception_response return view_func(request, *args, **kwargs) return _wrapper return _decorator @method_decorator( check_thing( "some_dynamic_thing", APIException("you can't do stuff with this thing!") ), name="dispatch" ) class MyListView(generics.ListAPIView): queryset = MyModel.objects.all() When thing_to_check == bad_thing is True I get the following error: AssertionError: .accepted_renderer not set on Response Any suggetions? -
Error installing Mysql and connect to Django
I try to connect MySQL on my django project, but I still have error : django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? For more information I use Fedora 31, virtual env in python3.7.7, and when I try to install Mysql pip3 install mysql, mysql-python, pymysql... ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-h723r47l/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-h723r47l/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-jqp83cjt/install-record.txt --single-version-externally-managed --user --prefix= --compile --install-headers /home/carthur/.local/include/python3.7m/mysqlclient cwd: /tmp/pip-install-h723r47l/mysqlclient/ Complete output (31 lines): running install running build running build_py creating build creating build/lib.linux-x86_64-3.7 creating build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.7/MySQLdb creating build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.linux-x86_64-3.7 creating build/temp.linux-x86_64-3.7/MySQLdb gcc -pthread -Wno-unused-result -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Dversion_info=(1,4,6,'final',0) -D__version__=1.4.6 -I/usr/include/mysql -I/usr/include/mysql/mysql -I/usr/include/python3.7m -c MySQLdb/_mysql.c -o build/temp.linux-x86_64-3.7/MySQLdb/_mysql.o … -
How To Change A Label Class In Django Crispy Forms
I am wanting to create a bootstrap themed togglebox with crispy forms, but the toggle box displays with a checkbox inside it. In order to find out why I opened the page in Chrome and using inspect, deleted the class from the label tag (custom-control-label below) which removed the inner checkbox leaving just the bootstrap togglebox as I wanted. So my question is how can I remove a class from a cripsy forms field? forms.py completed = forms.BooleanField(label='Have you completed it?', required=False, widget=forms.CheckboxInput(attrs={})) generated html: <div class="form-group"> <div id="div_id_completed" class="custom-control custom-checkbox"> <input type="checkbox" name="completed" class="checkboxinput custom-control-input" id="id_completed" checked=""> <label for="id_completed" class="custom-control-label"> Have you completed it </label> </div> </div> Thank you. -
Why am i getting Application Error using Heroku?
i pushed my Django project to Heroku server and did migrations yet still i am getting this error APPLICATION ERROR SCREENSHOT and when i checked logs this is what i see -
How to cache view for all users in Django
I'm trying to use a Memcached instance of AWS ElastiCache with a Django project. It seems to be caching a view for a user, but if you come in on a different PC, it isn't cached until called from that PC (or same PC with different browser). I'm not sure what I've got wrong. Within settings.py I have CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': os.environ.get('CACHE_LOCATION','127.0.0.1:11211'), } } MIDDLEWARE = [ 'core.middleware.DenyIndexMiddleware', 'core.middleware.XForwardedForMiddleware', 'core.middleware.PrimaryHostRedirectMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.redirects.middleware.RedirectFallbackMiddleware', 'masquerade.middleware.MasqueradeMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.sites.middleware.CurrentSiteMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', 'cms.middleware.utils.ApphookReloadMiddleware', ] I've then cached the views using cache_page path('<str:service_type>/<str:location>/', cache_page(60*60)(views.canonical_search), name="canonical-search"), How do I cache the site so that the page is cached irrespective of the user? -
ModelForm returns None even fields has value
I've been searching of why modelforms fields model returns None even it has a value given in the fields. Form class GoodMoralSettingForm(CrispyFormMixin, forms.ModelForm): class Meta: model = Student fields = [ "requestor", "good_moral_certificate", "good_moral_remarks", "good_moral_purpose" ] def __init__(self, *args, **kwargs): self.student = kwargs.pop('student', None) super(GoodMoralSettingForm, self).__init__(*args, **kwargs) student = Student.objects.get(pk=self.student) self.fields['good_moral_certificate'].initial = student.good_moral_certificate def clean_good_moral_certificate(self): good_moral_certificate = self.cleaned_data.get('good_moral_certificate', None) good_moral_remarks = self.cleaned_data.get('good_moral_remarks', None) good_moral_purpose = self.cleaned_data.get('good_moral_purpose', None) requestor = self.cleaned_data.get('requestor', None) if requestor is None: requestor = "{requestor}" if good_moral_purpose is None: good_moral_purpose = "{good_moral_purpose}" if good_moral_remarks is None: good_moral_remarks = "{good_moral_remarks}" print("=========================") print(good_moral_remarks) # returns None print(good_moral_purpose) # returns None print(requestor) # returns data I suppose to get good_moral_certificate = good_moral_certificate.replace( "{requestor}", requestor).replace( "{remarks}", good_moral_remarks).replace( "{purpose}", good_moral_purpose ) return good_moral_certificate I try to clean that two fields but throws again a None, can someone help me where I did wrong? Really appreciate it -
What is the ideal way to patch values (save edits to server) from an Angular Form?
I am using Angular & Django. I have an Angular Form in which the user can create a "Bill" object. The object has has one to many relationship with "Bill Line Item". When a new Bill object is created, that gets saved to the server. The user also has the option to edit an existing Bill and its relevant Bill Line Items. So far, in my form: Bill Form: this.form = this._formBuilder.group({ date: new FormControl(null, [Validators.required]), dueDate: new FormControl(null, [Validators.required]), notes: new FormControl(''), payee: new FormControl(null, [Validators.required]), lineItems: this._formBuilder.array([]) }); The user can add Bill Line Items with this FormGroup, and these FormGroup line items get added to the lineItems FormArray in the Bill Form: createLineItem(): FormGroup { let fg: FormGroup = this._fb.group({ item: new FormControl(null), quantity: new FormControl(0), unitCost: new FormControl(0), weight: new FormControl(0), }); return fg; } Later on, the user can edit an existing Bill. A GET request is made on the Bill Django model with the relevant Bill Id. I have managed to populate all the FormControls with the correct values. After the user makes edits and I need to save/ patch/ partial_update the existing Bill object...what is considered good practice? My solutions: Option 1: My … -
How can i query with ManyToManyField?
If i know company_id, how can i call a query list department, each department have list user and each user has username and staff_id? class User(models.Model): username=models.CharField(max_length=40,unique=True) class Company(models.Model) name=models.CharField(max_length=100) users = models.ManyToManyField('User', through='User_Company',related_name="companies") class Department(models.Model) name=models.CharField(max_length=100) users = models.ManyToManyField('User', through='User_Department',related_name="departments") class User_Department(models.Model) user = models.ForeignKey('User', on_delete=models.CASCADE,related_name="ud_membership") department = models.ForeignKey('Department', on_delete=models.CASCADE,related_name="ud_membership") class User_Company(models.Model) user = models.ForeignKey('User', on_delete=models.CASCADE,related_name="uc_membership") company = models.ForeignKey('Company', on_delete=models.CASCADE,related_name="uc_membership") staff_id = =models.CharField(max_length=50) -
How to serve the static content in nginx + django + kubernetes?
I have a minikube running with the deployment of django app. Till today, we used server which django spins up. Now, I have added another Nginx container so that we can deploy django app cause I read django is not really for production. After reading some documentation and blogs, I configured the deployment.yaml file and it is running very much fine now. The problem is that no static content is being served. This is really because static content is in django container and not Nginx container. (Idk if they can share volume or not, please clarify this doubt or misconception) What will be the best way so I can serve my static content? This is my deployment file's spec: spec: containers: - name: user-django-app image: my-django-app:latest ports: - containerPort: 8000 env: - name: POSTGRES_HOST value: mysql-service - name: POSTGRES_USER value: admin - name: POSTGRES_PASSWORD value: admin - name: POSTGRES_PORT value: "8001" - name: POSTGRES_DB value: userdb - name: user-nginx image: nginx volumeMounts: - name: nginx-config mountPath: /etc/nginx/nginx.conf subPath: nginx.conf volumes: - name: nginx-config configMap: name: nginx-config I believe that server { location /static { alias /var/www/djangoapp/static; } } needs to be changed. But I don't know what should I write? … -
how to install adminlte template on my django app
i'm trying to install a template AdminLte to my new django app i create static folder (CSS & JS files) template folder (demo.html) media folder i add this code settings.py MEDIA_URL="/media/" MEDIA_ROOT=os.path.join(BASE_DIR,"media") STATIC_URL="/static/" STATIC_ROOT=os.path.join(BASE_DIR,"static") and also in settings.py template 'DIRS': [os.path.join(BASE_DIR,template)], in url.py urlpatterns = [ path('demo',views.showDemoPage), path('admin/', admin.site.urls), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)\ +static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) in views.py : def showDemoPage(request): return render(request,"demo.html") when i run it show me this errors: this my errors message -
How to send data to a multiple choice form?
When you want to send data to be updated just do: def MyView(request, pk): instance = get_object_or_404(Mymodel, id=pk) form = Myform(request.POST or None, instance=instance) But when I do this for a form that has a single field of multiple choices it goes wrong. forms.py class FormChoices(forms.Form): result = forms.MultipleChoiceField( choices=(MyModel.objects.values_list("id","name")), widget=forms.CheckboxSelectMultiple(), label="Select") views.py def MyViewChoices(request, pk): instance = MyModel.objects.values_list('id','name' ).filter(id=pk) form = FormChoices(request.POST or None, instance=instance) I get the following error: __init__() got an unexpected keyword argument 'instance' How can I send data to this form with a multiple choice field to show all items and those that have been registered appear marked? -
Loosing metadata when uploading or an image in Django Admin
I want to add a copyright notice into exif data of my displayed images. I'm using django-imagekit and piexif libraries. I can't manage to preserve nor enrich metadata of an image when I upload then process them in my Django admin. Here is my model : class Still(models.Model): image = ProcessedImageField(upload_to='images', processors=[ResizeToFit(1024)], format='JPEG', options={'subsampling': 0, 'optimize': True, 'quality': 85} ) img_th_watermarked = ImageSpecField(source='image', processors=[ResizeToFit(width=612), TextOverlayProcessor(), ExifCopyrightProcessor()], ) Here is the processor : def add_copyright_exif(image): copyright = "© {} my name".format(datetime.now().year) try: exif_dict = piexif.load(image.info["exif"]) except KeyError as k: exif_dict = {"0th":{}} exif_dict["0th"][piexif.ImageIFD.Copyright] = copyright exif_bytes = piexif.dump(exif_dict) new_image = image.copy() new_image.info["exif"] = exif_bytes print(new_image.info) return new_image class ExifCopyrightProcessor(object): def process(self, image): return add_copyright_exif(image) The print seems to display the correct info, other processors work fine, but metadata get lost on the way. I tried removing format option as well. I don't mind that metadata get lost at the ProcessedImageField step, but I should be able to add new info at the ImageSpecField step. Images and cached versions are stored on S3. Thanks in advance for your help. -
A django field with two fields. Need opinion
There is a scenario where I want to store two types of information for a field. For example, consider a field namely "name". This field should two types of the following information:- Boolean - to store whether the user wants this field to shown or not. Label - if the user wants to change the label to show. I was wondering to solve this by using a model. Any suggestions? -
Feedback Form Django
I’m finally tormented with the feedback form. As a result, it worked for me, but it only works on a separate page of the project, and I need to implement it in each page of the site so that it is displayed together with the rest of the content. This is not the first time I have encountered such a problem; I cannot display several models on one page at the same time. How this is implemented in the case of a separate page: views.py: def contact(request): form_class = ContactForm if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): contact_name = request.POST.get( 'contact_name' , '') contact_email = request.POST.get( 'contact_email' , '') form_content = request.POST.get('content', '') # Email the profile with the # contact information template = get_template('app/contact/contact_template.txt') context = { 'contact_name': contact_name, 'contact_email': contact_email, 'form_content': form_content, } content = template.render(context) email = EmailMessage( "New contact form submission", content, '', ['mail@mailer.com'], headers = {'Reply-To': contact_email } ) email.send() return redirect('contact') return render(request, 'app/contact.html', { 'form': form_class, }) in urls.py: ... path('contact/', views.contact, name='contact'), ... contact.html: <h1>Contact</h1> <form role="form" action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> forms.py: class ContactForm(forms.Form): contact_name = forms.CharField(required=True) contact_email = forms.EmailField(required=True) content = forms.CharField( … -
Can I restrict Endpoints with dry-yasg with this type of view?
I have the following in my views.py I've been reading the documentation and trying to work out is there a way to exclude certain endpoints for this view. from EoX.models import Vendor from rest_framework import viewsets from rest_framework import permissions from .serializers import VendorSerializer from url_filter.integrations.drf import DjangoFilterBackend from drf_yasg.utils import swagger_auto_schema from django.utils.decorators import method_decorator class VendorViewSet(viewsets.ModelViewSet): queryset = Vendor.objects.all() serializer_class = VendorSerializer permission_classes = [permissions.AllowAny] filter_backends = [DjangoFilterBackend] filter_fields = ['name',] I can exclude the view all together with schema=None I tried decorating it with @method_decorator(name='list', decorator=swagger_auto_schema( operation_description="description from swagger_auto_schema via method_decorator" )) and that changes the description of the 'get' endpoint. but trying @method_decorator(name='list', decorator=swagger_auto_schema(methods=['get'], operation_description="description from swagger_auto_schema via method_decorator" )) throws an error AssertionError:methodormethodscan only be specified on @action or @api_view views Is this a bug? or just not a supported feature, and is there a way to accomplish what I am trying? Many thanks. -
Docker-compose command: file not found
I want to initialize Docker for my Django project with postreSQL. I followed instrunctions from https://docs.docker.com/compose/django/ I also want to be sure that db runs before web so I use wait_for_db.sh. When I try to execute command docker-compose up I see following respond: web_1 | chmod: cannot access 'wait_for_db.sh': No such file or directory pipingapi_web_1 exited with code 1 Before I try to use "docker-compose run", I Change directory to project root. I tried also to write $ docker-compose run web django-admin startproject pipingapi . even though project was created before with venv. I guess its not exactly about .sh file because when I erase lines reffering to that file, Docker cant find manage.py then (look at command order in docker-compose.yml). I also tried to put code/ before wait_for_db.sh in docker-compose.yml but it did not work. My project tree: . L apienv/ L docker-compose.yml L Dockerfile L manage.py L project/ L README.md L requirements.txt L restapi/ L wait_for_db.sh Dockerfile: FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ RUN apt-get install -yq netcat docker-compose.yml version: '3' services: db: image: postgres:12.3 volumes: - /var/lib/postgresql/data env_file: - ./.env web: build: … -
how can we upload csv file to django project and fetch data after certain time
I want to upload a csv file from a Django-project folder and fetch data from it and save to table, this should happened after every 24 hour. -
Arrange Django Models Column in Template
I have a Model object containing images field. Now I want to get the images in template by a sequence like one image floating left and another one floating right order from last entry. models.py # models.py class Image(models.Model): icon = models.ImageField(upload_to='static/img') views.py # views.py def index(): image = Image.objects.latest('id') return render(request, 'index.html', {'images': image}) index.html {% for image in images %} <div class="float-left"> {{ image }} </div> <div class="float-right"> {{ image }} </div> {% endfor %} Assume all imports are ok. -
Django: django.core.exceptions.FieldError: Cannot resolve keyword 'date2' into field
I have a model, which has many attributes, two of which are: date2 = models.DateField(null=True, blank=True) date1 = models.DateTimeField(null=True, blank=True) I try to use the following query in my django view: q = MyModel.objects.filter(date2__range=[datefrom, dateto]) And I get this error: 'django.core.exceptions.FieldError: Cannot resolve keyword 'date2' into field. Choices are: ...' When I change my query to: q = MyModel.objects.filter(date1__range=[datefrom, dateto]) Everything works fine. Migrations were done several times and each object in database has a value for Besuchsdatum. I also tried setting up a new database and migrated all the data over, but I still have this issue. First database engine I used was sqllite and now I use postgresql but I have the same issue. I'm new to django, so if possible I need a simple answer for that issue. -
Simple authentication Django
I have a django-rest/React project and want to enable simple (hard-coded) login/pass authentication on index page. Only need this authentication to access the page by the user, and don't want to use authetication on rest requests. Have tried this approach, but in this case all rest API requests return 403 forbidden responses after entering login/pass credentials. Any ideas? -
How to generate an excel file and save it to database as a file
I have created a function that creates an excel file using xlwt. I was able to download it as file but I want it to be saved to the database first. Here's what I have so far. import xlwt response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="excel-file.xls"' wb = xlwt.Worbook() # some excel file generating code here wb.save(response) return response After generating the excel file I want to add it to the database but this does not work. # file = models.FileField Reports.objects.create( file=wb ) I have also tried saving it a stream first but it does not also work. f = io.StringIO() wb.save(f) # file = models.FileField Reports.objects.create( file=f ) -
How to use javascript in django template
I am using javascript for validating a form in django template, but it's not working, the DOM events are not fetching the values. HTML snippet <form onsubmit="return validate_hotel()" action="confirm_hotel/{{hotel_name}}" method="post"> {% csrf_token %} <div id="left"> <label>Check in date</label> <input id="checkin" type="date" autocomplete="off" name="checkin" > <br><br> <label>Number of guests</label><br> <select autocomplete="off" name="guests" id="guests"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select><br><br> <label>Username</label> <input id="HotelUsername" type="text" name="username" autocomplete="off"> </div> <div id="right"> <label>Check out date</label> <input id="checkout" type="date" autocomplete="off" name="checkout"> <br><br> <label>Number of rooms</label><br> <select autocomplete="off"> <option value="1">1</option> <option value="2">2</option><br> </select><br><br> <label> password</label> <input id="password" type="password" autocomplete="off" name="password" > </div> <br><label id="hotel_error_message"> {{error_message}} </label><br> <button type="submit">Confirm booking</button> </form> here is the javascript function i am using to validate things. i am using document.getElementById() method to fetch the input values. function validate_hotel() { var hotel_username = document.getElementById("HotelUsername").value; var checkin = document.getElementById("checkin").value; var checkout = document.getElementById("checkout").value; var hotel_password = document.getElementById("password").value; var date_regx = /^(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$/ var username_regx = /^[a-zA-Z0-9_$.@]+$/ var password_regx = /^(?=.*\d).{4,12}$/ var valid = true; console.log(hotel_username, checkin, checkout, hotel_password); if (! username_regx.test(hotel_username)) { valid = false; } if (! password_regx.test(hotel_password)) { valid = false; } if (! date_regx.test(checkin)) { valid = false; } if (! date_regx.test(checkout)) { valid = false; } if (!valid) { … -
Find out in queryset whic manager was used in Django
Question is – is it possible in case I have 2 or more model’s managers somehow make one of queryset’s method unreachable from one of the managers? For example… class MyModel(models.Model): … … … manager_1 = CustomManger_1() manager_2 = CustomManger_2() If I want to make for example queryset delete() method non-callable from manager_2, but callable from manager_1 . To do that if I have custom queryset I need somehow find out from which exact manager queryset method is called. I.E I need to distinguish 2 situations: MyModel. manager_1.all().delete() and MyModel. manager_2.all().delete() Is it possible to do it somehow? Thank you -
Django get_queryset return custom variables
Using users as an example I am trying to show how many users there are. get_context_data works totally fine but get_queryset does not. I know that it's not set up properly but I've been playing around with it for quite some days and something is just not clicking.. The main goal is to use the Dajngo-Filter form and then be able to get the updated number of user count. I've only found endless documentation on how to show the "list" of users. Which I have done but no documentation on how to show custom variables. I have many statistics & charts I'd like to calculate based on the filters applied. class UserFilterView(LoginRequiredMixin, FilterView): template_name = 'community/user_list.html' model = User filterset_class = UserFilter def get_queryset(self): user_count = User.objects.all().count() def get_context_data(self, *args, **kwargs): context = super(UserFilterView, self).get_context_data(*args, **kwargs) context['user_count'] = User.objects.all().count() return context -
Handling multiple database in Django
I am developing a web-application in Django using MySQL database. Now, I need to connect to an internal MSSQL Database and update only 1 table ClientDetails Here is my Database configuration: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'database_name', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" } }, 'internal': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'client_database', 'USER': 'client', 'PASSWORD': 'password', 'HOST': 'Database_Internal' } } How do I write to the table ClientDetails in the 2nd Database?