Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Vuejs SFC (single file component) in django
fil1.vue <script setup> import { ref } from 'vue' const msg = ref('Hello World!') </script> <template> <h1>{{ msg }}</h1> <input v-model="msg"> </template> I would like to render this in my Django template. Previously with normal vue components I was able to do use them as follows: JS file: Vue.component('comp1', {...}) django html template: <comp1> </comp1> -
How to refer custom User model in settings.py using subapp in Django?
I followed this StackOverflow post to create a sub-app in Django. I've got a custom 'User' model which is inside an 'account' app which is then inside in parent app 'myapp'. -myapp (parent app) --accounnt (subapp) ---models.py User I changed the name of my account app to class accountConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'myapp.account' Installed app INSTALLED_APPS = [ ... 'myapp.account' ] Now, I need to refer this model for AUTH_USER_MODEL in my settings.py. The basic method is AUTH_USER_MODEL = 'app_label.model'. In my case its AUTH_USER_MODEL = 'myapp.account.User'. I got this error: ValueError: Invalid model reference 'myapp.account.User'. String model references must be of the form 'app_label.ModelName'. or if I refer User model as AUTH_USER_MODEL = 'account.User'. then, Django isn't able to recognize account as an installed app Is there any way, I can refer to my User model in AUTH_USER_MODEL? Any help is highly appreciated. -
Deserialize JSON with User ID
I am running into an issue while deserializing JSON data. One of the field is the customerID and i cannot find a way to user a Serializer class properly. Here is my code: class UserProfileData(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) captureDateTime = models.CharField(_('Capture datetime'), blank=True, null=True, max_length=100) class UserProfileDataSerializer(serializers.ModelSerializer): class Meta: model = UserProfileData fields = "__all__" The JSON i receive is the following: { "customerID": "someUUID", "captureDateTime": "..." } Here is the current state of my view: @api_view(['POST']) def register_profile(request): data = JSONParser().parse(request) serializer = UserProfileDataSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) It fails with the following error: {'user': [ErrorDetail(string='This field is required.', code='required')]} I understand i am missing something here, but can't figure out what... Also, i almost forgot to mention the User object has a customerId field. Thanks for your help. -
Connecting react.js to Django backend: Postman works but Axios post does not
I would like a decisive solution to linking my react to my django backend, as I have fallen into confusion by picking bits and pieces from various sources. I am trying to deploy a fine-tuned transformer model for inference, it works perfectly, and I am able to post and get a response with postman. Below is the Axios/node.js code from postman for reference. var axios = require('axios'); var data = JSON.stringify({ "data": "my input sentence..." }); var config = { method: 'post', url: 'http://127.0.0.1:8000/api/infer/', headers: { 'Content-Type': 'application/json', 'Cookie': 'csrftoken=zVbH181pBhnaAAtEoTmQGd0XLABvVLjsjVsDNYVudLZCmSMSXpe1RQJOd' }, data : data }; axios(config) .then(function (response) { console.log(JSON.stringify(response.data)); }) .catch(function (error) { console.log(error); }); This app doesn't require any login or authentication modules.. Below is the code of the single page in react which I expect to -> on click <-, send my "data" to the Django backend for prediction, and return my result. Below is the Home.js file import * as React from 'react'; import Box from '@mui/material/Box'; import TextField from '@mui/material/TextField'; import { IconButton } from '@material-ui/core'; import { InputAdornment } from '@mui/material'; import {useState, useEffect} from "react" import axios from "axios" import {component} from 'react' export default function MultilineTextFields() { const [data, setData] = React.useState(''); … -
Django Rest API returning ValueError: Invalid format string
Getting the error Invalid format string when creating a new user in Django. Even though I am getting this error, a new user is being created. Here is my serializers.py: from django.contrib.auth.models import User from rest_framework import serializers #changed from serializers.HyperLinked to ModelSerializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User #removed url from fields fields = ['username', 'email', 'password'] extra_kwargs = { 'password': {'write_only': True}, } def create(self,validated_data): user = User.objects.create_user( username=validated_data['username'], password=validated_data['password'], email=validated_data['email']) user.set_password(validated_data['password']) user.save() return user class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) class PasswordSerializer(serializers.Serializer): old_password = serializers.CharField(required=True) new_password = serializers.CharField(required=True) My urls.py: from django.contrib import admin from django.urls import path, include from rest_framework import routers from . import views from rest_framework_simplejwt.views import (TokenObtainPairView, TokenRefreshView, TokenVerifyView) from .api import RegisterApi router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) urlpatterns = [ path('', include(router.urls)), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'), path('api/register', RegisterApi.as_view()), ] and api.py: from rest_framework import generics, permissions, mixins from rest_framework.authentication import TokenAuthentication from rest_framework.response import Response from .serializers import RegisterSerializer, UserSerializer from django.contrib.auth.models import User from rest_framework.permissions import AllowAny #Register API class RegisterApi(generics.GenericAPIView): serializer_class = RegisterSerializer #remove this if it … -
Django : How can we custom login_required decorator?
I want to rewrite the login decorator of Django to check an Azure AD authentication. For the authentication, I used the tutorial (https://docs.microsoft.com/en-us/graph/tutorials/python). I do not how how to deal with groups and permission since I use this authentication, so I take the username, surname as a password to create un user in the User django models. For that I modify the callback function of the tutorial : def callback(request): # Make the token request result = get_token_from_code(request) #Get the user's profile user = get_user(result['access_token']) # Store user store_user(request, user) # Get user info # user attribute like displayName,surname,mail etc. are defined by the # institute incase you are using single-tenant. You can get these # attribute by exploring Microsoft graph-explorer. username = user['displayName'] password = user['surname'] email = user['mail'] try: # if use already exist user = User.objects.get(username=username) except User.DoesNotExist: # if user does not exist then create a new user user = User.objects.create_user(username,email,password) user.save() user = authenticate(username=username,password=password) if user is not None: login(request,user) messages.success(request,"Success: You were successfully logged in.") return redirect('home') return redirect('home') If I want to check if the user is authenticated by Azure AD, I have to do something like that : if request.session.get('user').get('is_authenticated') : But … -
Cookie collision: is it possible to distinguish between parent domain and subdomain cookies in Django and Javascript?
I have built a bunch of Django websites at a single domain: example.com site1.example.com site2.example.com site3.example.com They are supposed to be completely independent — used by different people for different purposes. However cookies set by example.com are given priority by Django, and values set by site1.example.com, site2.example.com etc. are ignored if the parent domain has set a cookie with the same name. How it works: When the first page is loaded, it sets a cookie so the server knows to send a computer page or a mobile page with the next request. The Django program builds the correct version based on the cookie value. When site1.example.com loads, it sets a cookie asking for the mobile version. But then the Django program sees the value set by example.com and ignores the correct cookie. So, I need a way to do one of the following: prevent site1.example.com from reading the cookie of example.com differentiate in Django the domain associated with the cookie so I can tell that the value is wrong find a way to set a parent domain cookie in Javascript that makes it inaccessible to subdomains (I'm not using www) If I can't find an elegant solution, I will likely … -
Insert data from SQL file in Django DB
I'm working on a Django Project, and I have all my datas in .sql files. I want to insert all of them in my Database. Can I use the python shell to do it ? Or should I use another method ? -
How to remove some items form queryset depending on @property?
I don't know how to remove results from a queryset without using .exclude(). I want to filter the result if the argument is_active is passed as a parameter of my search based on the result of the property is_active. My model with the calculated property 'is_active': class Discount(models.Model): name = models.CharField(_("name"), max_length=255) date_start = models.DateField(_("Date start"), null=True, blank=True) date_end = models.DateField(_("Date end"), null=True, blank=True) [...] @property def is_active(self): if self.date_start and self.date_end: return self.date_start <= date.today() <= self.date_end return True My viewset: class DiscountViewSet(viewsets.ModelViewSet): """ A simple ViewSet for listing or retrieving discounts. """ permission_classes = [CustomDjangoModelPermission] filter_backends = [DjangoFilterBackend] filter_fields = '__all__' def get_serializer_class(self): if hasattr(self, 'action') and self.action in ['list', 'retrieve']: return DiscountListSerializer return DiscountSerializer def get_queryset(self): if self.request.user.is_staff: return Discount.objects.all().prefetch_related('products') \ .prefetch_related('machines').prefetch_related('categories') else: return Discount.objects.all().prefetch_related('products') \ .filter(machines__site__client__in=self.request.user.profil.client.all()) \ .prefetch_related('machines').prefetch_related('categories') @swagger_auto_schema(manual_parameters=[height, width], responses={200: DiscountListSerializer}) def list(self, request): height = self.request.query_params.get('height') width = self.request.query_params.get('width') queryset = self.get_queryset() queryset = self.filter_queryset(self.get_queryset()) active_filter = request.data.get('is_active') if active_filter: for item in qs: if not item.is_active: ???? // remove item if height and width: for discount in queryset: if discount.menu_photo: discount.menu_photo = generate_thumbnail(discount.menu_photo, width, height) if discount.standby_photo: discount.standby_photo = generate_thumbnail(discount.standby_photo, width, height) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, … -
Issue with CSS file in Django
Trying to load a css file into my base.html file. When I load the webpage, it is not updating the webpage with the css styling I loaded. Everything is running as expected, 0 issues when I activate it in terminal. -
How to add multiple forms in one page using django formset
Using Django formset, you can add multiple forms at once on one page. However, two problems arose. Googling for a few days doesn't solve it. [forms.py] from django import forms from django.forms import modelformset_factory, ModelForm, DateTimeInput, Select from .models import Supporting SupportingModelFormset = modelformset_factory( Supporting, fields=('date', 'student', 'kinds', 'post_hour', 'teacher', 'comment', 'technician'), extra=1, widgets={'date': forms.DateTimeInput(format=('%Y-%m-%d %H:%M'), attrs={'name': 'date', 'id': 'date', 'autocomplete': 'off', 'class': 'form-control col-sm-12 date'}), 'student': forms.Select(attrs={'id': 'student', 'name': 'student', 'class': 'chosen'}), 'kinds': forms.Select(attrs={'id': 'kinds', 'name': 'kinds'), 'post_hour': forms.TextInput(attrs={'type': 'text', 'class': 'form-control col-sm-3', 'name': 'post_hour', 'placeholder': 'hr'}), 'cteacherrc': forms.TextInput(attrs={'type': 'text', 'class': 'form-control col-sm-12', 'name': 'teacher'}), 'comment': forms.TextInput(attrs={'class': 'form-control position-relative', 'name': 'comment', 'rows': '4'}) } ) [views.py] def add_supporting(request): if request.method == 'GET': formset = SupportingModelFormset(queryset=Supporting.objects.none()) elif request.method == 'POST': formset = SupportingModelFormset(request.POST) if formset.is_valid(): for form in formset: form.save() return redirect('supporting_list') return render(request, 'supporting/add.html', {'formset': formset}) [supporting/add.html] <form class="form-horizontal" method="POST" action=""> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="row form-row spacer mt-4"> <div class="form-group row"> <label>{{form.date.label}}</label> <div class="input-group"> {{form.date}} </div> </div> <div class="form-group row"> <label>{{form.student.label}}</label> <div class="input-group"> {{form.student}} </div> </div> <div class="form-group row"> <label>{{form.kinds.label}}</label> <div class="input-group"> {{form.kinds}} </div> </div> <div class="form-group row"> <label>{{form.post_hour.label}}</label> <div class="input-group"> {{form.post_hour}} </div> </div> <div class="form-group row"> <label>{{form.teacher.label}}</label> <div … -
How to put the product price with a ManyToManyField between Sellers and Products Table
I want a product price between two table Sellers and Products. Here are my models- class Products(models.Model): name = models.CharField(max_length=60) price= models.IntegerField(default=0) category= models.ForeignKey(Category,on_delete=models.CASCADE,default=1 ) description= models.TextField(blank=True, null= True) image= models.ImageField(upload_to='uploads/products/') def __str__(self): return self.name class Sellers(models.Model): name = models.CharField(max_length=60) products = models.ManyToManyField(Products) description= models.TextField(blank=True, null= True) image= models.ImageField(upload_to='uploads/sellers/') def __str__(self): return self.name Where to put the product price for each seller? -
FilterSelectMultiple | Django Form | widget | Django Template - Not able to see the form, return NoReverseMatch Error
I am trying to build a form, taking input through a FilterSelectMultiple field from Group model My urls.py looks like from django import views as django_views urlpatterns = [ # some other patterns url(r'^jsi18n/', django_views.i18n.JavaScriptCatalog.as_view(), name='javascript-catalog'), ] forms.py looks like from django import forms from django.contrib.auth.models import Group from django.contrib.admin.widgets import FilteredSelectMultiple class MyForm(forms.Form): """Form for assigning groups to new users.""" options = [(group_name, group_name) for group_name in Group.objects.all()] # other fields groups = forms.MultipleChoiceField(required=False,widget=FilteredSelectMultiple("Groups", is_stacked=False),choices=options) class Media: css = { 'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n',) def __init__(self, *args, **kwargs): """Init.""" super(MyForm, self).__init__(*args, **kwargs) template looks like {% extends base.html %} {% block head %} {% load staticfiles %} some stuff {% endblock head %} {% block content %} <script type="text/javascript" src="{% url 'jsi18n' %}" > </script> {{ form.media }} <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Submit</button> </form> {% endblock content %} But I am getting error - NoReverseMatch Reverse for 'jsi18n' not found. 'jsi18n' is not a valid view function or pattern name -
Why is my Python for loop running out of memory?
I have a for loop in Python/Django to iterate over a long list of users and create recommendations for them using a saved tensorflow model: def create_recommendations_for_users(): user_ids = User.objects.values_list("id", flat=True) retrieval_model = tf.saved_model.load("tensorflow_models/model") ranking_model = tf.saved_model.load("tensorflow_models/ranking_model") for user_id in user_ids: create_recommendations_for_user(user_id, retrieval_model, ranking_model) def create_recommendations_for_user(user_id, retrieval_model, ranking_model): _, items = retrieval_model([user_id]) for item_id in items[0]: item_id = item_id.numpy() rating = ranking_model.ranking_model( (tf.constant([user_id]), tf.constant([item_id])) ).numpy() Recommendation.objects.create(user_id=user_id, item_id=item_id, rating=rating) The issue is that calling create_items_for_users is causing a memory leak. Why would this happen? items is scoped to the create_items_for_user function, so wouldn't this be garbage collected, as would item_id and rating, each time it gets run? user_ids is a long list of integers, but doesn't grow over time and isn't all that large. I'm not storing a growing list of results anywhere. Why would these functions cause a memory leak? -
Populating a hidden field after form save
I am very new to Django and I wanted some guidance on building this. I have a form that works well right now, but I want to change a functionality. There is a hidden field that doesn't show on the form but is in the model, I want to be able to populate that hidden field based on an entry on the form. I've tried overriding the clean method in the view but that wasn't working. Any guidance would be appreciated, thanks! -
Django Import Export Strip White Space & Additional Condition
I'm using the Django Import and Export plugin and in my Admin.py I need to solve two problems. The excel file I'm uploading has white space at the end of the cells, I need to remove that. This import is uploading test scores, there is no test id in the import to determine if its a different test. However, there is a test date field. I need to be able to get the date field before the import of each row and analyze it to determine if this is an update of the current test data or make a new record signaling this was a different test. I appreciate the help. Here is my admin.py class MindResource (resources.ModelResource): state_province = fields.Field(column_name='state_province', attribute='state_province',widget=ForeignKeyWidget(Student, 'state_province')) def import_row(self, row, instance_loader, **kwargs): # OVERRIDE ERROR TO IMPORT RECORDS (STOPS FAILURE OF IMPORT) import_result = super(MindResource, self).import_row(row, instance_loader, **kwargs) if import_result.import_type == RowResult.IMPORT_TYPE_ERROR: # COPIES VALUES TO DISPLAY ON THE REPORT import_result.diff = [row[val] for val in row] # ADD COLUMN WITH ERROR MESSAGE import_result.diff.append('Errors: {}'.format([err.error for err in import_result.errors])) # CLEAR ERRORS AND MARK TO SKIP import_result.errors = [] import_result.import_type = RowResult.IMPORT_TYPE_SKIP return import_result class Meta: model = Mind clean_model_instances = True import_id_fields = … -
Django Abandoned/Unused Models
I have a models.py file with 6-10 unused models on a Django Project. What do you do with these unused models? Do you delete them (and migrate them out)? Do you just push them to the side and ignore them? -
Present Python variable in HTML Template in Django
I have a value extracted from JIRA API showing a total for a particular project. When I print the value, I can see the correct values and these are clearly being stored in the variable. # Emergency Changes Query jira_emergency_changes = jira.search_issues('labels = new-emerging-audit AND resolution = Unresolved').total # Open Issues Query jira_open_issues = jira.search_issues('project = UTILITY AND status = Open').total # Open JIRA Ticket Total Query jira_open_tickets = jira.search_issues('project = "UTILITY" AND status not in (Closed, Completed, Resolved) ORDER BY created DESC').total I want to add these values to a template page in a <p> tag, but no matter what method I try, it just doesn't render. Could some advice? :) -
ssl error with copying file in s3 server?
I tried to collect static files on the S3 Server for my Django project with the command : python manage.py collectstatic But It failed because of SSLError : During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\botocore\httpsession.py", line 414, in send chunked=self._chunked(request.headers), File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\connectionpool.py", line 756, in urlopen method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2] File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\util\retry.py", line 507, in increment raise six.reraise(type(error), error, _stacktrace) File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\packages\six.py", line 769, in reraise raise value.with_traceback(tb) File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\connectionpool.py", line 706, in urlopen chunked=chunked, File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\connectionpool.py", line 382, in _make_request self._validate_conn(conn) File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\connectionpool.py", line 1010, in _validate_conn conn.connect() File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\connection.py", line 421, in connect tls_in_tls=tls_in_tls, File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\util\ssl_.py", line 450, in ssl_wrap_socket sock, context, tls_in_tls, server_hostname=server_hostname File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\util\ssl_.py", line 493, in _ssl_wrap_socket_impl return ssl_context.wrap_socket(sock, server_hostname=server_hostname) File "C:\Users\Anthony\AppData\Local\Programs\Python\Python37\lib\ssl.py", line 423, in wrap_socket session=session File "C:\Users\Anthony\AppData\Local\Programs\Python\Python37\lib\ssl.py", line 870, in _create self.do_handshake() File "C:\Users\Anthony\AppData\Local\Programs\Python\Python37\lib\ssl.py", line 1139, in do_handshake self._sslobj.do_handshake() urllib3.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1091) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute … -
django get related names for object
we can access to an object's all field by __dict__ class Profile(models.Model): chips = models.PositiveIntegerField(default=0) user = models.OneToOneField(User, on_delete=models.CASCADE) desc = models.CharField(max_length=255, default='', blank=True, null=True) image = models.ImageField(default='profile/default.jpg', upload_to='profile') active = models.BooleanField(default=False) points = models.PositiveIntegerField(default=0) createTime = models.DateTimeField(default=now, editable=False) email = models.EmailField(blank=True, null=True) Profile.objects.all()[0].__dict__ """ { '_state': <django.db.models.base.ModelState object at 0x7fe6d9632390>, 'id': 1, 'chips': 100000, 'user_id': 1, 'desc': None, 'image': 'profile/default.jpg', 'active': False, 'points': 100010, 'createTime': datetime.datetime(2022, 3, 13, 13, 45, 57, 513699, tzinfo=<UTC>), 'email': None } """ But does not include reference from ForeignKey, OneToOneField and ManyToManyField, that was defined on other models that has a related name. for example class Article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="articles") # __dict__ of Profile object does not include articles is there a way I can get all callable attributes of database from the model. thanks very much. -
Django - Update a model field through a form
I have this model which represents the values users submit through a form when making an applying for sponsorship. class ApplicationData(models.Model) : class Status(models.TextChoices): REJECTED = 'Rejected' PENDING = 'Pending' ACCEPTED = 'Accepted' """Define table for Applications in database""" user = models.ForeignKey(User, on_delete=models.DO_NOTHING) organisationName = models.CharField(max_length=200, null=True, blank=True) projectTitle = models.CharField(max_length=200, null=True, blank=True) CH_OSCR_number = models.CharField(max_length=20, unique=True, blank=True, null=True, ) projectDesc = models.TextField(max_length=300, null=True, blank=True) userGroupDesc = models.TextField(max_length=300, null=True, blank=True) learningOpp = models.TextField(max_length=300, null=True, blank=True) keyPartnersWork = models.TextField(max_length=300, null=True, blank=True) projImpactClimate = models.TextField(max_length=300, null=True, blank=True) projSupportLocBus = models.TextField(max_length=300, null=True, blank=True) proContribution = models.TextField(max_length=300, null=True, blank=True) length = models.IntegerField(null=True, blank=True) application_complete = models.BooleanField(default=False) date_of_application = models.DateField(null=True, blank=True) reviewed = models.BooleanField(default=False) app_status = models.TextField(choices = Status.choices, default = Status.PENDING) On the system there are 3 different user types. Once an applicant submits an application the staff users can view the submitted application details on a dedicated page. What I'm trying to do is to add a form on that page where the staff will have the ability to change the status of the application (app_status on the model). Here are my efforts: Here the is the form to update the field. class UpdateAppStatus(forms.ModelForm): class Meta: model = ApplicationData fields = ('app_status',) labels … -
How to have a ManyToManyField with two tables Sellers and Products
I have a Products Table class Products(models.Model): name = models.CharField(max_length=60) price= models.IntegerField(default=0) How to proceed with ManyToManyField between Sellers and Products -
TypeError: cannot use a string pattern on a bytes-like object python3
I have updated my project to Python 3.7 and Django 3.0 Here is code of models.py def get_fields(self): fields = [] html_text = self.html_file.read() self.html_file.seek(0) # for now just find singleline, multiline, img editable # may put repeater in there later (!!) for m in re.findall("(<(singleline|multiline|img editable)[^>]*>)", html_text): # m is ('<img editable="true" label="Image" class="w300" width="300" border="0">', 'img editable') # or similar # first is full tag, second is tag type # append as a list # MUST also save value in here data = {'tag':m[0], 'type':m[1], 'label':'', 'value':None} title_list = re.findall("label\s*=\s*\"([^\"]*)", m[0]) if(len(title_list) == 1): data['label'] = title_list[0] # store the data fields.append(data) return fields Here is my error traceback File "/home/harika/krishna test/dev-1.8/mcam/server/mcam/emails/models.py", line 91, in get_fields for m in re.findall("(<(singleline|multiline|img editable)[^>]*>)", html_text): File "/usr/lib/python3.7/re.py", line 225, in findall return _compile(pattern, flags).findall(string) TypeError: cannot use a string pattern on a bytes-like object How can i solve my issue -
Signing up users returning no attribute action error
I have an API handling the login and signup process (Django to React front end). While users can login, receiving an access and refresh token when I point towards the signup endpoint I get the error 'RegisterApi' object has no attribute 'action' Here is a breakdown of my code api.py: from rest_framework import generics, permissions, mixins from rest_framework.response import Response from .serializers import RegisterSerializer, UserSerializer from django.contrib.auth.models import User from rest_framework.permissions import AllowAny #Register API class RegisterApi(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "message": "User Created Successfully. Now perform Login to get your token", }) #allow for anonymous signup def get_permissions(self): if self.action == 'create': return [AllowAny()] else: return super().get_permissions() def get_authenticators(self): if self.action == 'create': return [] else: return super().get_authenticators() serializers.py from django.contrib.auth.models import User from rest_framework import serializers #added more imports based on simpleJWT tutorial from rest_framework.permissions import IsAuthenticated from django.db import models from django.contrib.auth import authenticate from django.contrib.auth.hashers import make_password #changed from serializers.HyperLinked to ModelSerializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User #removed url from fields fields = ['username', 'email', 'password'] extra_kwargs = { 'password': {'write_only': True}, } def create(self,validated_data): user = User.objects.create_user(validated_data['username'], … -
Django custom admin filter: get filtered queryset before the current filter itself is applied
I have a classic admin.SimpleListFilter. I would want to get the current filtered/displayed queryset, but before my own filter is applied, so I can show the result count for each of my filter lookups. The current code below always shows total counts of each lookup, not respecting eventual other selected filters. class ByAssignementStatusFilter(admin.SimpleListFilter): title = _('Assignement Status') parameter_name = 'status__exact' def lookups(self, request, model_admin): choices = [] qs = model_admin.get_queryset(request) # qs.count() is always the unfiltered amount for key, label in Assignement.STATUS_CHOICES: count = qs.filter(assignement__status=key).count() label = f"{label} ({count})" choices.append((key, label)) return choices def queryset(self, request, queryset): if self.value() is not None: return queryset.filter(assignement__status=self.filter_value) else: return queryset