Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Filter: Filter two models and get output as xml file
I currently have these models in my models.py file: class category(models.Model): name = models.CharField(max_length=200) flag = models.BooleanField(default=True) def __str__(self): return self.name class security_incident(models.Model): asset = models.CharField(max_length=200) actor = models.CharField(max_length=200) action = models.CharField(max_length=200) cia = models.ForeignKey(category, on_delete=models.CASCADE) def __str__(self): return self.action class attack(models.Model): name = models.CharField(max_length=100) defense_mechanism = models.CharField(max_length=100) action = models.ForeignKey(security_incident, on_delete=models.CASCADE) def __str__(self): return self.name class adtree(models.Model): goal = models.CharField(max_length=200) security_incident = models.ManyToManyField(security_incident) attack = models.ManyToManyField(attack) def __str__(self): return self.goal The case is that a user should input a goal (adtree model) in a filter form and then select at least two checkboxes (categories - there are in total three of them: confidentiality, integrity and availability). The view should then check if it exists a match for the goal with asset in the security incident model ( ex. goal = database and asset = database). The filter(or the view, I am not sure where I should do this) should return all security incidents for the selected categories as well as the attacks and defense mechanisms from the attack model. The goal is to return this as a dictionary or string and from there serialize it into an xml output. Here is my current filters.py file: class ADTreeFilter(django_filters.FilterSet): goal = … -
Must provide query string error when getting data from graphql api react js next js
when i use this code , it is saying please provide query string.. i am trying to get data from graphene api in django export async function getStaticProps() { const query_data = `query{ forumPost(category:"web"){ forumPostAuthor forumPostBody forumPostCode forumPostVote forumPostCategory forumPostLanguage1 forumPostLanguage2 forumPostLanguage3 forumPostLanguage4 forumPostLanguage5 id } }`; const request_parameters = { method: 'POST', header: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query_data }), }; const res = await fetch('http://127.0.0.1:8000/', request_parameters); const data = await res.json(); return { props: { data } }; } -
how to update the time_update from the form of the object?
how to update the time_update from the form of the object (file) that is attached to the main post? class AttachmentFileCreateView(SuccessMessageMixin, CreateView): model = Attachment template_name = 'modules/files/attachment_create.html' form_class = AttachmentForm success_message = "Файл для поста успешно добавлен!" def form_valid(self, form): form.instance.created_by = self.request.user form.instance.post_id = self.kwargs['pk'] #? how to update time_update included in the post? print(form.cleaned_data) return super().form_valid(form) def get_success_url(self): return reverse_lazy('files:file_detail', kwargs={'cat_slug': self.object.file.category.slug, 'slug': self.object.file.slug}) I hope there is an answer) -
Python3.7 and Django3.2.3
I am new to Python3.7 and Django and I am trying to build a small webapp by following instructions from a book. While I am trying to edit entry and submit, it always """Reverse for ' topic' not found. ' topic' is not a valid view function or pattern name.""" appeared, Here are some of my files: views.py from django.shortcuts import render from .models import Topic, Entry # Create your views here. from .forms import TopicForms, EntryForms from django.http import HttpResponseRedirect from django.urls import reverse def index(request): """主页内容""" return render(request, 'learn_logs/index.html') def topics(request): """显示所有的主题""" topics = Topic.objects.order_by('date_added') # 查询数据库, -> 请求提供Topic对象, 并按属性date_added对他们进行排序 context = {'topics': topics} # 一个将要发送给模块的上下文,字典形式, 键是访问数据的名称, 之是我们要发送给模块的数据 return render(request, 'learn_logs/topics.html', context) def topic(request, topic_id): """显示单个主题及所有的条目""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learn_logs/topic.html', context) def new_topic(request): if request.method != 'POST': """未提交数据,创建一个新表单""" form = TopicForms() else: # POST提交数据,对数据进行处理 form = TopicForms(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learn_logs:topics')) """ 我们导入了HttpResponseRedirect类,用户提交主题后我们将使用这个类将用户重定向到网页topics。函数reversed() 根据指定的URL模型确定URL,这意味着Django将在页面被请求时生成URL。我们还导入了刚才创建的表单TopicForm """ context = {'form': form} return render(request, 'learn_logs/new_topic.html', context) def new_entry(request, topic_id): """在特定的主题中添加新条目""" topic = Topic.objects.get(id=topic_id) if request.method != "POST": form = EntryForms() else: # post 提交的数据,对其进行处理 form = EntryForms(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic.id])) … -
How can I use django with socketio so that I can do real time communication between my arduino and my server ie on my site?
I want to read data in realtime from my arduino to my site using serial port communication. -
how can I insert input data of form in form action url
When the data is entered in the input field of form . I want it to submit that data in /wiki/that_data through form action. How do I do that?.I tried wiki/{{ title }} ,passing title as a dict in render function but it doesn't work. Can someone explain why this doesn't work? Or,guide me to good resource to learn this. layout.html <form action="/wiki/{{ title }}" method="post"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> with this view : views.py def EntryPage(request, title): if request.method == "POST": title = request.POST return render(request, "encyclopedia/entrypage.html", { "title" : title, "getentry": util.get_entry(title) }) -
Select which fields to export in django-import-export
I'm adding the django-import-export to the admin in my app. One thing I wanted to do was to offer the possibility of selecting in the admin page of selecting which fields to export. I searched for this topic but I only came across two questions with no answers. Is it possible to add the possibility to dynamically choose which fields to export from the admin page? Thanks. -
Django: Abstract models cannot be instantiated for models for retrieving data
I am working on a project which has one abstract model and one main model for Djongo. when i try to insert a value ,it is getting inserted without errors. But when i try to retrieve the data i get " Abstract models cannot be instantiated" . Here is my model: question=models.CharField(max_length=200,null=True) options=ArrayField(models.CharField(max_length=50)) answer=models.CharField(max_length=50,null=True) types=models.CharField(max_length=50,null=True) class Meta: abstract=True class ExamDetails(models.Model): _id=ObjectIdField() exam_id=models.IntegerField(null=False,default=0) questions=models.EmbeddedField(model_container=Exam_questions) objects = models.DjongoManager() here is my code for querying: def exams_questions(request,exam_id): get_exams=ExamDetails.objects.filter(exam_id=3) print(get_exams) return HttpResponse("hello") # have given this response only for testing when i try to iterate or get values in the variable get_exams im getting "Abstract models cannot be instantiated" error. Please help! Thanks -
ModuleNotFoundError: No module named 'learning_logs.settings' in Django
For some reason i am not able to migrate file from one to another. I am working on a Django project from the book "Python crash course". CMD prompt message- (ll_env) C:\Users\visha\learning_log>python manage.py makemigrations learning_logs ModuleNotFoundError: No module named 'learning_logs.settings' this is in the command prompt. I checked the settings file and i did include the 'learning_logs' with a comma in installed apps tuple. Here is the code of the python ' settings' file INSTALLED_APPS = [ # default apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # my apps 'learning_logs',] I had seen solutions where they had to only include the comma but i have invcluded it and still get the error in command prompt. -
Commaseparated form field in django
Suppose I have a following fields class SomeField(forms.Charfield): def to_python(self, value): value = super().to_python(value) # some cleaning logic return value def validate(self, value): super().validate(value) #some logic class AnotherField(forms.Charfield): def to_python(self, value): value = super().to_python(value) # some cleaning logic return value def validate(self, value): super().validate(value) #some logic class CommaSeparatedSomeField(Field): base_class=SomeField class CommaSeparatedAnotherField(Field): base_class=AnotherField What is the best way to implement above CommaSeparated***Field, where comma-separated means just a text field, with comma-separated values? I tried to represent it with a CharField, splitted by commas, but now I need to validate and clean each value in a list using the base_class logic. Here I encountered a problem, since all logic is not class methods. -
Can not create a superuser in my python django project
I ran makemigration and migrate and the ran OK. When I run python manage.py createsuperuser, after keying in my info I get TypeError: save() got an unexpected keyword argument 'force_insert' -
Storing files Django
I am building an website using django in which I have to store a lot of files. I have a view, which takes file from the user and saves it. def store(request): if request.method == "POST": sender = request.POST['sender'] file = request.POST['file'] I have a model in which i save these data: class t_data(models.Model): sender = models.TextField() file = models.FileField(upload_to='files') and I have this on my settings file: MEDIA_ROOT = os.path.join(BASE_DIR,"media") MEDIA_URL = '/media/' Many files can have same name. Should I rename before saving them? How should I save them. There will be many users, So how can I distinguish files for each user? my question is : **What is the best way to store files in a django application?**Please Thank you -
Anonymous users in django many to many fields
I am trying to make a simple blog in django. I have a django ManyToManyField in my models to keep the record of likes on a blog post. It is working just fine but it only allows authenticated users to like a post but not anonymous users. I also want anonymous users to be able to like a post. Is there a way to do it? here is my models.py class Posts(models.Model): post = models.TextField(max_length=1500) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) likes = models.ManyToManyField(User, related_name="post_likes") here is my vies.py def likes(request): if request.method == "POST": post = get_object_or_404(Posts, id=request.POST.get("like_button")) post.likes.add(request.user) here like_button is a name of a input in form that has value=id of a post. -
Django admin and wagtail static files not found
I have a Django site with wagtail and puput integrated into it, as well as whitenoise handling the static files. For some reason, in production, the static files are working for the regular site, but not for the django admin or wagtail admin. Also, this may be a separate issue, but when I set debug = True, the main site throws a 500 error, while the two admin sites remain unchanged. urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', views.home, name='home'), path('clubs/', include('clubs.urls', namespace="clubs")), path('members/', include('members.urls', namespace="members")), path('videos/', include('videos.urls', namespace="videos")), path('cms/', include(wagtailadmin_urls)), path('documents/', include(wagtaildocs_urls)), path('blog/', include(wagtail_urls)), path('posts/', include(puput_urls)), ] + static( settings.STATIC_URL, document_root=settings.STATIC_ROOT ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' folder structure staticfiles/ admin/ wagtailadmin/ ... -
Django logging PermissionError with TimedRotatingFileHandler
I am trying to make django create and rotate new logs every 10 minutes using TimedRotatingFileHandler. My settings is as follows: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class':'logging.handlers.TimedRotatingFileHandler', 'filename': 'logs/site.log', 'backupCount': 10, 'when':'m', 'interval':10, }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } The first log file is created successfully. But when it is time to rotate the log file, I get the following error: PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'F:\\logs\\site.log' -> 'F:\\logs\\site.log.2021-05-22_19-18' How do I configure the logging so that the current log is copied to a timed log and new data written to the main log file? -
Using custom django model in DRF Token Authentication
I want to connect a custom User model with the Django Rest Framework TokenAuthentication module. I have tried the followings: settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'myapp.authentication.MyOwnTokenAuthentication', ), } authentication.py: class MyOwnTokenAuthentication(TokenAuthentication): model = MyOwnToken models.py: class User(models.Model): name = models.CharField(max_length=100) email = models.EmailField() birth = models.DateField() class MyOwnToken(models.Model): key = models.CharField(_("Key"), max_length=40, primary_key=True) user = models.OneToOneField( User, related_name='auth_token', on_delete=models.CASCADE, verbose_name="User" ) created = models.DateTimeField(_("Created"), auto_now_add=True) views.py: class UserApi(APIView): authentication_classes = [MyOwnTokenAuthentication] permission_classes = [IsAuthenticated] #returns all data def get(self, request): alldata=User.objects.all() alldata_serialized=UserSerializer(alldata, many=True) return Response(alldata_serialized.data) The token generates fine but when I call the UserApi get then it gives WrappedAttributeError: 'User' object has no attribute 'is_active' can anyone help?? Thanks in advance. -
How to get Django to make some files public and media files private on AWS S3 (no 403 errors)?
I'm using boto3 and django-storages to serve files from AWS S3. I'd like my static files to be public but other files to be private. I've got it kinda sorta working but not quite. My static files are being served as if they're private, with a pre-signed key. In my template file when I use: <img src="{% static 'images/3d-house-nav-gray.png' %}"> instead of what I want <img src="https://mybucket.s3.amazonaws.com/static/images/3d-house-nav-gray.png"> I'm getting <img id="home-img" src="https://mybucket.s3.amazonaws.com/static/images/3d-house-nav-gray.png?AWSAccessKeyId=AKIA1234564LQ7X4EGHK&amp;Signature=123456gIBTFlTQKCexLo3UJmoPs%3D&amp;Expires=1621693552"> This actually works when the templates are rendered from the server as part of an HTTPResponse, but not when an image like this is simply included as part of, say, a .css file. In that case I'll get: Failed to load resource: the server responded with a status of 403 (Forbidden) (I find I can copy and paste the problematic image link and replace the &amp; with an & then I have access, a further mystery.) Here is how I have AWS configured: AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = 'mybucket' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_DEFAULT_ACL = None AWS_LOCATION = 'static' STATICFILES_STORAGE = 'myapp.storage_backends.StaticStorage' DEFAULT_FILE_STORAGE = 'myapp.storage_backends.MediaStorage' AWS_S3_URL = 'https://%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATIC_DIRECTORY = '/static/' MEDIA_DIRECTORY = '/media/' STATIC_URL = AWS_S3_URL + STATIC_DIRECTORY MEDIA_URL = … -
Django AttributeError: 'Cart' object has no attribute 'get'
I am getting this error on my django project: Request Method: GET Request URL: http://127.0.0.1:8000/cart/ Exception Type: AttributeError at /cart/ Exception Value: 'Cart' object has no attribute 'get' and here is carts.views.py: from django.shortcuts import render, redirect, get_object_or_404 from store.models import Product from .models import Cart, CartItem # Create your views here. def _cart_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product= product, quantity= 1, cart= cart, ) cart_item.save() return redirect('cart') def cart(request): return render(request, 'store/cart.html') I tried: rewrite the name of class 'Cart' use objectDoesnotexist instead of DoesnotExit double check the names of the classes in models.py I am not able to debug this error. I overlooked my codes many times, but cant able to understand where is the error being generated. Thanks in advance. -
Django 3.2 LookupError: Model not registered
While trying to upgrade an existing project to Django 3.2 (from 2.2), I have been getting the following error: ... from .permissionmodels import * # nopyflakes File "/home/user/miniconda3/envs/app-web-py38-test/lib/python3.8/site-packages/cms/models/ permissionmodels.py", line 19, in <module> User = apps.get_registered_model(user_app_name, user_model_name) File "/home/user/miniconda3/envs/app-web-py38-test/lib/python3.8/site-packages/django/apps /registry.py", line 273, in get_registered_model raise LookupError( LookupError: Model 'user_accounts.CustomUser' not registered. The custom model is located in apps/user_accounts/models.py and looks like this from django.db import models from django.contrib.auth.models import AbstractUser from django.db import models from .managers import CustomUserManager class CustomUser(AbstractUser, PermissionsMixin): username = None email = models.EmailField(('email address'), unique=True) # add additional fields in here profile_picture = models.ImageField(upload_to='profile/', blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email The installed apps are as follows INSTALLED_APPS = [ # this app is at the top because it defines a custom user model for the whole project 'apps.user_accounts', 'djangocms_admin_style', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', #'django.contrib.contenttypes.models.ContentType', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', #after project creation# #Django CMS stuff 'django.contrib.sites', 'cms', 'menus', 'treebeard', 'sekizai', 'filer', 'easy_thumbnails', 'mptt', 'djangocms_link', 'djangocms_file', 'djangocms_picture', 'djangocms_video', 'djangocms_googlemap', 'djangocms_snippet', 'djangocms_style', 'djangocms_column', 'djangocms_text_ckeditor', 'djangocms_comments', 'bootstrap4', #Aldryn News Blog 'aldryn_apphooks_config', 'aldryn_categories', 'aldryn_common', 'aldryn_newsblog', #'aldryn_newsblog.apps.AldrynNewsBlog', 'aldryn_people', 'aldryn_translation_tools', 'absolute', 'aldryn_forms', 'aldryn_forms.contrib.email_notifications', 'captcha', 'emailit', 'parler', 'sortedm2m', 'taggit', # this AWS S3 work (boto + django-storages) … -
How can I display html using a view that displays multiple object items and after one of those items has been deleted form Django database?
I have the following models: CATEGORY_CHOICES = ( ('Hotel', 'Hotel'), ('Restaurant', 'Restaurant'), ('Attraction', 'Attraction'), ('Activity', 'Activity') ) LABEL_CHOICES = ( ('P', 'primary'), ('S', 'secondary'), ('D', 'danger') ) class Item(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64) address = models.CharField(max_length=64) postcode = models.CharField(max_length=7) category = models.CharField(choices=CATEGORY_CHOICES, max_length=20) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() image = models.ImageField(blank=True, null=True, upload_to="images/") description = models.TextField() def __str__(self): return f"{self.id}: {self.name}" def get_absolute_url(self): return reverse("product", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("remove-from-cart", kwargs={ 'slug': self.slug }) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.name}" class Order1(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) step = models.CharField(max_length=1, default=0) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) step_duration = models.FloatField(default=0) def __str__(self): return self.user.username def get_total_duration(self): Pass def get_total_price(self): return F"£{self.step_duration * 20}" class Order2(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) step = models.CharField(max_length=1, default=0) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) step_duration = models.FloatField(default=0) def __str__(self): return self.user.username def get_total_duration(self): Pass def get_total_price(self): return F"£{self.step_duration * 20}" I have the following view: @login_required(login_url='login') def OrderSummaryView(request): try: order1 = Order1.objects.get(user=request.user, ordered=False) … -
django get image url from custom user creation form
i have created a custom usercreation form in django i cant figure out how to get the url from my image feild in my user creation form. i am getting error inmemoryuploadedfile has no attribute url any help would be appreciated my form: class RegisterForm(UserCreationForm): bio = forms.CharField(max_length=400, required=False) image = forms.ImageField(required=False) class Meta: model = User fields = ["username", "image", "password1", "password2", "bio"] def save(self, commit=True): user = super(RegisterForm, self).save(commit=False) user.bio = self.cleaned_data["bio"] user.image = self.cleaned_data["image"] if commit: user.save() return user views.py: class RegisterPage(FormView): template_name = "main/register.html" form_class = RegisterForm success_url = reverse_lazy('blog_list') def form_valid(self, form): user = form.save() if user is not None: login(self.request, user) return super(RegisterPage, self).form_valid(form) def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) if form.is_valid(): user = form.save() form.user = request.user login(self.request, user) print(request.user.image.url) messages.success(request, "Account Created Successully") return redirect('blog_list') return render(request, self.template_name, {'form': form}) def get(self, *args, **kwargs): if self.request.user.is_authenticated: return redirect("blog_list") return super(RegisterPage, self).get(*args, **kwargs) register.html <div class="form"> <h1>Register</h1> <form enctype='multipart/form-data' method="POST"> {% csrf_token %} <ul> {% for field in form %} {% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %} {% endfor %} </ul> <label>{{form.username.label}}</label> {{form.username}} <br> <label>{{form.password1.label}}</label> {{form.password1}} <br> <label>{{form.password2.label}}</label> {{form.password2}} <br> <label>{{form.image.label}}</label> {{form.image}} <br> <label>{{form.bio.label}}</label> {{form.bio}} <br> … -
Wikipedia-typed Django models relations
I need to connect some articles where mentioned some people from another fields. For example, science, cinema, music, etc. How to build models in this situation, I'm sure, it is many to many relation, but how to control this third table and which data needed to connect? I need model, where will be name of article, text of article, field (cinema), and person (50 Cent). How to deal wit that fact, that one person may be related to several fields, for example, music and cinema? -
Downloading files from a website on django
I have a website on a debian server. I fill out the template in docx format and save it. How do I download it to the user's devices? post_data = json.loads(request.body) date = post_data.get('date', False) price = post_data.get('price', False) pricesum = post_data.get('pricesum', False) startdate = post_data.get('startdate', False) enddate = post_data.get('enddate', False) doc = DocxTemplate('template.docx') dates = date prices = price tbl_contents = [{'expirationdate': expirationdate, 'price': price} for expirationdate, price in zip(dates, prices)] context = { 'tbl_contents': tbl_contents, 'finalprice': sum(prices), 'startdate': startdate, 'enddate': enddate } doc.render(context) doc.save("static.docx") -
How to query data in fields from django model?
I get values for CharField from ModelForm and i need get that data from database. I need value of variable in model from model with a certain id. -
How to set Cache-Control with django.contrib.syndication.views
I try to set the Cache-Control HTTP header in django.contrib.syndication.views with cache_control() (of django.views.decorators.cache), but in vain: from django.contrib.syndication.views import Feed from django.utils.feedgenerator import Atom1Feed import lxml.html import requests class TestFeed(Feed): feed_type = Atom1Feed language = 'zh-Hant-TW' link = 'https://www.example.com/feed' title = 'Sample feed' def items(self): s = requests.Session() r = s.get(self.link) body = lxml.html.fromstring(r.text) items = body.cssselect('.item a') return items def item_description(self, item): img = item.cssselect('img')[0] img.set('src', img.get('data-src')) content = lxml.etree.tostring(item, encoding='unicode') return content def item_link(self, item): link = item.get('href') return link def item_title(self, item): title = item.get('title') return title After tracing the source code of django.contrib.syndication.views it seems unlikely to use decorator(s) to add a HTTP header into the HTTP response object. Is there any workaround to accomplish this?