Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to properly use Jquery to disable checkboxes in a Django Form when a certain number of them are checked
I've been trying a couple of ways to disable checkboxes in a Django ModelForm. Using Jquery I was able to write some code that does disable checkboxes when a certain number is checked, but it also disables the ones that have been checked. I want a dynamic way to check and uncheck boxes and only block boxes that have not been checked when the limit is hit. This is my JS: function checkBoxes() { $(' input[type=checkbox]'). attr('disabled', true); $(document).on('click', 'input[type=checkbox]', function (event) { if ($(this).is(":checked")) { console.log("1") } else { console.log('2') } }); } The issue I'm having trying to figure this out is how to verify if the box has been checked or not because of how I'm creating the checkbox list with Django: <div style="height:30px"></div> <form method="post"> {% csrf_token %} {{ context.form.as_p }} <button type="submit">Submit</button> </form> How can I fix my JS and be able to enable and disable checkboxes dynamically, meaning when the limit is hit, disable all the unchecked boxes, and when the limit is reduced allow checkboxes to be clicked again? -
how to copy variable to [clipboard] in django template
How do I copy a variable from inside the html page of Django templates? render(request, 'doc.html', {'stack': stack, 'text':text,}) -
how to get input from html form to python code
I have created a python code and an html form with text boxes and button. what I want is to pass the text box value into my python code I m using django, and I've tried whit cgi but nothing has given me the output that I'm looking for. besides I get in the browsers just the python code when I click on the button. so if anyone has an idea how this could be done please help -
How can I set default_currency= "INR" in settings.py file because its use many times in project?
I want to save MoneyField details in setting.py file so I can use it every places where I use MoneyField I want to save this.. MoneyField(max_digits=10, decimal_places=2, default_currency='INR', null=False, default=0.0) How can save it in settings.py -
Using django-elasticsearch-dsl-drf, how to implement autocomplete and term matching
I'm very new to elasticsearch, so some terminology may be wrong. I want to implement autocomplete as well as term matching. Say I have a document with the name "Foo Bar." If I query "fo," it works. However, I also want to be able to find this document by querying "bar" This is my document: @registry.register_document class ReviewableDocument(Document): id = fields.TextField() name = fields.TextField( fields={ "raw": fields.TextField(analyzer=html_strip), "suggest": fields.CompletionField(), } ) class Index: name = "reviewables" settings = {"number_of_shards": 1, "number_of_replicas": 0} class Django: model = Reviewable fields = [ "url_name", "profile_picture", ] This is my serializer: class ReviewableAutocompleteSerializer(DocumentSerializer): class Meta(object): fields = ("id", "name", "url_name") document = ReviewableDocument And this is my view: class SuggestReviewableByName(DocumentViewSet): serializer_class = ReviewableAutocompleteSerializer permission_classes = (AllowAny,) document = ReviewableDocument filter_backends = [ SuggesterFilterBackend, ] suggester_fields = { "name_suggest": {"field": "name.suggest", "suggesters": [SUGGESTER_COMPLETION]} } -
Value type dependant on column describing the type
I'm creating a tool where all you would need to add a new field in a website you would only need to add data describing the field in the database and css style (for minimal front-end developer and zero backend developer effort). In turn I need a database with a column storing dynamic value type. Example: | Type | Value | -------------------------------- | string | "abc": string | | number | 51: number | | Date | 2020-10-10: Date | How and with what database can this be achieved? Or is there an alternative way to achieve this goal? -
Django Wsgi ModuleNotFoundError: No module named 'project_name'
I am trying to deploy a Django project using WSGI and NGINX. The problem is that at startup, the logs show a module missing error When launched via the service uwsgi restart command, an error appears in the logs /var/log/uwsgi/app/django.log: Wed Aug 18 17:25:21 2021 - Python version: 3.8.10 (default, Jun 2 2021, 10:49:15) [GCC 9.4.0] Wed Aug 18 17:25:21 2021 - *** Python threads support is disabled. You can enable it with --enable-threads *** Wed Aug 18 17:25:21 2021 - Python main interpreter initialized at 0x55f90e1e7700 Wed Aug 18 17:25:21 2021 - your server socket listen backlog is limited to 100 connections Wed Aug 18 17:25:21 2021 - your mercy for graceful operations on workers is 60 seconds Wed Aug 18 17:25:21 2021 - mapped 145840 bytes (142 KB) for 1 cores Wed Aug 18 17:25:21 2021 - *** Operational MODE: single process *** Traceback (most recent call last): File "project_name/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/usr/local/lib/python3.8/dist-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/usr/local/lib/python3.8/dist-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File … -
How to send a response from Django view function to a HTML popup windows
So, my app works like this: 1- user clicks and a function will call a ajax jquery send some data to a function in views.py, Done! 2- some process will be made in the function. some data are ready. Done! 3- I want to show the data on a html format like a popup window. I am new in this and I have not find any straight forward instruction. You can find my step 1 in How to send a simple data by Ajax jQuery to views.py in Django? Thanks in advance -
API interface in django
I am working in a project on connected objects. My job is to retrieve the data from the devices at the broker level by providing an HTTP push interface. I was therefore asked to set up an API interface. I am developing with django and I want to write an API with django restframework. I would like to know if a REST API could serve as an interface in this case. -
Is it possible to join 2 django models with no references?
I want to make a join with 2 django models with no relationship, so there are no foregn keys. class Person(models.Model): id = models.IntegerField() name = models.CharField() class Pilot(models.Model): id = models.IntegerField() vehicle = models.CharField() How do I join Pilot and Person by "id"? -
Handling Of Database (sqlite) for Django on Heroku
[Error Log][1] I had run "heroku run python manage.py migrate" yet the migrate aren't working. [1]: https://i.stack.imgur.com/QKtZr.png -
Django best practices regarding custom User models
This is more of a general best practices question. When you start a new project in Django, do you generally create a custom User model, or rely on the default one? Personally it seems cleaner to me if I don't mess with the default User model. If there are any additional attributes I want to add, I feel it is simpler to add a Profile or UserInfo model with a one-to-one/foreign key relation with a User. A lot of articles I've read about Django, however, disagree with this. Apparently it is recommended to build a custom User model? I'm curious about what everyone does, and what exactly I'm missing out on if I make either of these choices. -
How to get data from parent table through child table
I want to get all the product name that has been ordered and stored in OrderItem table and I want to sum their quantity group by product name. Help!!! Here are my tables. class m_Product(models.Model): name = models.CharField(max_length=200) Brand = models.CharField(max_length=200) quantity = models.IntegerField(default=0, null=True, blank=True) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False, null=True, blank=True) image = models.ImageField(null=True, blank=True) description = models.CharField(max_length=2000) tags = models.CharField(max_length=20) class OrderItem(models.Model): product = models.ForeignKey( m_Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey( Prescription, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) s = m_Product.objects.select_related('orderitem').filter('name').values('quantity').annotate(sum = Sum('quantity')) -
What is the best way to paginate a large table using React Table and Django?
I have a table with 50k rows and 20+ columns. For now, I have configured a custom Django Rest Framework pagination so that I can use query string to set the page size as well as the page number: http://127.0.0.1:8000/api/ix/?page=2&page_size=100 The JSON result looks like this: { "count": 48629, "next": "http://127.0.0.1:8000/api/ix/?page=3&page_size=100", "previous": "http://127.0.0.1:8000/api/ix/?page_size=100", "results": [{...}] } For the frontend, I want to use React Query to get the JSON, and React Table to display and handle the pagination. From React Table's offical example, it seems to me that it just get the unpaginated version of the data, then do a slicing on the client side: const startRow = pageSize * pageIndex const endRow = startRow + pageSize setData(serverData.slice(startRow, endRow)) Possible Approaches Don't use pagination on the server side, and slice the data as shown by the example Pro: I can just use the example codebase with a little modification to make this work Con: It will take quite while to load the data; the pagination might cause re-fetching and loading the data per pagination operation Use custom pagination on the server side, and make my own pagination methods Pro: Since the data is already paginated, it's more efficient to load … -
Make PermissionRequiredMixin also check for object level permission
I am using Django Guardian to have object-level permission along with global permissions. Some of the users have a group with global permissions, and some have object-level permissions. With this, I seem to need to modify the PermissionRequiredMixin to check also for the object-level permission. views.py class MainPageView(PermissionRequiredMixin, TemplateView): permission_required = "app.view_mainpage" template_name = "web/mainpage.html" This one works if the user has global permission but if the user is under a group with object-level permission, it won't. With guardian, to check for object-level permission, you also have to pass the object instance. example: self.request.user.has_perm('view_mainpage', obj) And on PermissionRequiredMixin, the checking goes only like this, self.request.user.has_perms(perms) So if the user has a group with permission of view_mainpage of a specific object, how can I check it too? By the way, all my permissions are of the same content_type. Is there any way I can execute this? Like I have to pass the object instance to PermissionRequiredMixin if the user is under an object-level group and None if the user is under a global group. -
After overriding permissions, endpoint should require a token to access, however it's not
I am using Django REST for my API. Here is my custom permission class: permissions.py: from rest_framework.permissions import BasePermission from rest_framework.response import Response class ItemsPermissions(BasePermission): def has_permission(self, request, view): try: request_data = request.data print(request_data) auth_token = request_data['returnedDataFromAuthAPI'] if("accessToken" in auth_token): auth_token = auth_token['accessToken'] Response({"Permission Granted - AccessToken": auth_token}) return True #else Response({"message": "No Auth Token Provided! You Need To Login!"}) return False except Exception as ex: return Response({"message": ex}) in views.py: class ListItems(generics.ListAPIView): permission_classes = [ShippingPermissions] queryset = myModel.objects.all() serializer_class = mySerializer in urls.py: url_patterns = [ path("/items/list/", ListItems.as_view()), ] I have an authentication microservice that I get the JWT Token from, for the user to have access to the views. In the ItemsPermissions class I am checking the token. My Question: I want to grant the user access to the ListItems class, after the token is provided, but if token is not provided then the user should not have access. However, for some reason, I am able to access the /items/list/ endpoint, and it does not ask me/require a token at all. I am getting No errors. What is the problem ? -
If in Html calling a model
I have this model: class Canva(models.Model): name = models.CharField(null=True, blank=True, max_length=255) site = models.CharField(null=True, blank=True, max_length=255) month = models.CharField(null=True, blank=True, max_length=255) year = models.IntegerField(null=True, blank=True) def __str__(self): return self.name in html page: when I write {{ canva.month }}, it shows me the value JUNE but when I write: {% if JUIN == canva.month %} hello {% else %} goodbye {% endif %} it always show me goodbye. -
Django don’t redirect to confirmation page when delete
Django don’t redirect to confirmation page when delete. Hi all, I did a standard CRUD on a table, which is foreign key on one other table. I use the Django view class. Create, Read and Update work, but I have a bug on the Delete. When I delete one item, I am redirected to detail page (Read page) with the good delete address (‘localhost/table_name/pk/delete’). I follow the standard way describe in Django Project and in several tutorial. Following, portion of my code: model.py : class Badge(models.Model): id_badge = models.AutoField(primary_key=True) title = models.CharField(max_length=100) category = models.CharField(max_length=60) level = models.IntegerField() image_badge = models.ImageField(upload_to='badge_image/', null=True, blank=True, default='ex-par-nat_logo.png') class Meta: managed = True db_table = 'badge' view.py: from django.shortcuts import redirect, render from UsersApp.tribut_sign_up_form import TributSignUpForm from UsersApp.tutor_sign_up_form import TutorSignUpForm from UsersApp.child_sign_up_form import ChildSignUpForm from django.contrib.auth import authenticate, login from django.contrib.auth import logout as account_logout from UsersApp.models import Tribut, Tutor, Child, Account from django.http import HttpResponse from django.contrib.auth.decorators import login_required from UsersApp.decorator import tribut_required @method_decorator([login_required, author_required], name='dispatch') class BadgeListView(ListView): model = Badge ordering = ('title', ) template_name = 'ArticlesApp/badge_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context def get_queryset(self): queryset = Badge.objects.all() return queryset @method_decorator([login_required, author_required], name='dispatch') class BadgeCreateView(CreateView): model = Badge # form_class … -
django.db.utils.IntegrityError: null value in column COLUMN_id violates not-null constraint
Newbie here both on Stackoverflow as well as django/drf. I am receiving this error, I know that I can solve this by adding the null field in the calendar foreign key file. I can not modify the field due to some reason, how can I fix this. Please let me know if other info is required. Error: django.db.utils.IntegrityError: null value in column "instructor_id" violates not-null constraint Model class Calendar(models.Model): instructor = models.ForeignKey('Instructor', on_delete=models.PROTECT) Serializer class CalendarSerializer(serializers.ModelSerializer): class Meta: model = Calendar fields = '__all__' depth = 1 -
should ssh file "ssh_config" always be located in "~/.ssh" folder
I have noticed while learning how to setup ssh that lots of stackoverflow posts referred to the file ssh config being inside of the folder ~/.ssh but when i look at the same folder in my macbook the files listed are: created from my last ssh setup someprivatekey someprivatekey.pub known_hosts now when i inspect the folder cd /etc/ssh/ then i can see the file ssh_config there. Is it a normal behavior or should ssh file "ssh_config" always be located in "~/.ssh" folder and I have presumably a wrong configuration? (Sorry if the post sound very elementary, i am learning how to use ssh) Thanks -
How to deliver image file to python backend with Imgur API when uploading images from React frontend
I am trying to upload image from React frontend and deliver this image object to Django, Python backend, with Imgur API. (imgurpython) My goal is to upload the image to Imgur in Python backend and gets image url from Imgur, finally I will return this url back to React frontend side to use. But I have some problem and confused it how to get this Image File in Django views with request. Here is my frontend page. And there are my codes frontend/Screen import React, {useState,useEffect} from 'react' import { Link } from 'react-router-dom' import { useDispatch, useSelector} from 'react-redux' import { Row, Col, ListGroup, Image, Form, Button, Card } from 'react-bootstrap' import Message from '../components/Message' import { uploadImage } from '../actions/caseActions' function CaseScreen({ match, location, history}) { const dispatch = useDispatch() const [image, setImage] = useState(null) const handleInputChange =(event) =>{ event.preventDefault(); console.log(event) console.log(event.target.files[0]) setImage({ image: event.target.files[0] }); } const uploadImgurImage = (event) => { event.preventDefault(); let data = new FormData(); data.append("image", image); dispatch(uploadImage(data)) // send to actions } return ( <Row> <Col md={8}> <Card>個案頁</Card> <form onSubmit={uploadImgurImage}> <input type="file" name="image" onChange={handleInputChange}/> <button>Submit</button> </form> </Col> </Row> ) } export default CaseScreen frontend/uploadActions import axios from 'axios' import { UPLOAD_IMAGE_REQUEST , UPLOAD_IMAGE_SUCCESS … -
Import xlsx spreadsheet with column index accented - Django Models
My question is that I want to import a spreadsheet, but some columns are with accented names (words in Portuguese) Example: Município Municipio = models.TextField('Município', blank=True, null=True) Consequently, the column is imported without values as the column was not recognized. The only way to solve it would be to change the column names in the spreadsheet to words without accents? -
Django get data from Partition in Model
We are building a website and our system is dynamically partitioned with the architect plugin. Is there any way to look into the partitioned table directly and get data from it with Django Models? Can we pass the table name while filtering or retrieving the data, can I do so? -
Is it possible to make a connection to a ready made server in a Django/Python web app
I have been asked to create a Django Web Application that prints account balances, age analysis', customer statements etc. This program needs to connect to the database at our office (Pastel Evolution Database) and fetch accounts etc. from there. I had previously created this code to connect to the database via .bat: import pymssql user = '[User ]' password = '[Password]' server = '[IP]' #username: [Username]_dev_ro #password: [Password] #database name: DB_Name databaseName = 'DB_Name' conn = pymssql.connect(server, user, password, databaseName) cursor = conn.cursor(as_dict=True) cursor.execute('SELECT top 10 * FROM [DB_Name].[dbo].[_etblGLAccountTypes]') for row in cursor: print(row) conn.close() If anyone knows how I would create the same sort of function inside of Django so that I can fetch the data from the server and print it onto a Web-Page , please assist . -
how to optimize the execution time of a django view so that it does not take time to execute
I need help, my django view is taking a long time to run I have 6 views in total and each view takes 6min of responses i use pandas dataframe to extract xml data then i apply multiple calculation formula, the slowest is when loading the home.html homepage because it takes 45min to run solution I read: -use multiprocessing to execute each view in parallel but I don't know how to do it what I looked for: -django-q, unfortunately this is for sql queries, my code doesn't contain sql queries, Do you have any ideas? of the process that I have to follow my home_view django def home_view(request): month = ''.join(request.GET.getlist('id_mois')) this_region = ''.join(request.GET.getlist('id_region')) # --------------------REVENU-------------------- : from REVENU.revenu import details_revenu init_revenu = initializing_revenu() ref_details_revenu = details_revenu(init_revenu[0], init_revenu[1], this_region, month) # ---------------------SUBSCRIBER------------------: from SUBSCRIBER.subscriber import subscriber_details init_subscriber = initializing_subscriber() ref_subscriber = subscriber_details(init_subscriber[0], init_subscriber[1], this_region, month) # -----------------ANIMATEUR--------------------: from ANIMATEUR.animateur import function_animateur init_animateur = initializing_animateur() ref_animateur = function_animateur(init_animateur[0], init_animateur[1], this_region) # -----------------MVOLA--------------------: from MVOLA.mvola import mvola_details init_mvola = initializing_mvola() mvola = mvola_details(init_mvola[0], init_mvola[1], this_region, month) context = {#....some context} return render(request, 'home.html', context) here returned, subscriber, mvola, animateur takes 6min each time to execute