Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Ajax request gets stuck after pressing "submit"
I am using AJAX to create a blog post object from the website, however, after pressing submit chrome freezes and the modal doesn't hide. I can see in the terminal the view is being called but my chrome freezes and I have to close the tab and then enter the website again. I have also tried using Safari but it happens there as well, I havent changed anything in my code I do not know why this is appening. My view for creating a post: @login_required def post_create(request): data = dict() if request.method == 'POST': image_form = ImageForm(request.POST or None, request.FILES or None) form = PostForm(request.POST) if form.is_valid() and image_form.is_valid(): post = form.save(False) post.author = request.user post.save() images = request.FILES.getlist('image') for i in images: image_instance = Images(file=i,post=post) image_instance.save() data['form_is_valid'] = True posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) else: data['form_is_valid'] = False else: image_form = ImageForm form = PostForm context = { 'form':form, 'image_form':image_form } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) my javascript for handling Ajax: $(document).ready(function(){ $(document).ajaxSend(function (event, jqxhr, settings) { jqxhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}'); }); var ShowForm = function(e){ e.stopImmediatePropagation(); var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType:'json', beforeSend: function(){ $('#modal-post').modal('show'); }, success: function(data){ $('#modal-post … -
Axios Authorization not working - VueJS + Django
I am trying to build an application using VueJS and Django. I am also using Graphene-Django library, as the project utilize GraphQL. Now, The authentication works fine and i get a JWT Token back. But when i use the token for other queries that need authentication, i got this error in Vue: "Error decoding signature" and the Django Log also returns this: graphql.error.located_error.GraphQLLocatedError: Error decoding signature jwt.exceptions.DecodeError: Not enough segments ValueError: not enough values to unpack (expected 2, got 1) the bizarre thing is that the same query when executed in Postman just works fine. As i mentioned in the title is use Axios for my requests, here's an example of a request: axios({ method: "POST", headers: { Authorization: "JWT " + localStorage.getItem("token") }, data: { query: `{ dailyAppoint (today: "${today}") { id dateTime } }` } }); Note: It uses 'JWT' not 'Bearer' because somehow 'Bearer' didn't work for me. -
AJAX post-ing of python dictionary leads to JSONDecodeError
I am passing a python dictionary to a template then $.post-ing it to a view in django, and when I try to json.loads it in my post view, I get JSONDecodeError. Anyone know how I can fix this? //1. vars to templates @login_required def bracket(request): ''' :param request: :return: ''' ... context = {'arr':json.dumps(tournament_games_json_serializable), 'nested':nested_tournament_games['rounds']}#{'latest_question_list': latest_question_list} return render(request, 'madness/bracket.html', context) //2. AJAX post of template var $.post('{% url "update_bracket" %}', { bracketData: "{{arr}}" }, function(data, status, xhr) { console.log(JSON.stringify(data)); var nested = JSON.stringify(data); }).done(function() { }) .fail(function(jqxhr, settings, ex) { alert('failed, ' + ex); }); //3. update_bracket @csrf_exempt def update_bracket(request): bracketData = request.POST['bracketData'] print(json.loads(bracketData)) ... where tournament_games_json_serializable is tournament_games_json_serializable {'round_1_game_1': {'players': (2, 3), 'winner': None, 'loser': None, 'done': False}, 'round_2_game_1': {'players': (1, 'winner of Round 1 Game 1'), 'winner': None, 'loser': None, 'done': False}} request.POST['bracketData'] '{"round_1_game_1": {"players": [2, 3]... json.loads(bracketData) json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 -
Initiate new instance from UpdateView
I am making an app to create repair work orders which also has an inventory app in it. I create and edit repair work orders using class-based views. I have a model for work orders; class Order(models.Model): """Maintenance work orders""" ... parts = models.ManyToManyField(UsedPart, blank=True) model for parts inventory class Part(models.Model): """List of company equipment""" partnum = models.CharField(max_length=20) amount_in_stock = models.PositiveIntegerField() price = models.FloatField(blank=True, null=True) vendr = models.ManyToManyField('Vendor', blank=True) ... And a model for instances of used parts class UsedPart(models.Model): """List of company equipment""" part = models.ForeignKey(Part, on_delete=models.CASCADE) amount_used = models.PositiveIntegerField() The way i wanted to implement it was. I create a UpdateView for an order. Check the parts i need in a m2m form and on submit create instances of this parts with associated amount. But i can't figure out how to initiate the instances from request. i wrote this, but id doesn't work class AddPartView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Order form_class = AddPartForm template_name_suffix = '_add_part' def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update(request=self.request) return kwargs def post(self, request, **kwargs): UsedPart.__init__(self) request.POST = request.POST.copy() request.POST['parts'] = request.POST.get('parts') return super(SomeUpdateView, self).post(request, **kwargs) form class AddPartForm(forms.ModelForm): class Meta: model = Order fields = ['parts', ] labels = {'parts': "", } def filter_list(self, … -
how to show list view in my urls based on string not integer in django
this is my model where I have people class where every person in this people class lives in a zone this is my people class and zone class class Zones(models.Model): zone_name = models.CharField(max_length=120) def __str__(self): return self.zone_name class People(models.Model): first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) address = models.TextField() phone_number = models.CharField(max_length=12) national_number = models.CharField(max_length=14) no_of_members = models.PositiveIntegerField(null=False, blank=False) zone = models.ForeignKey(Zones, null=False, blank=False, on_delete=models.CASCADE) def __str__(self): return self.first_name and how I want to show them the in the route /zone will be list of my zones, and when the user click on any of those zone I want him to see list of people who are in this zone here is my views class PeopleView(ListView): model = People template_name = "people.html" context_object_name = 'people_list' class ZoneView(ListView): model = Zones template_name = "zones.html" context_object_name = 'zones_list' class PeopleDetailView(DetailView): model = People template_name = "people_detail.html" and here is my urls urlpatterns = [ path('admin/', admin.site.urls), path('people/', PeopleView.as_view(), name='people'), path('zone/', ZoneView.as_view(), name='zone'), path('zone/<int:pk>/', PeopleDetailView.as_view(), name='detail'), ] and here is my html template for zone <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Zones List</title> </head> <body> <h1>Zones List</h1> <ul> {% for zone in zones_list %} <a href="#"><li>{{ zone }}</li></a> {% endfor %} </ul> </body> </html> -
Implementing MVC pattern with Django Rest Framework
I was wondering how could I implement a MVC pattern on a Django Api project, when I start a django project it gives me the apps.py, admin.py, models.py and the views.py , I understand the the models, should be the "M", and the views the "V", but as i'm using the project like an api, the view would be an Angular or React App, so where I put the logical ? Where is the right place to put the "C" controller on a django rest framework project, is it on views.py ? -
Select one field from a filter in Django
I have a quick question: How can I select only one field from my filter form in Django? I'm currently displaying the whole thing: <div class="container"> <form method="GET" > {{ filter.form.Precio|crispy }} <button class="btn btn-primary" type="submit">Aplicar filtros</button> </form> </div> I'd like to separe the filter form. I used to do this: {{ form.username }} but it doesn't seem to work... EDIT: This is filters.py class PubFilters(django_filters.FilterSet): Precio = django_filters.NumericRangeFilter() o = django_filters.OrderingFilter( choices=( ('-Más nuevo', 'Más nuevo'), ('Más nuevo', 'Menos nuevo') ), fields={ 'Fecha': 'Más nuevo', } ) class Meta: model = publicaciones fields = ['Título', 'Precio', 'Categoría'] fields ={ 'Título': ['icontains'], } -
How to respond with child object based on its parent id?
I have a parent class and a child class, like so: class Animal(models.Model): age = models.IntegerField() class Bird(Animal) wingSpan = models.DecimalField() Here's the view to get birds: class BirdViewSet(viewsets.ModelViewSet): queryset = Bird.objects.all() serializer_class = BirdSerializer And here is the serializer: class BirdSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Bird fields = ['age', 'wingSpan'] In the database, jango appropriately created an animal_prt_id field in the birds table, so that this view/serializer pair knows where to find the age, which is mapped to the parent class, Animal. How to make a view/serializer pair that does the opposite, meaning, it receives the id of an Animal and responds with the complete Bird (or with any other Animal subclass I might have)? -
DRF Update cross-table data
In my project I have Job, Skill and JobSkills models: class Job(models.Model): name = models.CharField( max_length=127, verbose_name=_('Job name'), ) description = models.TextField( verbose_name=_('Job description'), ) class Skill(models.Model): name = models.CharField( max_length=63, verbose_name=_('Skill name'), ) class JobSkills(models.Model): class Meta: verbose_name = 'Job skill' verbose_name_plural = 'Job Skills' unique_together = ['job', 'skill'], job = models.ForeignKey( Job, on_delete=models.CASCADE, related_name='job_skills', null=True, ) skill = models.ForeignKey( Skill, on_delete=models.CASCADE, related_name='job_skills', null=True, ) # generate list of lists of number from 1 to 10 like ((0, 0), (1, 1), ... (10,10)) SKILL_LEVEL = [(i, i) for i in range(1, 11)] level = models.IntegerField( choices=SKILL_LEVEL ) One job has many skills with skill level. User can add skills to job from default list and can not create new skill example data: PUT /api/jobs/1 { "name": "Job", "description": "Job description", "job_skills": [ { "id": 1, # job_skill_id "skill": { "id": 4, # skill_id }, "level": 7 } ], } class JobViewSerializer(serializers.ModelSerializer): job_skills = JobSkillsSerializer(many=True) def update(self, instance, validated_data) -> Job: job_skills = validated_data.get('job_skills') instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.save() But how to write the right logic for update Job skills? I need add new relation between Job and Skill if it doesn't exist, change Job skill … -
Database Management on Django and Github
I am trying to set up a website using the Django Framework. Because of it's convenience, I had choosen SQLite as my database since the start of my project. It's very easy to use and I was very happy with this solution. Being a new developer, I am quite new to Github and database management. Since SQLite databases are located in a single file, I was able to push my updates on Github until that .db file reached a critical size larger than 100MB. Since then, it seems my file is too large to push on my repository (for others having the same problem I found satisfying answers here: GIT: Unable to delete file from repo). Because of this problem, I am now considering an alternative solution: Since my website will require users too interact with my database (they are expected post a certain amount data), I am thinking about switching SQLite for MySQL. I was told MySQL will handle better the user inputs and will scale more easily (I dare to expect a large volume of users). This is the first part of my question. Is switching to MySQL after having used SQLite for a while a good idea/good … -
Attribute error : 'WSGIRequest' object has no attribute 'get'
I've been working on a project lately and got the above error. It says " Error during template rendering".I have a similar model, which works perfectly fine. I've looked for similar errors but got none matching my situation. I don't know where I went wrong. It would be great if I get helpful answers. Models.py class ServiceTax(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="service_tax",null=True,blank=True) name=models.CharField(max_length=100) percent=models.FloatField(default='0') add_amount=models.IntegerField(default='0') def __str__(self): return self.name Forms.py class ServiceTaxForm(forms.ModelForm): class Meta: model = ServiceTax fields = "__all__" widgets = { 'name' : forms.TextInput(attrs={'class': 'form-control'}), 'percent' : forms.NumberInput(attrs={'class': 'form-control','step':'0.01'}), 'add_amount' : forms.NumberInput(attrs={'class':'form-control','maxlength':5}), } labels={ 'add_amount': "Additional Amount" } Views.py def tax_form(request,id=0): if request.method == 'GET': if id == 0: form = ServiceTaxForm(request) else: tax = ServiceTax.objects.get(pk=id) if tax in request.user.service_tax.all(): form = ServiceTaxForm(request,instance=tax) else: return redirect('/revenue/tax') return render(request,'tax-form.html',{'form':form}) else: if id==0: form = ServiceTaxForm(request,request.POST) if form.is_valid(): name = form.cleaned_data["name"] percent = form.cleaned_data["percent"] add_amount = form.cleaned_data["add_amount"] t = AnnualTax( name=name, percent=percent, add_amount=add_amount, ) t.save() request.user.service_tax.add(t) else: tax = ServiceTax.objects.get(pk=id) if tax in request.user.service_tax.all(): form = ServiceTaxForm(request,request.POST,instance=tax) if form.is_valid(): name = form.cleaned_data["name"] percent = form.cleaned_data["percent"] add_amount = form.cleaned_data["add_amount"] tax_obj = ServiceTax.objects.get(pk=id) tax_obj.name = name tax_obj.percent = percent tax_obj.add_amount = add_amount tax_obj.save() return redirect('/revenue/tax') tax-form.html {% extends 'base.html' %} {% load crispy_forms_tags %} … -
Django Rest API Url Pattern to handle . (dot) symbol
Creating Django REST API, Need suggestions to handle the .(dot char) in the urlpatterns. Below is the example detail: I have a Model (test) with name as one of the fields and name value is of format ABC.XYZ Below URL pattern does not work when name = ABC.XYZ url(r'^tests/(?P<string>[\w\-]+)/$', views.tests.as_view(), name='api_tests_name') -
Django3: Dynamic queryset function allocation performance
i am just experimenting on how to 'dynamically allocate queryset functions' and i would like to know the performance issues i might face later on. My querysets are working perfectly but i am a little skeptical about them. Please have a look at my code: settings.py: ... TODO_PRIORITY = ( ('LOW', 'Low'), ('MEDIUM', 'Medium'), ('HIGH', 'High'), ) ... models.py from django.db import models from django.contrib.auth import get_user_model from django.utils import timezone from .manager import TodoManager from django.conf import settings User = get_user_model() TODO_PRIORITY = getattr(settings, 'TODO_PRIORITY', None) assert TODO_PRIORITY is not None, "Your settings file is missing `TODO_PRIORITY` variable" assert isinstance(TODO_PRIORITY, tuple), "`TODO_PRIORITY` must be a tuple" # Create your models here. class Todo(models.Model): class Meta: ordering = ('start_time',) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="todos") content = models.TextField(max_length=500, blank=False) start_time = models.DateTimeField(default=timezone.now) end_time = models.DateTimeField(blank=False) priority = models.CharField(max_length=6, choices=TODO_PRIORITY, default="MEDIUM") timestamp = models.DateTimeField(auto_now_add=True) objects = TodoManager() @property def todo_id(self): return self.id manager.py from django.db import models from django.utils import timezone from django.conf import settings now = timezone.now() today = now.replace(hour=0, minute=0, second=0, microsecond=0) tomorrow = today + timezone.timedelta(days=1) TODO_PRIORITY = getattr(settings, 'TODO_PRIORITY', None) assert TODO_PRIORITY is not None, "Your settings file is missing `TODO_PRIORITY` variable." assert isinstance(TODO_PRIORITY, tuple), "`TODO_PRIORITY` must be … -
How can I generate an annotated Django queryset that checks value of across rows within the same model that are also within a specific date range?
Looking for some guidance as I'm not making progress after a week of jumping between the Django documentation for Subqueries, Window functions, and dozens of other SO answers. I'm about 20 different queryset variations in and none are yielding the right results. WHAT I HAVE TimestampedModel(models.Model): # Attributes label = CharField() timestamp = DatetimeField() # Relationships traits = ForeignKey('TraitModel') TraitModel(models.Model): # Attributes value = IntegerField() WHAT I'M TRYING TO DO I would like to annotate a queryset of the TimestampedModel with a count on how many other rows within a certain date range meet a specific threshold. Said in another way, I want to detect whenever for each TimestampedModel object, there is a consecutive dip of trait values for each of the surrounding rows (based on a variable date range around each specific row). A more concrete example: Day 1: 10 traits Day 2: 11 traits Day 3: 10 traits Day 4: 13 traits Day 5: 2 traits Day 6: 3 traits Day 7: 3 traits Day 8: 11 traits ... I want to find if there are at least X consecutive timestamps dipping below Y number of traits. Using the example above, it would detect if there were 3 … -
Update item in django DetailView
I am trying to understand django better and have worked on the following simple app. I am trying to have (recurring) tasks which belong to a certain project. At the top of a task list I will have the task that has not been performed for the longest time. Clicking on a task will mean that it is/has been performed and I want to update the field last_performed to today and then reload the view. So far I have solved it like this. class Project(models.Model): project_name = models.CharField(max_length=100) class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) task_name = models.CharField(max_length=100) last_performed = models.DateField('last time peformed') The template for the task list is <h1>{{ project.project_name }}</h1> <ul> {% for task in project.task_set.all %} <li>{{ task.task_name }} ({{ task.last_performed }}) <a href="{% url 'update' 1 task.task_name %}">Perform</a> </li> {% endfor %} </ul> and the view.py class ProjectView(generic.ListView): template_name = 'tasks/index.html' context_object_name = 'project_list' def get_queryset(self): return Project.objects.all() class TaskView(generic.DetailView): model = Project template_name = 'tasks/detail.html' def update(request, project_id, task_name): project = get_object_or_404(Project, pk=project_id) task = project.task_set.filter(task_name=task_name).first() task.last_performed = timezone.now().today() task.save() return render(request, 'tasks/detail.html', {'project': project}) I have the following patterns urlpatterns = [ path('', views.ProjectView.as_view(), name='index'), path('<int:pk>/', views.TaskView.as_view(), name='detail'), path('<int:pk>/<task_name>/', views.update, name='update'), ] Now my … -
GeoDjango store user location from request
I'm using GeoDjango version 2.2.6. Is there a way to get the users location from just their request and store them? I want to keep track of any location changes made by the user. -
Page not found when opening link as new window
Getting the error message; Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/students/undefined When I try and open a link as a new window on Django, this is the code I wrote; <a href="#" onClick="MyWindow=window.open('https://www.youtube.com/watch?v=fNk_zzaMoSs','MyWindow','width=600,height=300'); return false;">Click Here</a> The YouTube video opens in a new window, but I get the error message in my initial window, the one with my current project open -
Django - How to get model id when clicked on it
My django application purpose is so simple: user solves algorithm from some source (for instance, Hackerrank), and returns back to my application and sends feedback about result (these algorithms are given to users by me as a task). Now I want to get id of task when clicked on send button after feedback wrote. Because from admin dashboard I could see feedback was written for which task. BTW, I'm getting no such column: algorithmtrackerapp_taskfeedback.task_id error because of thinking task as a foreign key for feedback. Here are my codes: views.py: def index(request): tasks = Task.objects.all().order_by('-task_deadline') task_feedbacks = TaskFeedback.objects.all() form = CreateFeedbackForm() context = { 'tasks': tasks, 'task_feedbacks': task_feedbacks, 'form': form } if request.method == 'POST': form = CreateFeedbackForm(request.POST) if form.is_valid(): form.save() return render(request, 'index.html', context) models.py: class Task(models.Model): task_name = models.CharField(max_length=100) task_url = models.URLField(max_length=300, blank=True, null=True) task_source = models.CharField(max_length=50, blank=True, null=True) task_deadline = models.DateTimeField() uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.task_name class TaskFeedback(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) sender = CurrentUserField() is_solved = models.BooleanField(default=False) feedback_content = models.TextField(max_length=500, null=True, blank=True) date_added = models.DateTimeField(auto_now_add = True) def __str__(self): return self.feedback_content This is my interface: -
DRF Serializers taking a lot of time to execute , What other option do i have to send the serialized response in DJANGO
So I am trying to send complex nested JSON response from one of the endpoints in API developed in DJANGO , I am using DRF for that purpose , they're great but they're really slow . I was wondering what other option do I have . The response needs to be serialized and it's nested , complex . DRF Serializers were working great until the dataset grew and now it's really slow . -
Pytest failing to import third-party packages
So I am stuck with pytest. My setup is a django setup with docker-compose. Anytime I run pytest, I get errors like this Hint: make sure your test modules/packages have valid Python names. Traceback: lib/python3.6/site-packages/compressor/tests/test_signals.py:4: in <module> from mock import Mock E ModuleNotFoundError: No module named 'mock' another one E _pytest.config.ConftestImportFailure: (local('/app/lib/python3.6/site-packages/testfixtures/tests/conftest.py'), (<class 'ModuleNotFoundError'>, ModuleNotFoundError("No module named 'sybil'"), <traceback object at 0x7fb8a7a4e780>)) Seems like it's having problem importing third-party libs, how do I ignore these kinds of errors. -
django-plotly-dash serve css files locally
I am trying to serve css files locally in a DjangoDash app using django-plotly-dash. Simpleexample.py app = DjangoDash('SimpleExample', serve_locally=True) app.css.append_css("path_to_css") app.layout = html.Div([ html.Div( className="app-header", children=[ html.Div('Plotly Dash', className="app-header--title") ] ), html.Div( children=html.Div([ html.H5('Overview'), html.Div(''' This is an example of a simple Dash app with local, customized CSS. ''') ]) ) ]) simpleexample.html {% extends 'base.html' %} {% load static %} {% block content %} {% load plotly_dash %} {% plotly_app name='SimpleExample' ratio=0.45 %} </div> {% endblock %} header.css and topography.css are the files as described here: https://dash.plotly.com/external-resources. According to these: https://github.com/GibbsConsulting/django-plotly-dash/issues/121 and https://github.com/GibbsConsulting/django-plotly-dash/issues/133, the issues regarding this should be fixed. However the css styling does not render-- What am I missing here? There was a suggestion in the above github issues that we can use django template rather than iframe. I could not find much documentation on that -- can anyone point me there? Thank you. -
Django Manytomany Autocomplete Lookup
Is it possible to adopt the Django many to many autocomplete loopup for form? I know how to adopt the Django normal loopup but not the many to many with autocomplet outside of admin page. For the normal loopup this will work by adding this into the html template: <a onclick="return showRelatedObjectLookupPopup(this);" class="related-lookup" id="lookup_id_object" title="Lookup" href="/admin/..."></a> -
Django search form with multiple filter
in my Django web site I've got a User page where are listed all the items the User added to the database. There's a search form for the user to search into its own items. The problem is that the search form doesn't work. I'm a little bit confused about how to filter through the database because, first I've filtered all the items in order to show only the ones added by the User logged, and then I should filter through these based on the user input. Hope someone could help me, thanks! The 'def look()' is what I tried but doesn't work Views.py class userListView(ListView): model = Info template_name = 'search/user.html' paginate_by = 10 def get_queryset(self): qs = super().get_queryset() qt = qs.filter(utente=self.request.user) return qt def look(self, request, *args, **kwargs): print('FORM POSTED WITH {}'.format(request.POST['cerca'])) srch = request.POST.get('cerca') if srch: sr = Info.objects.filter(srch = Subquery(qt)) if sr: return render (self.request, 'search/user.html', {'sr':sr}) else: return render(self.request, 'search/user.html') else: return render(self.request, 'search/user.html') user template html <div class="add"> <div class="posted"> <div class="head"> <h2> YOUR LIST </h2> <div class="form"> <form method="post" action="{% url 'user' %}"> {%csrf_token%} <input type="text" name="cerca" class= "form-control" placeholder=" Type Album or Band Name..."> <!-- <button type="submit" name="submit">Search</button> --> </form> </div> </div> … -
Django - Foreign key, admin and forms
I’m working on a Django Project (i’m a beginner) and i have a small problem. I have different model with Foreign_Key. And also I have Forms to implements model. My problem, is not to big i think : I want the id + name instance on my admin or on my forms. Actually i have the value in def __str__(self): return self.nom I can’t do return self.id because it’s Int type. example of my models.py class Affaires(models.Model): id = models.PositiveSmallIntegerField(primary_key=True) nom = models.CharField(max_length=50) adresse = models.CharField(max_length=100, blank=True, null=True) cp = models.CharField(max_length=5, blank=True, null=True) ville = models.CharField(max_length=50, blank=True, null=True) dessinateur = models.PositiveSmallIntegerField(blank=True, null=True) conducteur = models.PositiveSmallIntegerField(blank=True, null=True) chefdeprojet = models.PositiveSmallIntegerField(blank=True, null=True) cloture = models.IntegerField() class Meta: managed = True db_table = 'affaires' def __str__(self): return self.nom Have you got an idea ? -
Caching on Django Rest Framework GenericViews
I don`t find infos on how caching of Django Rest Framework generic views is configured. Do I have to override the get message and add an own @method_decorator? This feels ungeneric to me. class BlogTags(generics.ListAPIView): queryset = CustomContentBlogTag.objects.all() serializer_class = CustomContentBlogTagSerializer permission_classes = [AllowAny] @method_decorator(cache_page(60 * 60 * 24)) def get(self, request, *args, **kwargs): return super().get(request, *args, **kwargs) Docs I found: Caching: https://www.django-rest-framework.org/api-guide/caching/ Generic views: https://www.django-rest-framework.org/api-guide/generic-views/ In the generic views docs, there is a sentence, that the queryset is cached somehow. But what, if I want the whole view to be cached?