Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can i use haproxy for hosting django channels ASGI application instead of daphne?
I was curious to know can i host a ASGI django channels applications with haproxy instead of daphne as i heared it had some security issues. -
Djoser "Password Changed Confirmation" Email Not Sending
Good day, I have successfully overwriting 3 of the default Djoser templates and can receive those emails, but I can't get the "Password Changed Confirmation" email to send. According to djoser/conf.py, djoser/email.py, and djoser/templates/email it appears I am doing everything correctly. But it's not obvious why this one isn't sending as there are no errors being raised. The project directory has these relevant files and paths: project - core - email.py - settings.py - templates - email - activation.html # works - confirmation.html # works - password_changed_confirmation.html # does not work - password_reset.html # works settings.py was set as per the Djoser docs. DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'SET_PASSWORD_RETYPE': True, 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_CONFIRMATION_EMAIL': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', # I set this to True as per the docs: 'PASSWORD_CHANGED_EMAIL_CONFIRMATION:': True, 'USERNAME_RESET_SHOW_EMAIL_NOT_FOUND': True, 'PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND': True, 'SERIALIZERS': { 'user_create': 'users.serializers.UserCreateSerializer', 'user': 'users.serializers.UserCreateSerializer', }, 'EMAIL': { # These 3 templates send: 'activation': 'core.email.ActivationEmail', 'confirmation': 'core.email.ConfirmationEmail', 'password_reset': 'core.email.PasswordResetEmail', # This one does not: 'password_changed_confirmation': 'core.email.PasswordChangedConfirmationEmail', } } In email.py I create my custom class to reference the template. The print statements don't even fire so I don't think this is even getting called. from djoser import email # Override the default Djoser … -
How do I use the ability to add another ingredient that is available in admin?
I have a recipe database web app that allows users to add recipes to it. At the moment, it only allows users to enter up to three ingredients. In the admin page, there is an option to add another ingredient. Am I able to use this to allow users to choose to add another? Also, why is delete showing up? And is there a way to remove it? Thanks for any advice you can offer. # models.py class Ingredient(models.Model): #TODO allergies, more data on ingredient, looking towards APIs now name = models.CharField(max_length=20, unique=True) quantity = models.PositiveIntegerField() unit = models.CharField(max_length=50, validators=[validate_unit_of_measure], blank=True, null=True) unit_price = models.PositiveIntegerField() recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name="ingredients") def __str__(self): return self.name # forms.py class IngredientForm(forms.ModelForm): class Meta: model = Ingredient fields = ['name', 'quantity', 'unit', 'unit_price',] exclude = ('recipe',) -
How do I use a select2 multiple select in a django crispy form?
I have an existing crispy form. I want to use django-select2 to replace an existing multi-select with a Select2 field with a maximum of two selections. I know from this post that I need to include 'data-maximum-selection-length' as a widget attribute. Here is the field code I am adding: forms.ModelMultipleChoiceField( required=True, queryset=MyModel.objects.all(), widget=s2forms.Select2MultipleWidget(attrs={'data-maximum-selection-length': 2})) I have included {{ form.media.css }} in the head of my template and {{ form.media.js }} before the tag. Edit: I have path('select2/', include('django_select2.urls')), included on my urls.py. The field is not formatted to appear as a select2 dropdown, it looks like a standard multiselect field. This is what I'm hoping to obtain: ... this is how it looks: I'd be appreciative of any ideas! References: django-select2 docs django ModelMultipleChoiceField docs django crispy forms docs -
Original exception text was: 'Category' object has no attribute 'answer'
Please check the error.Much appreciate if you can help: error: Got AttributeError when attempting to get a value for field answer on serializer CategorySerializer. The serializer field might be named incorrectly and not match any attribute or key on the Category instance. Original exception text was: 'Category' object has no attribute 'answer'. model.py: class Question(models.Model): question_text = models.CharField(max_length=200) question_type = models.CharField(max_length=200) def __str__(self): return f'{self.id}-{self.question_text}' class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE,related_name='questions_answer') answer_text = models.CharField(max_length=200) def __str__(self): return self.answer_text class Category(models.Model): category_text = models.CharField(max_length=200) def __str__(self): return self.category_text serializer.py: class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = '__all__' class AnswerSerializer(serializers.ModelSerializer): ques=QuestionSerializer(source='questions',read_only=True) class Meta: model = Answer fields = '__all__' class CategorySerializer(serializers.ModelSerializer): # question=QuestionSerializer(read_only=True,source='question.question') answer=AnswerSerializer(many=True) class Meta: model = Category fields = ['id','category_text','answer'] def create(self, validated_data): answer_data = validated_data.pop('answer') category = Category.objects.create(**validated_data) for answer_data in answer_data: Answer.objects.create(**answer_data) return category views.py class QestionAnswer(generics.CreateAPIView): serializer_class = CategorySerializer def perform_create(self,serializer): serializer.save() -
django.db.migrations.exceptions.InconsistentMigrationHistory error
In my django project I am getting always this error after makemigrations and migrate (both of them).How can I fix that? raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration auth.0001_initial is applied before its dependency contenttypes.0001_initial on database 'default'. -
Problem with passing images from Django REST Framework to React
I'm trying to display an image for a product category in React. Added the following lines to the settings: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Then set up URLs to serve media files during development: router = routers.SimpleRouter() # some routes here urlpatterns = [ path('', include(router.urls)), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The category model looks like this: class Category(models.Model): title = models.CharField(max_length=100, null=False) slug = models.SlugField(max_length=100, unique=True) poster = models.ImageField(upload_to="categories/") Serializer for it: class CategorySerializer(ModelSerializer): class Meta: model = Category fields = '__all__' On the home page in React I display a list of CategoryCards: import React, {useEffect} from "react"; import * as API from "../apis/API"; import CategoryCard from "./CategoryCard"; import Loader from "./Loader/Loader"; export default function Home() { const [categories, setCategories] = React.useState([]); const [loading, setLoading] = React.useState(true); useEffect(() => { API.list('categories') .then(p => setCategories(p)) .then(_ => setLoading(false)); }, []); return ( <div> <label>Popular categories</label> {loading && <Loader/>} {categories.length ? ( <div> {categories.map(c => <CategoryCard key={c.id} product={c}/>)} </div> ) : ( loading ? null : <p>No categories</p> )} </div> ); } And React component to display category title and image: import React from 'react'; import {A} from 'hookrouter'; export default function CategoryCard({product}) { return ( … -
Django Queryset datetime filtering
I have a set of study sessions that have date and time details and I was wondering how I could go about filtering to just show users upcoming study sessions that are occurring either today or after today in my html file? Here is the model for the session. class Appointment(models.Model): date = models.DateTimeField() -
Languages to learn to develop a website and mobile app
Is it possible for me to use the same set of programming languages to create both a website and a mobile app ( IOS and Android ) and if so, what are they? Some of the features that I would like this project to have are as follows: The website and application can store and share data between the website / IOS and Android apps There are some animations (for example an interactive book that can open, close and flip pages) Has a store feature If I can not use the same languages for the entire project what languages would I need to learn to complete this project. If possible please provide me with some resources that I can reference while doing this project. -
NoReverseMatch at /info/1
I've been trying to fix this error all day, but nothing. NoReverseMatch at /info/1 Reverse for 'like_book' with arguments '(None,)' not found. 1 pattern(s) tried: ['like/(?P[0-9]+)\Z'] views.py def LikeView(request, pk): book = get_object_or_404(BookModel, id=request.POST.get('book_id')) book.likes.add(request.user) return redirect('more_info', pk=pk) html <form action="{% url 'like_book' book.pk %}" method='POST'> {% csrf_token %} <button type="submit" name="book_id" value="{{ book.id }}" class="btn btn-danger btn-sm">Like</button> </form> urls.py urlpatterns = [ path('', index, name='index'), path('allbook', AllBookView.as_view(), name='allbook'), path('addbook', AddBookView.as_view(), name='addbook'), path('register', RegisterView.as_view(), name='reg'), path('login', LoginView.as_view(), name='login'), path('logout', LogoutView.as_view(), name='logout'), path('info/<int:id>', MoreInfoView.as_view(), name='more_info'), path('profile', profileview, name='profile'), path('password-change', ChangePasswordView.as_view(), name='change_pass'), path('like/<int:pk>', LikeView, name='like_book') ] -
Django: session_key is an empty string
I'm using an analytics platform to track user interactions, and want to associate events by session id so I can track individual users' behaviors. So, I am using request.session.session_key as the user id I'm passing the event logging function. I don't use the session for anything else, and am not saving or modifying variables. I did set up middleware correctly, so far so good. However, when I check the analytics platform, I see that the id is often (but not always) blank. I looked up some answers, and thought I could solve this by running request.session.save() before accessing the session_key. However, I can't run .save() because I'm not actually modifying any session variables, so Django throws an error. What do I need to do to make sure the session always has an id? Some code from my very simple get view: def get(self, req: HttpRequest): form = self.form_class(None) # this is where I tried req.session.save() mixpanel.track( req.session.session_key, "Form Page Displayed", {"path": req.path, "route": req.method}, ) return render(req, self.template_name, {"form": form}) -
Add multiple people to one form dynamically. Python and Django
I want to make a form for a case entry. This form should be able to take one or more people associated with it dynamically. Basically, start with one person, and if another person is needed to click a button to say "add a person". This should populate all the fields for a person to be associated with the same case entry without submitting until every person that needs to be entered is entered. I know how to do this with just one person but am at a complete loss for adding multiple people dynamically to the same form. So I have no code to show because I have no idea how to implement this or start. -
Django PWA extention, Icons for pwa website not showing up in F12 menu by manifest in chrome
I am making a PWA website on top of django and the website icons ar not showing up when in the devoloper menu in Chrome as seen in the picture. Manifest in Chrome This is the code i use for the manifest. Manifest code There are no error in the web-console or webserver the images all have a good connection code 200. -
How can I access the created instance by a serializer in a view?
So I have a modelserializer that creates a new model instance in case of post requests to an endpoint. How can I grab the newly created instance in the view for further processing? (I need the id of the new instance for a related model). # serializers.py class OfferList(APIView): """ List all Offers or create a new Offer related to the authenticated user """ def get(self, request): offers = Offer.objects.filter(company__userprofile__user=request.user) serializer = OfferSerializer(offers, many=True) return Response(serializer.data) def post(self, request): serializer = OfferSerializer(data=request.data) if serializer.is_valid(): # Get the related company instance company = get_object_or_404(Company, userprofile__user=request.user) # Pass the related instance to the serializer instance to save the new Offer instance serializer.save(company=company) # Create Payment instances - returns a dict payments = create_payments( serializer.data.get('start_salary'), serializer.data.get('months'), serializer.data.get('start_date'), serializer.data.get('interest_type'), serializer.data.get('interest_interval'), serializer.data.get('interest_raise') ) # Loop the dict and generate instances for key, value in payments.items(): Payment.objects.create( offer= , # how to access the id of the created instance by the serializer above? month=key, amount=value ) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # models.py class Payment(models.Model): """ A table to store all payments derived from an offer. """ # Each monthly payment relates to an offer offer = models.ForeignKey(Offer, on_delete=models.CASCADE) month = models.DateField() amount = models.PositiveIntegerField() -
Run Dash plotly after click button
let's say I have a dashboard that contains many information and plots. I have a dropdown list that generates Plots and another dropdown list named Wells. I have a plot that I created with dash and it works very fine but with a fixed input! and also dash plots this plot at starting the page :( ! My question is how to prevent dash to plot directly and execute after I press a button that takes the selected item from the Wells list and callback the function and replots. so this is my HTML page : <div class="col-md-3" > <select class="custom-select mb-4" name="Wells" hx-get="{% url 'addplotly' %}" hx-trigger="change" hx-target="#plotly_production" hx-include="[name='Toggle']"> <option selected>Select Well</option> {% for well in TFTWells %} <option value="{{well.WellID}}">{{well.WellID}}</option> {% endfor %} </select> </div> and this is my dash script: app = DjangoDash('Pressure_guage', external_stylesheets=external_stylesheets) app.layout = html.Div( id="dark-light-theme", children=[ html.Div([html.H3("Pressure Control", style={"textAlign": "center"}),], className="row"), html.Div([ html.Div( daq.Gauge( #size=150, color={"gradient":True,"ranges":{"green":[0,the_maxCSG/3],"yellow":[the_maxCSG/3,the_maxCSG*6/7],"red":[the_maxCSG*6/7,the_maxCSG]}}, id="my-daq-gauge1", min=0, max=the_maxCSG, value=PRES_CSG, label="CSG "+str(PRES_CSG)+" bar",style={'display': 'inline-block'} ), className="three columns", ), html.Div( daq.Gauge( #size=150, color={"gradient":True,"ranges":{"green":[0,the_max/3],"yellow":[the_max/3,the_max*6/7],"red":[the_max*6/7,the_max]}}, id="my-daq-gauge2", min=0, max=the_max, value=PRES_TBG, label="TBG "+str(PRES_TBG)+" bar",style={'display': 'inline-block'} ), className="three columns", ), html.Div( daq.Gauge( #size=150, color={"gradient":True,"ranges":{"green":[0,the_maxAVD/3],"yellow":[the_maxAVD/3,the_maxAVD*6/7],"red":[the_maxAVD*6/7,the_maxAVD]}}, id="my-daq-gauge3", min=0, max=the_maxAVD, value=PRES_AVD, label="AVD",style={'display': 'inline-block'} ), className="three columns", ), html.Div( daq.Gauge( color={"gradient":True,"ranges":{"green":[0,the_maxGL/3],"yellow":[the_maxGL/3,the_maxGL*6/7],"red":[the_maxGL*6/7,the_maxGL]}}, id="my-daq-gauge4", min=0, max=the_maxGL, value=RESEAU_GL, … -
Exception Value: [Errno 111] Connection refused with djoser and django
I am trying to connect Django and celery .ith Djoser with JWT authentication. I am not sure how to diagnose this error or where to even start looking. This error message is so vague and does not point me to the problem. My Django is as follows Request URL: http://localhost/api/v1/auth/users/ Django Version: 3.2.13 Python Version: 3.9.5 djoser==2.1.0 django-redis==5.2.0 redis==4.2.2 celery==5.2.6 My url call is as follows path("api/v1/auth/", include("djoser.urls")), path("api/v1/auth/", include("djoser.urls.jwt")), Here is the error message: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/kombu/utils/functional.py", line 30, in __call__ return self.__value__ During handling of the above exception ('ChannelPromise' object has no attribute '__value__'), another exception occurred: File "/usr/local/lib/python3.9/site-packages/kombu/connection.py", line 446, in _reraise_as_library_errors yield File "/usr/local/lib/python3.9/site-packages/kombu/connection.py", line 433, in _ensure_connection return retry_over_time( File "/usr/local/lib/python3.9/site-packages/kombu/utils/functional.py", line 312, in retry_over_time return fun(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/kombu/connection.py", line 877, in _connection_factory self._connection = self._establish_connection() File "/usr/local/lib/python3.9/site-packages/kombu/connection.py", line 812, in _establish_connection conn = self.transport.establish_connection() File "/usr/local/lib/python3.9/site-packages/kombu/transport/pyamqp.py", line 201, in establish_connection conn.connect() File "/usr/local/lib/python3.9/site-packages/amqp/connection.py", line 323, in connect self.transport.connect() File "/usr/local/lib/python3.9/site-packages/amqp/transport.py", line 129, in connect self._connect(self.host, self.port, self.connect_timeout) File "/usr/local/lib/python3.9/site-packages/amqp/transport.py", line 184, in _connect self.sock.connect(sa) The above exception ([Errno 111] Connection refused) was the direct cause of the following exception: File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File … -
django filters | how to make order_by on multiple selected fields which are handled by different methods
#filters.py class PostFilter(django_filters.FilterSet): CHOICES = ( ('created_at','Old first'), ('-created_at','New first'), ) ordering = django_filters.ChoiceFilter(choices=CHOICES,method='ordering_filter',widget=Select(attrs={'class':'filter','id':'ordering'})) is_interesting = django_filters.BooleanFilter(method='filter_interesting',distinct=True,widget=CheckboxInput(attrs={'class':'filter','id':'radio1','checked':False})) class Meta: model = Post fields = [] def ordering_filter(self,queryset,name,value): return queryset.order_by(value) def filter_interesting(self,queryset,name,value): if value: followed = User.objects.filter(followers=getattr(self.request,'user')) return queryset.annotate(flag=Q(author__in=followed)).order_by('-flag','-created_at') return queryset #views.py class HomePage(LoginRequiredMixin,ListView): model = Post login_url = reverse_lazy('login') context_object_name = 'filter' template_name = 'main/home.html' def get_queryset(self): posts = Post.objects.all().select_related('author','profile','author__profile').prefetch_related('liked','images','viewers','author__followers') f = PostFilter(request=self.request,queryset=posts,data=self.request.GET) return f #main/home.html <div class="cd-filter"> <form method="get" class="cd-filter-form cd-filter-form--last"> <div class="cd-filter-block"> <div class="cd-filter-content"> <div class="cd-select cd-filters"> {{filter.form.ordering}} </div> </div> </div> <div class="cd-filter-block"> <ul class="cd-filter-content cd-filters list" style="list-style: none;"> <li> {{filter.form.is_interesting}} </li> </ul> </div> <button class="cd-filter__submit" type="submit">Confirm</button> </form> #comment from me the problem is that I can't filter by ordering and interesting at once, I filter only by the field below in the declaration of the class fields (only the last order_by is applied) and so, how can I put them in a single order_by? -
In django, how can I hold a class in memory for use in views without having to construct them every time?
For example, if I have a relatively large csv that I will use to lookup values based on the json parameters provided by an HTTP request. Ideally, I wouldn't have to load that large csv every time the endpoint is called and instead, use a lazily loaded variable: class CSVService: #static getter def get_csv_service() if not csv_service: csv_service = CSVService() return csv_service #Other functions... def my_view(request): service = CSVService.get_csv_service() service.some_function() ... Any Ideas where I would create such a class that the data could be reused between requests? -
Django, postgress docker-compose psycopg2.OperationalError
Set-up: postgres, django and redis services configured via docker-compose. I've read through similar questions on SO but can't see why my compose config results in django not being able to see the db service. The db service is internally configured to port 5432 in the compose network, but mapped to 5433 on the host machine (5432 on the host is used by another docker db container). I'm not sure what I'm missing here, hoping someone can see something in the config or logs that I can't... error logs from web service: stage_web_0.10 | django.db.utils.OperationalError: could not connect to server: Connection refused stage_web_0.10 | Is the server running on host "db" (172.25.0.2) and accepting stage_web_0.10 | TCP/IP connections on port 5432? Django settings from inside the container (correctly looking for db at 5432): settings.DATABASES {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': 'db', 'PORT': '5432', 'NAME': 'stage', 'USER': 'admin', 'TEST': {'NAME': 'test_stage'}}} docker-compose services db: container_name: stage_${DJANGO_ENV}_db_${TAG} env_file: - .env build: context: ./db/ args: # Make these available at build time to create the new db. - POSTGRES_HOST - POSTGRES_DB - POSTGRES_USER - POSTGRES_PASSWORD - POSTGRES_PORT volumes: - /data/postgresql/stage_${DJANGO_ENV}_${TAG}/:/var/lib/postgresql/data/ environment: - TAG - DJANGO_ENV - POSTGRES_HOST - POSTGRES_DB - POSTGRES_USER - POSTGRES_PASSWORD - POSTGRES_PORT ports: … -
What the meaning of the EC2 instance profile and IAM role?
I am using django-s3direct to upload file to S3. My environment is django project on fargate -> s3 Currently, I set ID and KEY in settings.py, it works. settings.py # If these are set to None, the EC2 instance profile and IAM role are used. AWS_ACCESS_KEY_ID = 'your-aws-access-key-id' AWS_SECRET_ACCESS_KEY = 'your-aws-secret-access-key' However, I don't want to use ID and KEY, So I set this None and try to set the EC2 instance profile and IAM role I attached AmazonS3FullAccess to the task role of fargate. However 403 error occurs when uploading file. Then,, what should I do more? -
Django NoReverseMatch: Reverse for 'add_continue' with arguments '('',)'
Anyone know what could be causing this error I'm getting? Most of the other code, which works the exact same way, works perfectly. However, this button doesn't work whenever I click it for some reason. The error only happens once the button to add a movie to a watchlist is clicked. I've checked out some of the other suggestions on here and none of them seem directly correlated to this issue. Any suggestions? Here is the error: NoReverseMatch at /watchlist/ Reverse for 'add_continue' with arguments '('',)' not found. 1 pattern(s) tried: ['resumeMovie/add/(?P<film_id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$'] Watchlist.html: {% extends "base.html" %} {% load static %} {% block metadescription %} This is the watchlist page. Proceed to review your items. {% endblock %} {% block title %} Watchlist - MovieBuff {% endblock %} {% block content %} {% if not watchlist_items %} <div> <div class="text-center"> <br /> <h1 class="text-center my_title">Your watchlist is empty</h1> <br /> <p class="text-center"> Please click <a href="{% url 'movies:allFilmGenre' %}">here</a> to continue browsing our collection. </p> </div> </div> {% else %} <div> <div class="text-center"> <br /> <h1 class="text-center my_title">Your Watchlist</h1> <br /> </div> </div> <div class="row mx-auto"> <div class="col-12 col-sm-12 col-md-12 col-lg-6 text-center"> <table class="table my_custom_table"> <thead class="my_custom_thead"> <tr> <th colspan="5">Your … -
Django - Function with template returns `TypeError: not enough arguments for format string`
I am trying to use PostgreSQL's FORMAT function in Django to format phone number strings. I can accomplish this with the following SQL query: SELECT phone_number, FORMAT('(%s) %s-%s', SUBSTRING(phone_number,3,3), SUBSTRING(phone_number,6,3), SUBSTRING(phone_number,9,4)) FROM core_user WHERE phone_number iS NOT NULL which returns a result like: Trying to implement this into Django to be used for an ORM query, I did the following: class FormatPhoneNumber(Func): function = "FORMAT" template = "%(function)s('(%s) %s-%s', SUBSTRING(%(expressions)s,3,3), SUBSTRING(%(expressions)s,6,3), SUBSTRING(%(expressions)s,9,4))" ORM query: User.objects.annotate(phone_number2=FormatPhoneNumber(f"phone_number")) Returns the following error: File /venv/lib/python3.10/site-packages/django/db/models/expressions.py:802, in Func.as_sql(self, compiler, connection, function, template, arg_joiner, **extra_context) 800 arg_joiner = arg_joiner or data.get("arg_joiner", self.arg_joiner) 801 data["expressions"] = data["field"] = arg_joiner.join(sql_parts) --> 802 return template % data, params TypeError: not enough arguments for format string I believe it is due to this line '(%s) %s-%s' that is supplied to the FORMAT function. Does anyone have any ideas on how I can make this work? -
Django test form upload including javascript
I make test script for django project For example normal url testing. def test_view_url(self): response = self.client.login(username="user@example.com", password="abcd1234") response = self.client.get("/resources/") self.assertContains(response, "page OK") It works, However in my case I am using django-s3direct in template. It uploads when file is selected from form not when submit. It uses javascript, so I should use another test script for javascript? or I can do this test in django as well?? -
Filtering queryset defined with @property
For a headless wagtail app I'm trying to query all of the blog pages, find the latest page that is marked as being a hero, and then exclude that hero page from the list of all pages. Reason being, I want to display the hero page as a hero image on the blog index page, and then render a list of all the other pages under that. (I could also just send all the live() pages and have react find the latest hero page on the front end, filtering it there, but trying to figure out a back end solution as well). I created to class properties and was hoping to use one to filter the other, i.e. get_child_pages would be able to exclude() the value returned by get_heroes. api_fields = [ APIField('get_child_pages', serializer=BlogIndexPageSerializer()), APIField('get_heroes', serializer=BlogIndexPageSerializer()), ] @property def get_heroes(self): heroes = BlogPage.objects.filter(hero=True).order_by('-first_published_at')[:1] return heroes @property def get_child_pages(self): # return "SOMETHING" # return self.get_children().specific().public().live() return BlogPage.objects.live().exclude(get_heroes) get_child_pages works without exclude but not with it (get_heroes is not defined). I'm learning wagtail and django and I'm not understanding how to work with properties like this. Thanks! -
What API request should I send to receive graph parameters?
I have a blog on django. I have two models article and comment. Each comment can be added to another one. If I send an API request localhost:8000/comments/1 I receive the comment with id="1" and all the nested comments to the third level. json after api request localhost:8000/comments/ : HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 9, "text": "First comment", "owner": "alex", "article": 3, "parent": null, "reply_set": [ { "id": 10, "text": "Comment to comment", "owner": "alex", "article": 3, "parent": 9, "reply_set": [ { "id": 11, "text": "Third level nested comment", "owner": "alex", "article": 3, "parent": 10 } ] } ] }, { "id": 10, "text": "Comment to comment", "owner": "alex", "article": 3, "parent": 9, "reply_set": [ { "id": 11, "text": "Third level nested comment", "owner": "alex", "article": 3, "parent": 10, "reply_set": [ { "id": 12, "text": "Forth level nested comment", "owner": "alex", "article": 3, "parent": 11 } ] } ] }, { "id": 11, "text": "Third level nested comment", "owner": "alex", "article": 3, "parent": 10, "reply_set": [ { "id": 12, "text": "Forth level nested comment", "owner": "alex", "article": 3, "parent": 11, "reply_set": [] } ] }, { "id": 12, "text": "Forth …