Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I bulk delete Django session?
I use sessions to store some API results as caches, though my session is db-based. In particular, I use session keys like "product_{id}". When a user makes a bulk edit, I need to delete the cache so he can load API results. How can I bulk delete them? I know I can manage sessions just like a model out of view. Also, I can bulk edit with filter - startswith. like below. q1 = Entry.objects.filter(headline__startswith="What") However, the key looks like encoded as mentioned from the first link. How can I handle it? from django.contrib.sessions.models import Session s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead') s.expire_date datetime.datetime(2005, 8, 20, 13, 35, 12) -
LEAD and LAG window fucntions in Django orm, how to apply on single object?
Question is regarding Window functions usage in Django. I have a following model: class EntriesChangeLog(models.Model): content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, ) object_id = models.PositiveIntegerField( ) content_object = GenericForeignKey( 'content_type', 'object_id', ) user = models.ForeignKey( get_user_model(), verbose_name='user', on_delete=models.SET_NULL, null=True, blank=True, related_name='access_logs', ) access_time = models.DateTimeField( verbose_name='access_time', auto_now_add=True, ) as_who = models.CharField( verbose_name='Status of the accessed user.', choices=UserStatusChoices.choices, max_length=7, ) operation_type = models.CharField( verbose_name='Type of the access operation.', choices=OperationTypeChoices.choices, max_length=6, ) state = JSONField( verbose_name='Model state before save or delete.', encoder=CustomEncoder, ) My goal here is to annotate each object in queryset of this model with state field from previous and next object in queryset with same object_id and content_type_id. This is needed to get this annotation later in detail view and calculate difference between previous, current and future state. My queryset in get_object: def get_queryset(self): model = self.kwargs['model_name'] instance_pk = self.kwargs['instance_pk'] self.queryset = self.model.objects.filter( object_id=instance_pk, content_type__model=model.__name__.lower(), content_type__app_label=model._meta.app_label.lower(), ).select_related('user', ) return super().get_queryset() def get_object(self): queryset = self.filter_queryset(self.get_queryset()) q = queryset.annotate( next_val=Window( expression=Lead('state'), order_by=F('id').asc() ), prev_val=Window( expression=Lag('state'), order_by=F('id').asc(), ), ) obj = q.filter(pk=self.kwargs['pk']).first() self.check_object_permissions(self.request, obj) return obj analogue in RAWSQL SELECT id, state, LEAD("state") OVER(ORDER BY "id" ) AS "next_val", LAG("state") OVER(ORDER BY "id") AS "prev_val" FROM "administration_entrieschangelog" where object_id =158 and content_type_id=7 … -
Restricting ManyToManyField to entries by same user django
I have two models that are connected via ManyToManyField. The problem is that other users can see & select the entries of another user. Here is what the models.py looks like: class TeamProfile(models.Model): teamAdmin = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='teamprofile') teamName = models.CharField(max_length=300) team_descriptions = models.CharField(max_length=3000) team_logo = models.FileField(upload_to='teamProfile/team_logo', blank=True, null=True) # team_captain = models.ManyToManyField(PlayerProfile) team_players = models.ManyToManyField(PlayerProfile, related_name= 'team_player') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.teamName class CompetitionProfile(models.Model): creator = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='competitionprofile') comp_Name = models.CharField(max_length=50) participating_team = models.ManyToManyField(TeamProfile, related_name='participating_team') viewership_type = models.CharField(max_length=5, blank=True, null=True) organizer_contact = models.CharField(max_length=14, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.comp_Name Here is what the views.py looks like: class CompetitionCreateView(CreateView): model = CompetitionProfile form_class = ComPCreateForm success_url = reverse_lazy('zone') team = TeamProfile.objects.all() def form_valid(self, form): form.instance.creator = self.request.user form.instance.participating_team = User.teamprofile.all() # form.instance.participating_team = self.request.user.team return super(CompetitionCreateView, self).form_valid(form) In this case if I create a Team Profile, other users can see the team profile I created as a option to select in their participating_team field of when filling up the Competition Profile form. I would want to restrict this to just the team profiles created by that users. You don't get to see or select team profile created by other users when completing the competition … -
Heroku can't detect my forms.py. "ModuleNotFoundError at /"
I keep getting a "ModuleNotFoundError at /" error when I try to visit my Heroku app. It works fine when I run it on localhost:8000. My project directory looks like this: frontpage -pycache (folder) -migrations (folder) -templates (folder) -__init.py__ -admin.py -apps.py -forms.py -models.py -tests.py -urls.py -views.py Log error: ModuleNotFoundError at / No module named 'frontpage.forms' Request Method: GET Request URL: http://cottonthebutton.herokuapp.com/ Django Version: 3.0.8 Exception Type: ModuleNotFoundError Exception Value: No module named 'frontpage.forms' Exception Location: /app/frontpage/views.py in <module>, line 5 Python Executable: /app/.heroku/python/bin/python Python Version: 3.8.5 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python38.zip', '/app/.heroku/python/lib/python3.8', '/app/.heroku/python/lib/python3.8/lib-dynload', '/app/.heroku/python/lib/python3.8/site-packages'] Server time: Sat, 1 Aug 2020 19:16:39 +0800 Traceback: Environment: Request Method: GET Request URL: http://cottonthebutton.herokuapp.com/ Django Version: 3.0.8 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'frontpage'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback (most recent call last): File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/base.py", line 100, in _get_response resolver_match = resolver.resolve(request.path_info) File "/app/.heroku/python/lib/python3.8/site-packages/django/urls/resolvers.py", line 544, in resolve for pattern in self.url_patterns: File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.8/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = … -
Django Rest Framework, custom pagination showing thie error: Type error at: " " unhashable type: 'slice'
I got this snippet from so, which handles custom pagination, I tried implementing it in my views, but I am getting this error TypeError at /api/posts/posts/favourites/ unhashable type: 'slice' This is my views class CustomPaginator(PageNumberPagination): page_size = 3 def generate_response(self, query_set, serializer_obj, request): try: page_data = self.paginate_queryset(query_set, request) except NotFoundError: return Response({"error": "No results found for the requested page"}, status=status.HTTP_400_BAD_REQUEST) serialized_page = serializer_obj(page_data, many=True) return self.get_paginated_response(serialized_page.data) class FavouritePostAPIView(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request): user = self.request.user favourite_posts = user.post_favourite.all() paginator = CustomPaginator() response = paginator.generate_response({'favourite':favourite_posts}, PostFavouriteListSerializer, request) return response Can someone tell me what the problem is? Thanks -
Django model.Model.'instance' raises AttributeError
I am making a website with a strava app using django. However, while trying to store a refresh token (code below) the programm runs into a AttributeError. u.refresh_token = str(answer['refresh_token']) Error: AttributeError 'dict' object has no attribute 'refresh_token' I can see why the code does this, because, when looking a the local variables, it shows that u does in fact have the attribute refresh_token. u{'cookie': 'oP2L2ZDziOl7obaaYXmhFcOfRdXmOXurdqURXhX4JsWnPE1FQAIbGoEwpbcXax3h','password': 'W00lly!', 'refresh_token': '', 'strava_id': '', 'username': 'jeroenkodde'} I tested if it maybe was the anwer dict, but that did not cause the issue. Also, when testing this in the shell it worked. Can somebody tell me what is wrong with the code. -
When I go to load my blog page, the base.html is extended and is working, but the content of my other html files are not showing. Why is this?
I have tried everything I can think of. I started off by going through the complete tutorial on Real Python. Now I am in the stage of building on it myself and have everything seemingly connected. All of the URLs and views and my database seem to be in order with no errors. Whenever I go to the blog url, the base.html and navbar and everything are in place, but the actual content of my other html files are just gone. Does anybody know why this would be? I tried to post code but it was a mess. I'm only just now becoming active on here. If anybody needs anymore information, or needs me to present any code I would be happy to do so. I will just screenshot everything I can. This has just been frustrating the hell out of me and I want to move on and get this one out of my head. Any help would be great. -
Python Django populate field in a model using another field in the same model
I have a User model. What I want is when a user registers, the slack field is filled with data from a function which uses users email as a parameter. (Basically slack should be something like "DS8ds9D" which is generated from email. I have the function that does that "get_slack(email)" which I know works if run outside model with an email. The error I get is when I try to "makemigrations" saying the email from "get_slack(email)" is null. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) slack = models.CharField(max_length=255, default=get_slack(email)) I think it is clear what I am trying to establish however my method using "default" may not be appropriate. Any suggestions? Thanks. -
How to remove related files from AWS S3 in Django
I have two models - Student and Results. The primary key of students is the foreign key of Results table. All the related files are stored in S3 buckets and only their url is stored in the database. My question is how do I delete the files of Results table from S3 when I delete a student record? I am able to delete the files of student using Post_Delete but I am not sure how to remove the related results file from S3. Please Help!! -
'WSGIRequest' object has no attribute 'objects' error when getting data from request object
So i am trying to make a reset password functionality in django but getting this error, can't debug it. So this is the error Traceback (most recent call last): File "/home/aman/.local/share/virtualenvs/stet-sikkim-project-D4VwjO1D/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/aman/.local/share/virtualenvs/stet-sikkim-project-D4VwjO1D/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/aman/.local/share/virtualenvs/stet-sikkim-project-D4VwjO1D/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/aman/.local/share/virtualenvs/stet-sikkim-project-D4VwjO1D/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/aman/.local/share/virtualenvs/stet-sikkim-project-D4VwjO1D/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/home/aman/Desktop/stet-sikkim-project/authentication/views.py", line 184, in post user = request.objects.filter(email=email) Exception Type: AttributeError at /authentication/request-password Exception Value: 'WSGIRequest' object has no attribute 'objects' This is the code, class RequestPasswordResetEmail(View): def get(self, request): return render(request, 'authentication/reset-password.html') def post(self, request): email = request.POST['email'] context = { 'values': request.POST } if not validate_email(email): messages.error(request, 'Please enter a valid email') return render(request, 'authentication/reset-password.html', context) current_site = get_current_site(request) user = request.objects.filter(email=email) if user.exists(): email_contents = { 'user': user[0], 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user[0].pk)), 'token': PasswordResetTokenGenerator().make_token(user[0]), } link = reverse('reset-user-password', kwargs={ 'uidb64': email_contents['uid'], 'token': email_contents['token']}) email_subject = 'Password Reset STET Sikkim' reset_url = 'http://'+current_site.domain+link email = EmailMessage( email_subject, 'Please click the link below to reset your password, ignore if you did not made this request\n'+reset_url, 'noreply@stetsikkim.com', [email], ) email.send(fail_silently=False) … -
Django caches API requests results
When developing an app locally using Django, I do runserver and I work locally. The issue that I have is that most of the time the GET requests to the API are cached, and therefore when I do for example a Patch or Update, it does not reflect results. Example: GET django.app/api/v1/cars Returns: {id: 1, is_active: True} PATCH {'is_active': False} django.app/api/v1/cars/1/ Returns: {id: 1, is_active: False} GET django.app/api/v1/cars Returns(cached): {id: 1, is_active: True} Is there a setting for this? or could it be a browser issue? I had a similar issue on the server nginx and I disabled the cached from the server side, but since locally I am using the runserver from Django, I don't know if there is such a setting. Note that I am using out of the box django. -
Is it right to save opencv SIFT descriptors to Django model field for future reference and how to do it
I am comparing user submitted image with images in postgressql database. I am using Django ImageField for saving images to the database. Below is the snippet i am using ''' image1 = None images = models.Image.objects.all() imgs = [] tempf = None if request.POST: image1 = request.FILES.get('imagesearch') tempf, tempfn = tempfile.mkstemp() try: for chunk in image1.chunks(): os.write(tempf, chunk) except: raise Exception("Problem with the input file ") finally: os.close(tempf) if tempf: image1 = cv2.imread(tempfn) image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY) sift = cv2.xfeatures2d.SIFT_create() keypoints_1, descriptors_1 = sift.detectAndCompute(image1,None) for image in images: tempf2, tempfn2 = tempfile.mkstemp() try: for chunk in image.image.chunks(): os.write(tempf2, chunk) except: raise Exception("Problem with the input file ") finally: os.close(tempf2) if tempf2: image2 = cv2.imread(tempfn2) image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY) #sift sift = cv2.xfeatures2d.SIFT_create() keypoints_2, descriptors_2 = sift.detectAndCompute(image2,None) #feature matching bf = cv2.BFMatcher(cv2.NORM_L1, crossCheck=True) matches = bf.match(descriptors_1,descriptors_2) matches = sorted(matches, key = lambda x:x.distance) ''' I am new to python and opencv. How can I store the SIFT descriptor results to database or file for future use to make the process quicker. -
Django Vs flask for table app database with ML
i'm using react to create an app similar to excels or notion.so table where I can add formulas and recursive inputs, but I want to implement machine learning with them, should I learn Django or flask for that? -
i want to get all records of a particular field after a particluar date
I am try to get all records to a particluar selected filed from dropdown menu after a particluar date if the exist.like all records for softwrae development after last 15 days.iam able to get the date 15 days ago but am unable to query database on that date i am getting blank screen on browser with no error. Please help. views.py def NewPageDetailsView(request): field_variable=request.GET['field_selected'] today = datetime.date.today() previous_date = today - datetime.timedelta(days=15) print(previous_date) print(type(previous_date)) AllDetails=Professional_Resources.objects.filter(Field=field_variable).filter(Released_On__gt=previous_date) return render(request,'FirstApp/NewPageDetails.html',{'AllDetails':AllDetails}) Model class Professional_Resources(models.Model): Field=models.CharField(max_length=50) Author=models.CharField(max_length=50) Released_On=models.DateField() template <body> {%for o in AllDetails%} {{o.Url}} {%endfor%} </body> -
How to Display Data from Array Using forloop in Jinja Template?
i Want to Display data in table using flask forloop. i have Following Array called "mainarray" [ ('x', 'y', 'z'), ('a', 'b', 'c'), ('m', 'n', 'o') ] Currently i am using following method {% for newmainarray in mainarray %} {{ newmainarray [0] }} {{ newmainarray [1] }} {{ newmainarray [2] }} {% endfor %} Currently its working for me.but i have seen in some tutorials that we can display data by using {{newmainarray.keyname}} also. However its not working for me. i will be very thankful if Anyone can help me With this -
How to make four different logins in one django site
I am making a test-portal on django. I want to make four logins in that. Admin, Institute, Teacher, Student. A teacher of one institute can also be a student of another institute. -
I really need help: django can't import taggit module in apache server, fine in local server, I installed it successfull, I haven't use virtualenv
As I said everything is working on my system, but when I pushed code to my server (I replace my app directory with a new updated code directory and manually add "taggit" in my installedapp in settings.py file) after that I run "sudo service apache2 reload". I got 500 Internal server error. I set the debug=True in settings.py but nothing comes up in browser still 500 Internal server error. I read a lots of solution but nothing worksfor me. When I undo the chnages every thing work fine website comes live. I install a taggit module using pip as shown below. ubuntu@ip-172-31-35-150:/var/www/mysite$ pip3 install django-taggit Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: django-taggit in /home/ubuntu/.local/lib/python3.6/site-packages (1.3.0) Requirement already satisfied: Django>=1.11 in /usr/local/lib/python3.6/dist-packages (from django-taggit) (3.0.7) Requirement already satisfied: asgiref~=3.2 in /usr/local/lib/python3.6/dist-packages (from Django>=1.11->django-taggit) (3.2.10) Requirement already satisfied: pytz in /usr/local/lib/python3.6/dist-packages (from Django>=1.11->django-taggit) (2020.1) Requirement already satisfied: sqlparse>=0.2.2 in /usr/local/lib/python3.6/dist-packages (from Django>=1.11->django-taggit) (0.3.1) Then I try to import the module from shell It get imported. ubuntu@ip-172-31-35-150:/var/www/mysite$ python3 manage.py shell Python 3.6.9 (default, Jul 17 2020, 12:50:27) [GCC 8.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from taggit.models import Tag … -
How to do LEFT OUTER JOIN on Django ORM on non ForeignKey field
I have 2 models: model A: name = CharField() ... model B: title = CharField(null=True) ... I want to get all record of model A which do not have record in model B by "name" = "title" ON SQL I got this by: SELECT "A".* FROM "A" LEFT OUTER JOIN "B" ON "A"."name" = "B"."title" WHERE "B"."title" IS NULL How to write this using Django ORM? -
django: how to include parent category URL in child category URL (Category is a nested model)
The thing is, I have a model named ProductCategory, this model may or may not have another model as a parent category. consider I have three Categories : grandParent -> parent -> child Currently when I click on child category the URL is /productCategory/child I want to include it's parents as well. so if user clicks on "child" category URL must look like this /grandParent/parent/child in case of parent category clicked it must generate /grandparent/parent and when User clicks on a product I want to concatenate it's URL with the category URL something like this: /grandparent/parent/child/product_slug so can you please help me with this? class ProductCategory(models.Model): ''' product category model ''' parent_category = models.ForeignKey( 'self', verbose_name=_('Parent Category'), related_name=('sub_categories'), blank=True, null=True, on_delete=models.CASCADE ) @property def is_last_child(self): ''' check whether current category is a parent for another category ''' return self.sub_categories.count() == 0 @property def is_root_category(self): ''' Check wheter current category has no parent ''' return self.parent_category is None def get_absolute_url(self): return reverse('productcategory', kwargs={'slug': self.slug}) -
Django tuggle buttpon listview to show detail
`i want to show detail of the object when user click on the toggle button (+) for loop for rendering listview object of Django {% for ques in python_objects %} <div class= "one"> print the list object <p class="question"><b>{{ ques.py_question }}</b> here i link to print detailview object from DetailView Django, I don't know this is the correct way of linking or not because i don't know more about javascript <span class="toggle_button" href="{% url 'interview:python_detail' ques.pk %}" onclick="toggle('answer1');"> <i class="fa fa-plus" style="color:whitesmoke;"></i></span> </p> <div style="display:none; padding-left: 30px; padding-bottom: 30px;" id="answer1">{{ python_detail_objects.py_answers }}</div> </div> {% endfor %} This is my javascript custom.js file function toggle(id) { var e = document.getElementById(id); if(e.style.display == 'none') e.style.display = 'block'; else e.style.display = 'none'; } please help me to solve this problem. Thank you -
How do I change the link from follow at no longer follow?
I'm working on a following system. But I don't know how to turn the link from follow to no longer follow. models.py from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Follower(models.Model): follower = models.ForeignKey(User, on_delete=models.PROTECT, related_name='following') following = models.ForeignKey(User, on_delete=models.PROTECT, related_name='followers') class Meta: unique_together = ('follower', 'following') def __str__(self): return u'%s follow %s' % (self.follower, self.following) views.py def AddFollowerView(request, pk, id): user = get_object_or_404(User, pk=pk) userFollow = get_object_or_404(User, id=id) Follower.objects.create(follower=user, following=userFollow) return HttpResponseRedirect('/') def RemoveFollowerView(request, pk, id): user = get_object_or_404(User, pk=pk) userFollow = get_object_or_404(User, id=id) Follower.objects.filter(follower=user, following=userFollow).delete() return HttpResponseRedirect('/') urls.py path('follow/<int:pk>/<int:id>/', AddFollowerView, name="add-follower"), path('no-longer-follow/<int:pk>/<int:id>/', RemoveFollowerView, name="remove-follower"), Link (template.html) {% if request.user == user.following %} <a href="{% url 'remove-follower' pk=user.pk id=request.user.pk %}">no longer follow</a> {% endif %} {% if request.user == user.following %} <a href="{% url 'add-follower' pk=user.pk id=request.user.pk %}">Follow</a> {% endif %} Thank you in advance! -
What to use for storing and showing files on a website?
I have a few days since I am searching for a method for uploading files on my website and print them on a webpage. I want to add a folder with some pdf files on my pc/server and than automatically to print them on a webpage or to make an upload form on another page where I can upload files to my pc and than print on a webpage. I am looking for options but I can't find anything, maybe I don't know how to search on google. I want to use nodejs or php if it's possible. Here are some exemple: https://itshare.ro/index.php/s/8TZ2fqSfQkiEk2F or Microsoft Teams(sections Files) or even Google Drive(but at a lower level) -
unable to get complete post details after clicking on post title.(django reverse url)
I'm new to Django and am trying to create blog project and i have created reverse url but when i am clicking on post title it is redirecting to same page.I have doubt with url defined but i am not getting any error after running server. 1.urls.py """blog_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path,re_path from blog import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.post_list_view), re_path('(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$',views.post_detail_view,name='post_detail'), ] 2.models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse # Create your models here. class Post(models.Model): STATUS_CHOICES = (('draft', 'DRAFT'), ('Published', 'PUBLISHED')) title = models.CharField(max_length=256) slug = models.SlugField(max_length=64, unique_for_date='publish') author = models.ForeignKey(User,related_name='blog_post', on_delete=models.DO_NOTHING) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created=models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = … -
Wagtail ; getting each category name and blogpages that fall under it
I don't know how exactly I can implement it I want to make a category page especially that shows each and every category and blog pages that belong to that specific category. For instance Category 1: blog article 1 blog article 2 .... Category 2: blog article 1 But I always come across BlogCategory not iterable error somehow... In wagtail models.py, def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) ca=BlogCategory.objects.all() BlogPagelist=[] for e in ca: try: BlogPagelist.append({"posts":[e,[e.blogpage_set.all()]]}) except: pass context["categories"] =BlogPagelist return context In template {% for category in categories %} {% for cat,po in category.items %} <li> {{ cat }} : {% for p in po %} {{p}} </li> {% endfor %}</br> {% endfor %} {% endfor %} -
how to get a field from a model in django api view
i have to api views that use a model. one view uses headlines.objects.all() to get evrything in the model and the second view is supposed to get only the title field from the model, i have tried filtering and i got a positional argument error. this is my views file. from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from news.models import Headline from news.api.serializers import * @api_view(['GET',]) def api_detail(request, any): try: qs = Headline.objects.get(slug=any) except Headline.DoesNotExist: return Response(status = status.HTTP_404_NOT_FOUND) if request.method == "GET": serializer = HeadlineSerializer(qs) return Response(serializer.data) @api_view(['GET',]) def api_head(request): try: py = Headline.objects.all().filter(title=title).order_by('-id') except Headline.DoesNotExist: return Response(status = status.HTTP_404_NOT_FOUND) if request.method == "GET": serializer = HeadlineSerializer(py, many=True) return Response(serializer.data) This is my serializers.py file from rest_framework import serializers from news.models import Headline class HeadlineSerializer(serializers.ModelSerializer): class Meta: model = Headline fields = ['title', 'contentt']