Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Maximum update depth exceeded on django instance deletion
When trying to delete the model tenantJobCategory I'm seeing a weird error message: RecursionError: maximum recursion depth exceeded The problem only exists whenever the tenantJobCategory has an active FK relationship to a profile instance (if it doesn't have that the deletion works fine). This is the profile: class Profile(models.Model): uuid = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) tenant_job_category = models.ForeignKey('job_categories.TenantJobCategory', null=True, blank=True, on_delete=models.SET_NULL) should_auto_promote = models.BooleanField(default=False) should_manual_promote = models.BooleanField(default=False) __original_should_auto_promote = None __original_manual_promote = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__original_should_auto_promote = self.should_auto_promote <-- this seems to be the cause self.__original_manual_promote = self.should_manual_promote <-- this too def save(self, *args, **kwargs): if self.should_auto_promote != self.__original_should_auto_promote: should_auto_promote_change.send(sender=self.__class__, instance=self) if self.should_manual_promote != self.__original_manual_promote: should_manual_promote_change.send(sender=self.__class__, instance=self) super().save(*args, **kwargs) I've marked two lines that I think, are causing the error (when I delete them, it works fine, if I delete only one of them, it also works). Maybe someone ran into this problem before and knows how to fix it? Thanks! -
How to select same object twice in Django ManyToMany Field
I have two models class Food(models.Model): name = models.CharField(max_length=200 ,null=False) class Profile(models.Model): food_selected_today = models.ManyToManyField(Food,related_name = 'inventory') Now in profile model I want to have one food for example Apple more than one time in food_selected_today. If I now add same food twice it only shows one Item. How can I add one food many times here. Any kind of help would be really appreciated -
Django: l'm trying to insert movies into MySQL db if it doesn't exist else if it exist query from database
json_response = response.json() movies = json_response['data']['movies'] movie_db = Movie.objects.all() print(movie_db) if movie_db is not None: for value in movies: Movie.objects.create( title=value['title'], description = value['description_full'], image = value['medium_cover_image'], category = value['genres'], year_of_production = value['year'], movie_url = value['url'], movie_torrent_link = value['torrents'][0]['url'], rating = value['rating'], runtime = value['runtime'], ) else: messages.info(request, "Movies exists...") return render(request, 'index.html',) so l tried to use queryset and store all movies in movie_db then l wanted to use an if statement to check if the movies don't exist insert else do nothing -
Django Model Classes
I have three model classes, identity, record, and times chedule. Identity is related to record using employee_id with length of 20 chars. And times chedule is related to record thru emp_time_sched field. Running migrate, django.db.utils.DataError:value too long for type character varying(3) error. Checked the table attributes, record.emp_type_sched has 20 chars. I include max_length=3 and still same error. -
Django: Call and edit model from template
I'm using Django for a simple web app where tasks have milestones. When clicking a milestone, it should be marked completed. I'm not sure how to change the completed attribute from my template. This is my milestone model, where I define a function Milestone.complete that I'm trying to call from the template (without success). class Milestone(models.Model): name = models.CharField(max_length=200) task = models.ForeignKey(Task, on_delete=models.CASCADE) completed = models.BooleanField(default=False) def complete(self): self.completed = True My template looks like this: ... {% if task.milestone_set.exists %} <div class="card"> <div class="card-header">Milestones</div> <ul class="list-group list-group-flush"> {% for milestone in task.milestone_set.all %} <li class="list-group-item"> {{ milestone.name }} {% if not milestone.completed %} {# <a href="{{ milestone.complete }}" class="btn btn-primary">Completed</a>#} <button type="button" class="btn btn-success" onclick="{{ milestone.complete }}">Completed</button> {% endif %} </li> {% endfor %} </ul> </div> {% else %} <p>task has no milestones</p> {% endif %} ... Calling milestone.complete works neither from the a link element nor from the button. The latter gives me Uncaught ReferenceError: None is not defined in the console and nothing happens. I also thought about how to implement the same function in a view, but didn't know how. -
Django Form : after correctly submitting form I got this: "this field is required"
I've a category and I've added a form for user in each category. So I've two fields to fill and after filling them correctly I submit but the page reload, and nothing appears in my DB... only one error on Image field: This field required. I don't really know what's wrong here. class Picture(models.Model): catego = models.ForeignKey(Catego,on_delete=models.CASCADE,related_name="catego_pictures") user = models.ForeignKey(User, blank=True, null=True,on_delete=models.CASCADE,related_name='user_pictures') image = models.ImageField(upload_to='nutriscore/') pictureoption = models.CharField(max_length=20,choices=Pictureoption.choices,default=Pictureoption.HOME,) publishing_date = models.DateField(auto_now_add=True) class CreatePictureForm(forms.ModelForm): def __init__(self,*args,**kwargs): super(CreatePictureForm, self).__init__(*args,**kwargs) self.helper = FormHelper() self.helper.form_method="post" self.helper.layout = Layout( Field("image",css_class="single-input"), Field("pictureoption",css_class="single-input"), ) self.helper.add_input(Submit('submit','Upload a pic',css_class="single-input textinput textInput form-control")) class Meta: model = Picture fields = [ 'image', 'pictureoption', ] def __str__(self): return self.catego.name views.py @login_required(login_url='/cooker/login') def catego(request, slug): catego = Catego.objects.get(slug=slug) context = { 'catego': catego } # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = CreatePictureForm(request.POST) # check whether it's valid: if form.is_valid(): form.instance.catego = self.object form.instance.user = self.request.user form.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: form = CreatePictureForm() context['form'] = form # add `form` to the context return render(request, 'post_catego.html', context) -
How can I get the previous URL in Django?
My code looks like this, I hope you will understand my logic. def home(request): if request.method == 'POST': return redirect('first-round') return render(request, 'home.html') def firstRound(request): # checking current url is redirected from home or not if request.META.get('HTTP_REFERER') == '/': if request.method == 'POST': return redirect('second-round') return redirect(request, 'first-round.html') else: return redirect('/') def secondRound(request): # checking current url is redirected from first-round or not if request.META.get('HTTP_REFERER') == '/first-round/': if request.method == 'POST': return redirect('third-round') return render(request, 'second-round.html') else: return redirect('/') def thirdRound(request): # checking current url is redirected from second-round or not if request.META.get('HTTP_REFERER') == '/second-round/': if request.method == 'POST': return redirect('login') return render(request, 'third-round.html') else: return redirect('/') request.META.get('HTTP_REFERER') return full path. So I need a previous URL full path like https://www.example.com/, https://www.example.com/first-round/, https://www.example.com/second-round/ and https://www.example.com/third-round/ -
problem deployind site in python any where
I'm trying to deploy my Django project with pythonanywher.com but I can't I'm a beginner please help I do exactly like his: creating an account creating API token in bash scripts pip3.6 install --user pythonanywhere and then $ pa_autoconfigure_django.py --python=3.6 https://github.com//my-first-blog.git but I face this and I can't figure out why it doesn't work please help 30 ~ $ pip3.6 install --user pythonanywhere Looking in links: /usr/share/pip-wheels Collecting pythonanywhere Downloading https://files.pythonhosted.org/packages/15/fa/812362a3910459a7ec1da428bdf44ea3c8468b92b57459c7d4a010f65ff7/pythonanywhere-0.9.4.tar.gz Requirement already satisfied: docopt in /usr/lib/python3.6/site-packages (from pythonanywhere) (0.6.2) Requirement already satisfied: python-dateutil in /usr/lib/python3.6/site-packages (from pythonanywhere) (2.8.0) Requirement already satisfied: requests in /usr/lib/python3.6/site-packages (from pythonanywhere) (2.22.0) Collecting schema Downloading https://files.pythonhosted.org/packages/6d/ae/835f2e0d304c9533c58fe5cbcdd9124708d32e82289fcb8d6084c908ba29/schema-0.7.2-py2.py3-none-any.whl Collecting tabulate Downloading https://files.pythonhosted.org/packages/c4/f4/770ae9385990f5a19a91431163d262182d3203662ea2b5739d0fcfc080f1/tabulate-0.8.7-py3-none-any.whl Requirement already satisfied: six>=1.5 in /usr/lib/python3.6/site-packages (from python-dateutil->pythonanywhere) (1.12.0) Requirement already satisfied: idna<2.9,>=2.5 in /usr/lib/python3.6/site-packages (from requests->pythonanywhere) (2.8) Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/lib/python3.6/site-packages (from requests->pythonanywhere) (3.0.4) Requirement already satisfied: certifi>=2017.4.17 in /usr/lib/python3.6/site-packages (from requests->pythonanywhere) (2019.9.11) Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/lib/python3.6/site-packages (from requests->pythonanywhere) (1.24.3) Collecting contextlib2>=0.5.5 Downloading https://files.pythonhosted.org/packages/85/60/370352f7ef6aa96c52fb001831622f50f923c1d575427d021b8ab3311236/contextlib2-0.6.0.post1-py2.py3-none-any.whl Building wheels for collected packages: pythonanywhere Building wheel for pythonanywhere (setup.py) ... done Created wheel for pythonanywhere: filename=pythonanywhere-0.9.4-cp36-none-any.whl size=30356 sha256=7bd01dd5d2d87faa19a931bd08f74e050498422a92a38f9e0b3b12b4c9bd0510 Stored in directory: /home/bookseagull13/.cache/pip/wheels/68/35/da/800f46741a95d4c66e77c7c2e145884a7ce9d2c46af401ee29 Successfully built pythonanywhere Installing collected packages: contextlib2, schema, tabulate, pythonanywhere Successfully installed contextlib2-0.6.0.post1 pythonanywhere-0.9.4 schema-0.7.2 tabulate-0.8.7 14:31 ~ $ python3 -m … -
django.urls.exceptions.NoReverseMatch: Reverse for 'foo-list' not found. 'foo-list' is not a valid view function or pattern name
I've got the message Reverse for 'receptionop-list' not found. 'receptionop-list' is not a valid view function or pattern name. in one of my test cases when trying to do the following: reverse('receptionop-list') Note: I have also tried reverse('receptionops-list') I've got it set in my urls like this: router.register(r'receptionops', views.ReceptionOperationViewSet) What's weird for me, is the fact I've got also a router.register(r'reception', views.ReceptionViewSet) registered in the same app, and using reverse('reception-list') works perfectly. Does anyone know what's going on here? (If needed, I can provide some further information) Thanks! -
Configuring httpd.conf with python Django and mod_wsgi : how to configure so I can access to my url like www.example.com?
I'm working on new personal project that consist on developing a website with python Django framework. I'm using macOS High Sierra system and I'm trying to follow python tutorial for that. First we need to configure environment with apache httpd server and mod_wsgi module. I could display "Hello world" script with mod_wsgi application script but I get it with http://localhost url instead of http://www.example.com url... Also, I'm trying to configure it with virtual environment. The question is how do I need to do into httpd.conf file for that ? Thank you in advance for your help Tony Here is the main configuration for my virtual host : <VirtualHost *:80> ServerName www.example.com ServerAlias example.com example # Chemin a partir duquel le serveur va servir les fichiers, racine a partir de laquelle nous pourrons consulter depuis internet DocumentRoot /Users/username/Desktop/example/Site # Etapes de configuration du module mod_wsgi. # Définie le point d'entrée via le wsgi WSGIScriptAlias / /Users/username/Desktop/example/Site/wsgi-scripts/wsgi.py # Configuration du monde Daemon WSGIDaemonProcess example.com python-home=/Users/username/.local/share/virtualenvs/example-P5vj6Ml3 python-path=/Users/username/Desktop/example WSGIProcessGroup example.com <Directory /Users/username/Desktop/example/Site/wsgi-scripts> <IfVersion < 2.4> Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.4> Require all granted </IfVersion> </Directory> <Directory /Users/username/Desktop/example/Site/wsgi-scripts> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> -
How to use the email field from a django-allauth table as username for authentication?
I'm using Django 3.1.1 with Django-allauth to handle user authentication. Creating a user makes entries in these 3 tables: auth_user account_emailaddress account_emailconfirmation Since usernames are not needed in my application I inherited from the User model to accept an email address instead: from django.contrib.auth.models import AbstractUser class User(AbstractUser): """User model.""" username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() This worked like a charm. However I noticed it makes absolutely no sense to have email addresses stored in auth_user at this point, because allauth already stores them in account_emailaddress. I noticed a foreign key already exists from the field user in account_emailaddress to auth_user: class EmailAddress(models.Model): user = models.ForeignKey(allauth_app_settings.USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE) email = models.EmailField(unique=app_settings.UNIQUE_EMAIL, max_length=app_settings.EMAIL_MAX_LENGTH, verbose_name=_('e-mail address')) Is it possible to make the USERNAME_FIELD variable afield from the account_emailaddress table instead or are there different/better practices? Also, it would be nice if this change would work with the manage.py createsuperuser script, so I can still create an admin account from the console. Thanks in advance! -
Deploying React + Django on Digital Ocean or another Cloud Service
I'm planning to develop a Django web application that extended with the DRF as well as Frontend will be powered by React js. Right now my selection for the deployment of the project is the Digital Ocean platform. I'm ok with Django deployments with the Digital Ocean, but I'm confused when it comes to django+React because both the technologies have two different servers running. So I need to know how to run Django and React in the same server. Please if anyone is aware of this or if there is clear documentation mention it out Thanks. -
you cannot alter to or from M2M fields, or add or remove through= on M2M fields
models.py from django.db import models from django.conf import settings import random User = settings.AUTH_USER_MODEL class TweetLike(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) tweet = models.ForeignKey("Tweet", on_delete= models.CASCADE) timestamp = models.DateTimeField(auto_now_add= True) class Tweet(models.Model): parent = models.ForeignKey("", null = True, on_delete=models.SET_NULL) user = models.ForeignKey(User, on_delete= models.CASCADE, related_name="tweets") likes = models.IntegerField(default= 0 ) content = models.TextField(max_length=200, blank = True, null = True) image = models.FileField(upload_to='images/', blank = True, null = True) timestamp = models.DateTimeField(auto_now_add= True) class Meta: ordering = ['-id'] def serialize(self): return{ "id": self.id, "content": self.content, "likes": random.randint(0,200) } While Migrating my models i get the erro -
Form views Failed lookup for key [form] in [{'True': True, 'False': False, 'None': None}, {}, {}, {'catego': <Catego: Salade>}]
I've a form on a post category. I'd like user to post some pictures. And something wrong when I try to load the page. Do you have any idea? I'm beginning with Django. I'm using crispy form and in my template I'm simply using this {% crispy form %} with tags load. class CreatePictureForm(forms.ModelForm): def __init__(self,*args,**kwargs): super(CreatePictureForm, self).__init__(*args,**kwargs) self.helper = FormHelper() self.helper.form_method="post" self.helper.layout = Layout( Field("image",css_class="form-control",style="margin-bottom:10px"), Field("pictureoption",css_class="form-control",style="margin-bottom:10px"), ) self.helper.add_input(Submit('submit','Upload a pic',css_class="single-input textinput textInput form-control")) class Meta: model = Picture fields = [ 'image', 'pictureoption', ] Here is my views: @login_required(login_url='/cooker/login') def catego(request, slug): catego = Catego.objects.get(slug=slug) context = { 'catego': catego } # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = CreatePictureForm(request.POST) # check whether it's valid: if form.is_valid(): form.instance.catego = self.object form.instance.user = self.request.user form.save() return HttpResponseRedirect('/thanks/') else: form = CreatePictureForm() return render(request, 'post_catego.html', context, {'form': form}) @property def total_categories(self): return self.categories.count() -
Should I always use super().clean() when overriding clean() method on a modelform in Django
I have some custom validation in my model, as well as in the modelform in Django project. As I understood this explanation form official Django docs I always have to call super().clean() on modelform clean method, if I want to preserve the validation in the model, like this: class BookForm(forms.ModelForm): has_sequel = forms.BooleanField(initial=True) class Meta: model = Book fields = ['author', 'length', 'has_sequel', 'sequel'] def clean(self): super().clean() if self.cleaned_data['has_sequel'] and self.cleaned_data['sequel'] is None: raise ValidationError('You should indicate the sequel if the book has one.') However, if I don't use super().clean() it works perfectly. Now I am confused, do I need to use super().clean() or not? Note: I used code from this answer for simplicity. -
How to do i validate a password in a login form in Django
I have a login form in which i want to validate if the password is correct. And I try to do it using the clean method. In my form class i am using the clean method like so def clean(self): cd = self.cleaned_data print(self.username) # to debug actual_password = Person.objects.get(username=self.username).password if cd.get('password') != actual_password: self.add_error('password', 'That is not the correct password!') return cd This is the view for the login page: def user_login(request): if request.method == 'POST': form = PersonLoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = Person.objects.get(username=username) if user.password == password: return redirect('all-users/') print(form.errors) form = PersonLoginForm() context = { 'form': form, 'title': 'Login' } return render(request, 'index/login.html', context) Currently i am using this if statement to check if the password is correct: if user.password == password:. But i don't think that is the right way to do it so i am using the clean method. And the error i get when i go into my login page and fill in the credentials is this one: AttributeError: 'PersonLoginForm' object has no attribute 'username' This is what my full PersonLoginForm class looks like: class PersonLoginForm(forms.Form): username = forms.CharField(max_length=20, required=True) password = forms.CharField(max_length=100, required=True) def clean(self): cd = … -
Django(python) I can not display comments from the form on the html page
I am new to Django. I have not found the answer to my question anywhere. I can not display comments from the form on the html page. I am trying to display comments below a post, but an error occurs. I believe that the problem is in views, but I can't figure out what it is. views.py def get_name(request): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): form.save() return redirect('/barbers/') else: form = CommentForm() return render(request, 'main/post_detail.html', {'form': form}) post_detail.html <form action="/barbers/" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'body') models.py class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField(blank=True) date_add = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post, self.name) Error : "POST /barbers/ HTTP/1.1" 405 0 -
How to import all cities in Django_cities_light
I want to import the cities of USA and Canada in Django cities light, so I my settings.py file looks alike CITIES_LIGHT_TRANSLATION_LANGUAGES = ['en'] CITIES_LIGHT_INCLUDE_COUNTRIES = ['CA','USA'] CITIES_LIGHT_INCLUDE_CITY_TYPES = ['PPL', 'PPLA', 'PPLA2', 'PPLA3', 'PPLA4', 'PPLC', 'PPLF', 'PPLG', 'PPLL', 'PPLR', 'PPLS', 'STLMT',] After this : python manage.py migrate cities_light python manage.py manage cities_light But after all this : I just got the cities of Canada not USA I again did the step but data still not dumps , Any suggestion? -
Django armazena valor da variável?
Estou usando o Heroku para fazer uma aplicação Web usando Django. No localhost funciona tudo certo, porém no site na Web parece que ele não continua com os dados colocados nas variáveis. Por exemplo(isso é somente um exemplo representando meu caso, cada append no meu caso é gerado através de um request GET): class Exemplo: def __init__(self): variavel = [] def exemplo(self, cor): variavel.append(cor) ex = Exemplo() ex.exemplo('verde') ex.exemplo('vermelho') ex.exemplo('vermelho') ex.exemplo('verde') print(ex.variavel) $ ['vermelho', 'verde'] Esse exemplo mostra que no retorno não é mostrado tudo, às vezes só os últimos números No real está assim: 2020-09-22T14:05:58.471644+00:00 app[web.1]: {datetime.datetime(2020, 9, 22, 11, 5, 55, 428895): 'verde', datetime.datetime(2020, 9, 22, 11, 5, 58, 471335): 'vermelho'} enter image description here -
make an algorithm that receives a user and returns an array of username suggestions python
good morning, I need when a user is writing his username in a combo box I deploy a list of suggestions for that user, here I share my serializer because here I have to take that logic class UserSerializer(serializers.ModelSerializer): """User Create Serializer Does permit User creation, just retrieving its info. """ phone = serializers.RegexField( '\+?1?\d{9,15}$', allow_blank=True, ) # email = serializers.EmailField( # validators=[UniqueValidator(queryset=User.objects.all())] # ) birthday = serializers.DateField( validators=[LegalAgeValidator()] ) class Meta: model = User fields = ( 'id', 'email', 'username', 'first_name', 'last_name', 'phone', 'birthday', 'photo', 'gender', 'verified', 'phone_is_verified', 'email_is_verified', 'username_asigned', 'date_joined', ) read_only_fields = ( 'id', 'verified', 'phone_is_verified', 'email_is_verified', 'username_asigned', 'date_joined', ) -
Pie chart of chart.js is not working while using ajax
I am working with Chart.Js to show a pie chart. I need to call ajax for fetching data from my database. ajax function: function monthlyAttendanceReport(){ $("#selected-month").html(); array = yearMonthArr($("#selected-month").html()); year = array[0]; month = array[1]; $.ajax({ type: 'GET', url: '{% url "attendance:ajax-user-monthly-attendance-report" %}', data: { 'employee_id': '{{ employee.id }}', 'month': month, 'year': year }, dataType: 'json', success: function (data) { chart(); } }); } pie.js: function chart(){ // Get pie chart canvas var context = $("#monthly-attendance-status-pie-chart"); //pie chart data var monthlyAttendanceStatusdata = { labels: ["match1", "match2", "match3", "match4", "match5"], datasets: [{ label: "Attendance Status", data: [10, 50, 25, 70, 40], backgroundColor: [ "#DEB887", "#A9A9A9", "#DC143C", "#F4A460", "#2E8B57" ], borderColor: [ "#CDA776", "#989898", "#CB252B", "#E39371", "#1D7A46" ], borderWidth: 1 }] }; //options var options = { responsive: true, title: { display: true, position: "top", text: "Pie Chart", fontSize: 18, fontColor: "#111" }, legend: { display: true, position: "bottom", labels: { fontColor: "#333", fontSize: 16 } } }; //create Chart class object var monthlyAttendanceStatusChart = new Chart(context, { type: "pie", data: monthlyAttendanceStatusdata, options: options }); } $(document).ready(function() { $("#selected-month").html(initCurrentMonth()); $('#month-next-btn').attr('disabled', true); // chart(); monthlyAttendanceReport(); }); when I try this lines of code I find that no pie is generating. But when I … -
Why doesn't my request.user have groups in Django?
I've got an endpoint built with Django Rest Framework, to which I now want to add permissions so that only users belonging to a certain group can access an endpoint. So I'm using token based access and inspired by this example I'm trying to use the following code: class ReadPermission(BasePermission): def has_permission(self, request, view): return request.user.groups.filter(name=settings.GROUP_POST_DATA).exists() class MyEndpoint(mixins.ListModelMixin, viewsets.GenericViewSet): permission_classes = [IsAuthenticated, ReadPermission] http_method_names = ['get'] # etc But unfortunately I get anAttributeError: 'User' object has no attribute 'groups' Why doesn't the user object have groups? -
Run django project - localhost with ssl
In the Django project, Is any way possible to enable SSL(https) in the localhost environment? Example, the application should run https://localhost:8000 instead of http://localhost:8000 -
Set up different CORS rules based on the endpoint in Django
I'm trying to figure out a way to have different CORS rules based on the backend endpoint frontend would hit. So I can have /api endpoint with a CORS domain whitelist and /public-api without a CORS domain whitelist. This is needed because I have both internal endpoints I use for my own frontend, and a public JS widget that can be installed in any 3rd party domain. I've looked at django-cors-headers library, but it's regex configuration CORS_ORIGIN_REGEX_WHITELIST = [] works to let requests FROM a list of domains through. I'm looking for a way to have a regex to let requests TO my endpoints through or not. -
django rest framework calculate/modify result before sending to browser
view: class ChartAPIView(RetrieveAPIView): serializer_class = ChartSerializer queryset = Chart.objects.prefetch_related('attendees__person').all() def get_object(self): user = self.request.user last_updated = user.profile.data_last_updated user_events = self.queryset.filter(user=user).order_by('-created') data = { 'total': user_events.count(), 'last_updated': last_updated, "chart_data": user_events } return type('DashboardData', (), data)() Serializer: class DashboardSerializer(serializers.Serializer): total = serializers.IntegerField(read_only=True) last_updated = serializers.DateTimeField(read_only=True) chart_data = EventSerializer(read_only=True, many=True) Result: { "total": 2, "last_updated": "2020-09-22 04:49:25", "chart_data": [ { "title": "Daily Stand-up", "organizer": "mailbox@phanig.com", "duration": "0:30", "attendees": "soubhagyakumar666@gmail.com, mailbox@phanig.com", "created": "2020-08-25 06:11:54", "updated": "2020-09-17 04:50:25" }, { "title": "Daily Stand-up", "organizer": "mailbox@phanig.com", "duration": "0:30", "attendees": "soubhagyakumar666@gmail.com, mailbox@phanig.com", "created": "2020-08-25 06:11:54", "updated": "2020-09-17 04:50:25" }, { "title": "Daily Stand-up", "organizer": "mailbox@phanig.com", "duration": "0:30", "attendees": "soubhagyakumar666@gmail.com, mailbox@phanig.com", "created": "2020-08-25 06:11:54", "updated": "2020-09-17 04:50:25" } ] Here is my code and results i am getting . But, before sending result to browser i wants to do some modification Is there any way we can achive that. Basically i wants to modify user_events data by passing it to a utils function. Please have a look. Expected result: [{'created': '2020-08-24', 'duration': 510}, {'created': '2020-08-25', 'duration': 1260}] I have already the function which is converting to it but, as the user_events is a query set i amgetting error while getting the key.