Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom JWT authentication
I want to authenticate the user with email and confirmation code. But JWT uses by default username and password for authentication. How can I change that? Should I override TokenObtainSerializer? -
How to compare list of models with queryset in django?
I have a serializer: class MySerializer(serializers.ModelSerializer): class Meta: model = models.MyClass fields = "__all__" def validate(self, data): user = self.context.get("request").user users = data.get("users") users_list = User.objects.filter(organization=user.organization) return data users will print a list of models like this: [<User: User 1>, <User: User 2>] users_list will display a queryset: Queryset: <QuerySet [<User: User 1>, <User: User 2>, <User: User 3>]> I want to write a query which checks if list of models e.g.users are present inside a queryset users_list. How to do that? -
I want to be able to update a user's password in my React.js and Django app
Backend is Dango The front end is made with React.js. What I want to achieve it I want to users to update their registered passwords. Issue/error message If you update the password on the React.js side, it will look like the following and the update will fail. . Django side Terminal {'password': 'welcome1313'} username {'detail': [ErrorDetail(string='Invalid data. Expected a dictionary, but got str.', code='invalid')]} Bad Request: /users/12/ [15/Jan/2023 15:42:10] "PATCH /users/12/ HTTP/1.1" 400 13 React.js const MyPagePasswordUpdate = () => { const [my_password, setValue] = useState(null); const [my_ID,setMyID] = useState(null); const isLoggedIn= useSelector(state => state.user.isLoggedIn); const { register, handleSubmit, errors } = useForm(); useEffect(() => { async function fetchData(){ const result = await axios.get( apiURL+'mypage/', { headers: { 'Content-Type': 'application/json', 'Authorization': `JWT ${cookies.get('accesstoken')}` } }) .then(result => { setValue(result.data.password); setMyID(result.data.id); }) .catch(err => { console.log("err"); }); } fetchData(); },[]); const update = async (data) =>{ console.log(data) await axios.patch(`${apiURL}users/`+my_ID+'/', { headers: { 'Content-Type': 'application/json', 'Authorization': `JWT ${cookies.get('accesstoken')}` }, password:data.password, }, ).then(message => { alert("Updated!") }) .catch(err => { console.log("miss"); alert("The characters are invalid"); }); }; return ( <div> {isLoggedIn ? <div class="update-block"> <form onSubmit={handleSubmit(update)}> <label for="password">Password:</label> <input className='form-control' type="password" {...register('password')} /> <input className='btn btn-secondary' type="submit" value="Update" /> </form> <Link to="/mypage">Back to … -
CheckboxSelectMultiple widget Django renders already collapsed in form
I am trying to create a form where you can enter the language or languages. I want to use a CheckboxSelectMultiple widget, but it renders already collapsed in the form: The form with already collapsed select How can I fix this? forms.py: class TweetForm(forms.ModelForm): class Meta: model = TweetSearch fields = ['search_term', 'query_type', 'start_date', 'end_date', 'language', 'country', 'tweet_count'] widgets = { 'search_term': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Search...'}), 'query_type': forms.Select(attrs={'class': 'form-control'}), 'tweet_count': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Number of tweets'}), 'start_date': DateTimePickerInput(attrs={'class': 'form-control', 'placeholder': 'From'}), 'end_date': DateTimePickerInput(attrs={'class': 'form-control', 'placeholder': 'Till'}), 'language': forms.CheckboxSelectMultiple(attrs={'class':'form-control'}) } html: <div id="searchcontainer"> <div class="card w-50 text-center mx-auto mt-8" id="searchcard"> <div class="card-header"> Search </div> <div class="card-body"> <h5 class="card-title">Search for tweets</h5> <form action="" method="POST"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-4"> {{form.search_term}} </div> <div class="form-group col-md-4"> {{form.query_type}} </div> <div class="form-group col-md-4"> {{form.tweet_count}} </div> </div> <div class="form-row"> <div class="form-group col-md-6"> {{form.start_date}} </div> <div class="form-group col-md-6"> {{form.end_date}} </div> </div> <div class="form-row"> {{form.language}} </div> <input class="btn btn-primary mb-2" type="submit"> </form> </div> </div> -
django multi file upload fields
List item registration start date Year Vin# Make Title Owner (Upload field) ==== (can be several files) HUT # (Upload field) ==== (can be several files) Ifta # (Upload field) ==== (can be several files) I need that model If file upload fields had to be for a single file, then it would be okay, but how Can I handle that model? (Should I create ForeignKey models for every file_upload field in order to handle multi file uploads??) -
nested result for nested serializer in django with many to many fields
i have four models : CommonAccess model that have four ManyToMany to AccessSubject,AccessGroup,AccessAction and AccessSubGroup class CommonAccess(TimeStampedModel): name = models.CharField(blank=True,null=True,max_length=200,) subjects = models.ManyToManyField(AccessSubject,) groups = models.ManyToManyField(AccessGroup,blank=True,) actions = models.ManyToManyField(AccessAction,blank=True,) sub_groups = models.ManyToManyField('AccessSubGroup,blank=True, ) def __str__(self): return self.ename or '' AccessSubject model: class AccessSubject(): name = models.CharField(blank=True, null=True, max_length=200, unique=True,) AccessGroup model: class AccessGroup(): name = models.CharField(blank=True, null=True, max_length=200, unique=True,) access_subject = models.ForeignKey(AccessSubject,on_delete=models.SET_NULL,related_name='access_groups') AccessSubGroup model: class AccessSubGroup(): name = models.CharField(blank=True, null=True, max_length=200, unique=True,) access_subject = models.ForeignKey(AccessSubject,on_delete=models.SET_NULL,) access_group = models.ForeignKey(AccessGroup,on_delete=models.SET_NULL,related_name='accessgroup_subgroups') i need to when pass a commonAccess id get commonAccess with nested subject,group and sub group that fileter with ManyToMany fields in CommonAccess model like : name: 'sample' subject: [ name: 'sub1' group : [ name: 'gr1' sub_group: [ name: 'sgr1' ] [ name: 'sgr2' ] ] group : [ name: 'gr2' sub_group: [name: 'sgr3'] ] ] [ name: 'sub2' group : [ name: 'gr3' ] ] i have used serializer like below, but only subjects filtered by CommonAccess ManyToMany fileds, i want Group and SubGroup also filtered by CommonAccess : class NewCommonAccessSerializer(ModelSerializer): subjects = NewAccessSubjectNestedSerializer(read_only=True, many=True) class Meta: model = CommonAccess fields = "__all__" class NewAccessSubjectNestedSerializer(ModelSerializer): accesslevel_groups = NewAccessGroupNestedSerializer(many = True) class Meta: model = AccessSubject fields = '__all__' class NewAccessGroupNestedSerializer(ModelSerializer): … -
AttributeError: module 'django.db.models' has no attribute 'SubfieldBase'
I'm trying to run application originally created using python 3.6 and django 1.11 with python 3.7 and django 2.2. I'm now getting problems when starting django server: python manage.py runserver Exception in thread Thread-1: Traceback (most recent call last): File "/opt/python/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/opt/python/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/srv/work/miettinj/tandt_putki/python/django/tandt/tandt/models.py", line 20, in <module> from select_multiple_field.models import SelectMultipleField File "/srv/work/miettinj/tandt_putki/python/django/tandt/python-3.7-django-*/lib/python3.7/site-packages/select_multiple_field/models.py", line 20, in <module> class SelectMultipleField(six.with_metaclass(models.SubfieldBase, AttributeError: module 'django.db.models' has no attribute 'SubfieldBase' my virtualenv: (python-3.7-django-*) miettinj@ramen:~/tandt_putki/python/django/tandt> pip freeze adal==1.2.7 aniso8601==7.0.0 anyascii==0.3.1 asgiref==3.6.0 azure-core==1.26.2 backports.zoneinfo==0.2.1 bcrypt==4.0.1 beautifulsoup4==4.11.1 bleach==6.0.0 … -
Retrieve the value of a field linked by foreign key to a Profile that extends the User (oneToOne relationship) in Django views.py
What I want to do : Display a phone book from Django User model extended with a Profile model related to several models What I have done : Of course, I've read Django documentation (4.1) I have my classic Django User model I have created a "Profile" model to extend the User model via a OneToOne relationship (here simplified) : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) entity = models.ForeignKey(Entity, null=True, blank=True, on_delete=models.CASCADE) class Meta: ordering = ['entity__name', 'user__last_name'] def __str__(self): return self.user.first_name + " " + self.user.last_name @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() I have created an "Entity" model (more or less the company where people work) (here simplified) : class Entity(CommonFieldsUUID): name = models.CharField(max_length=100, unique=True, null=False, default="N.C.") alias = models.CharField(max_length=25, unique=True, null=False, default="N.C.") class Meta: verbose_name = "Entity" verbose_name_plural = "Entities" def __str__(self): return self.alias Here is my views.py : from .models import User from django.http import HttpResponse from django.template import loader def phonebook(request): user = User.objects.filter(is_active=True).values('first_name','last_name','email','profile__entity','profile__pro_ext','profile__pro_gsm','profile__pro_trigram','profile__location') template = loader.get_template('phonebook/phonebook.html') context = { 'colHeaders': ['Firstname LASTNAME', 'Entity', 'Extension', 'Mobile', 'Email', 'Initials', 'Location'], 'user': user, } return HttpResponse(template.render(context, request)) Here is my template phonebook.html : {% extends "main/datatables.html" %} … -
How can I query item wise stocks and revenue in django ORM?
`class RevenueStockDashboardViewset(ViewSet): sale = InvSaleDetail.objects.filter(sale_main__sale_type='SALE') sale_returns = InvSaleDetail.objects.filter(sale_main__sale_type='RETURN') purchase = InvPurchaseDetail.objects.filter(purchase_main__purchase_type='PURCHASE') purchase_returns = InvPurchaseDetail.objects.filter(purchase_main__purchase_type='RETURN') def list(self, request): total_revenue = (self.sale.annotate(total=Sum('sale_main__grand_total')) .aggregate(total_revenue=Sum('total')) .get('total_revenue') or 0) - (self.sale_returns.annotate(total=Sum('sale_main__grand_total')) .aggregate(total_revenue=Sum('total')) .get('total_revenue') or 0) - (self.purchase.annotate(total=Sum('purchase_main__grand_total')) .aggregate(total_revenue=Sum('total')) .get('total_revenue') or 0) + (self.purchase_returns.annotate(total=Sum('purchase_main__grand_total')) .aggregate(total_revenue=Sum('total')) .get('total_revenue') or 0) total_stocks = (self.purchase.annotate(total=Sum('qty')) .aggregate(total_stock=Sum('total')) .get('total_stock') or 0) - (self.purchase_returns.annotate(total=Sum('qty')) .aggregate(total_stocks=Sum('total')) .get('total_stock') or 0) - (self.sale.annotate(total=Sum('qty')) .aggregate(total_stock=Sum('total')) .get('total_stock') or 0) - (self.sale_returns.annotate(total=Sum('qty')) .aggregate(total_stock=Sum('total')) .get('total_stock') or 0) return Response( { 'total_revenue': total_revenue, 'total_stocks': total_stocks, # 'item_wise_stocks': items, } )` I have Inventory Dashboard where I want to show the item wise revenue and item wise stocks. I have done query for total stocks and revenue but I want item wise. If you need more information. Please let me Know. -
localstorage alternatives for a django iframe app
Are there any alternatives for localstorage as we are using this to store a few data. Our issue is that our app is working as an iframe in Shopify, so when testing in incognito window it denies the access of localstorage. This is the error we are getting: Uncaught DOMException: Failed to read the 'localStorage' property from 'Window': Access is denied for this document. Can someone please suggest a solution for this issue? -
Get the string of two upper levels in foraign relations
Good Morning, How to get the value Entity.name about ProjectsComments row. Top model : class Entities(models.Model): code = models.CharField(verbose_name='Código', max_length=10, blank=False, unique=True, help_text='Codigo de entidad.') name = models.CharField(max_length=150, verbose_name='Nombre', unique=True, help_text='Nombre de la entidad.') def __str__(self): return self.name def toJSON(self): item = model_to_dict(self) return item Second Level: class Projects(models.Model): entity = models.ForeignKey(Entities, on_delete=models.DO_NOTHING, verbose_name="Entidad") def __str__(self): return f'{self.entity}' + ' \ ' + f'{self.code}' + ' \ ' + f'{self.name}' # + ' \ ' + f'{self.phase}' def toJSON(self): item = model_to_dict(self) item['entity'] = self.entity.toJSON() return item Third Level class ProjectsComments(models.Model): project = models.ForeignKey(Projects, on_delete=models.DO_NOTHING, default=0, verbose_name='Proyecto', help_text='Proyecto') def __str__(self): return f'{self.date}' + f' ' + f'#' + f'{self.user}' + f'# ' + f'{self.comment}' def toJSON(self): item = model_to_dict(self) item['project'] = self.project.toJSON() item['entity'] = Entities.objects.get(pk = ) item['user'] = self.user.toJSON() return item I would need that from projectscommentsListView get the value of ProjectsComments__Projects__Entity.name I have tried get into ProjectsComments.toJSON() with : item['entity'] = Entities.objects.get(pk = ) AND item['entity'] = self.entity.toJSON() I do not know anymore. -
Design a MLM Binary tree structure
I have the data coming from Django rest framework, I've created the tree using jQuery and also used some CSS for the structure. but the structure is not in a proper way. want perfect design just like a mlm binary tree I have the data coming from Django rest framework, I've created the tree using jQuery and also used some CSS for the structure. but the structure is not in a proper way. want perfect design just like a mlm binary tree. I want the design to be perfect and smooth. -
I want to run R modules in Django Framework on production using rpy2 ? is it possible ? Please let me know the steps
I want to run R modules in Django Framework on production using rpy2 ? is it possible ? Please let me know the steps. File "/mnt/d/venv/lib/python3.8/site-packages/rpy2/robjects/conversion.py", line 370, in _raise_missingconverter raise NotImplementedError(_missingconverter_msg) NotImplementedError: Conversion rules forrpy2.robjects appear to be missing. Those rules are in a Python contextvars.ContextVar. This could be caused by multithreading code not passing context to the thread. -
Filling a website page with info about ongoing proccess with Django and Selenium
Hey I'm currently building a website that uses Django as front and back and selenium automations with python. I'm unsure how to implement this idea, for example user is creating an object and then he's redirected into another blank page and I want this blank page to fill with paragraph about each of the processes Selenium does (where it succeeds and where it fails for a re run) I thought about using javascript to load dynamic late into the dom as selenium runs its functions and the results outputted into the blank page for the user to see, is there any other way to do so with django? -
In Python, I want to give image as input and according to it products from local db (SQLite or SQLServer or MySQL) should be displayed
I am looking for a sample code where I can give input type as Image to search for products using Python Django Framework for one of project. after image successfully uploaded, I need to check the image and according to it, products should be listed on search page. After image successfully uploaded, I need to check the image and according to it, products should be listed on search page, from Database (SQLite, MySQL, SQL Server or any) -
How to approach Django app in another Docker Container?
I running Django Projects with Docker Container. Theres' three containers in Server. Accounts Container Blogs Container Etc Container Situation. I want to approach to Accoutns Container in Blogs Container. Why. There's Article Table in Blogs Conatiner. And Blogs Container doesn't have accounts app. so I have to approach to accounts app in Accounts Container. class Article(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ... I dont have any idea :( -
How to set up rollup config to allow for direct imports?
I have created a component library in React and am using rollup as my bundler. My project directory looks like this: src ├── assets │ ├── fonts │ └── icons ├── components │ ├── Alert │ │ ├── Alert.tsx │ │ └── index.tsx │ ├── Button │ │ ├── Button.tsx │ │ └── index.tsx │ └── index.tsx ├── styles ├── utils └── index.tsx My package.json looks like this: "files": [ "dist" ], "main": "dist/esm/index.js", "module": "dist/esm/index.js", "type": "module", "exports": { ".": "./dist/esm/index.js", "./components": "./dist/esm/components", "./assets": "./dist/esm/assets", "./utils": "./dist/esm/utils" }, "types": "dist/index.d.ts", My rollup configuration looks like: import resolve from '@rollup/plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; import typescript from '@rollup/plugin-typescript'; import terser from '@rollup/plugin-terser'; import copy from "rollup-plugin-copy-assets"; import dts from 'rollup-plugin-dts'; import postcss from 'rollup-plugin-postcss'; import svgr from '@svgr/rollup'; import packageJson from './package.json' assert { type: "json" }; /** * @type {import('rollup').RollupOptions} */ const config = [ { input: 'src/index.ts', output: [ { file: packageJson.module, format: 'esm', }, ], plugins: [ copy({ assets: [ "src/assets", ] }), resolve(), commonjs(), typescript({ tsconfig: './tsconfig.build.json', declaration: true, declarationDir: 'dist', }), postcss(), svgr({ exportType: 'named', jsxRuntime: 'automatic' }), terser(), ], external: ['react', 'react-dom', 'react-select', 'styled-components'], }, { input: 'dist/esm/index.d.ts', output: [{ file: 'dist/index.d.ts', format: "esm" … -
ImportError: attempted relative import with no known parent package WHILE IMPORTING VIEWS INSIDE URLS IN DJANGO
i am a beginner in Django and I am trying to import views in URL getting this error. Attaching the screenshots enter image description here enter image description here I hoped that the import of views inside Url would be successful .is that a problem with directory?? -
cPanel terminal not found, how to find it?
I am deploying a Django project in cPanel, but not showing a terminal option even in advance section. how can I find it? -
python django serializer wrong date time format for DateTimeField
I'm using Django 3.0.2. I have a serializer defined: class ValueNestedSerializer(request_serializer.Serializer): lower = request_serializer.DateTimeField(required=True, allow_null=False, format=None, input_formats=['%Y-%m-%dT%H:%M:%SZ',]) upper = request_serializer.DateTimeField(required=True, allow_null=False, format=None, input_formats=['%Y-%m-%dT%H:%M:%SZ',]) class DateRangeSerializer(request_serializer.Serializer): attribute = request_serializer.CharField(default="UPLOAD_TIME") operator = request_serializer.CharField(default="between_dates") value = ValueNestedSerializer(required=True) timezone = request_serializer.CharField(default="UTC") timezoneOffset = request_serializer.IntegerField(default=0) class BaseQueryPayload(request_serializer.Serializer): appid = request_serializer.CharField(required=True, validators=[is_valid_appid]) filters = request_serializer.ListField( required=True, validators=[is_validate_filters], min_length=1 ) date_range = DateRangeSerializer(required=True) And the payload : { "appid": "6017cef554df4124274ef36d", "filters": [ { "table": "session", "label": "1month" } ], "date_range": { "value": { "lower": "2023-01-01T01:00:98Z", "upper": "2023-01-20T01:00:98Z" } }, "page": 1 } But I get this validation error: { "error": { "date_range": { "value": { "lower": [ "Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm:ssZ." ], "upper": [ "Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm:ssZ." ] } } } } The suggested format YYYY-MM-DDThh:mm:ssZ is similar to what is passed. Am I missing anything here? -
How to add a check constraint in django model that a field value startwith letter 'c' or 'e' or 'a'
How to add a check constraint in django model that a field value startwith letter 'c' or 'e' or 'a' like the bellow SQL check constraint CREATE TABLE Account ( account_no varchar(12), FirstName varchar(255), Age int, City varchar(255), CONSTRAINT CHK_Person CHECK (SUBSTR(account_no,1,1) = 'c' OR SUBSTR(account_no,1,1) = 'e' OR SUBSTR(account_no,1,1) = 'a' ) ); i try with meta class of model. but i don't know how to specify the or case class Meta: constraints = [ CheckConstraint( check = Q(account_no___startswith=F('')), name = 'check_start_date', ), ] -
plain python script vs robot framework vs python script with web ui
I have a task to create a validation testing for new firmware builds of firewalls (do upgrade and test all firewall features ), i have a good Python knowledge . and need users to have any kind of UI for the test . i am confused which method to use . 1- Python scripts with logging and execute it from Jenkins . 2- robot framework which has its own reporting and run it from Jenkins . 3- python script with Django web UI . i'v done part of the project with robot framework which has a very limited documetation and info on the internet . i cannot do certain tasks as it gets complex . i am in love with it's reporting but at some point felt it is not worth it . now i am trying to redo this part with normal python scripts . -
How we can connect react js with django?
How we can connect react js with django without installing node js? Code of connect django with react without install nodejs server -
msgfmt : The term 'msgfmt' is not recognized as the name of a cmdlet, function, script file, or operable program. (Windows 10)
I have a django application based on django 1.11 and when i make changes on locale's .po files i run the following command: msgfmt django.po -o django.mo The command worked fine on my linux machine but I can't find a proper guide on how to get msgfmt command to work on windows. Following error message is shown: msgfmt : The term 'msgfmt' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + msgfmt django.po -o django.mo -
How i can to use django-import-export with a django-mptt?
In the project i using 2 package "django-import-export" and "django-mptt" url follow below. django-import-export : https://django-import-export.readthedocs.io/en/latest/ django-mqtt : https://django-mptt.readthedocs.io/en/latest/overview.html I have a problem when i import using django-import-export is not work with mqtt models. show error below PARENT Cannot assign "'Dept1'": "Dept.parent" must be a "Dept" instance. i think to error cause when i import data from xlsx. the django-import-export will try to check data. due to mqtt have a node parent the second records will try to add data but not have a parent in database. i want to know how i can to import and export ? thank you for expert .