Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to restrict staff-user to edit or delete others staff-user post
Right now my all django staff-user can edit or delete others staff-user post. I want they only can able to be edit or delete their own post. How to restrict them to edit or delete others people post? here is my code: views.py: class BlogPublishView(PermissionRequiredMixin,CreateView): raise_exception = True permission_required = "blog.add_post" model = Post form_class = BlogPost template_name = "blog_post.html" #fields = ['title','author','body'] class BlogUpdateView(PermissionRequiredMixin,UpdateView): raise_exception = True permission_required = "blog.change_post" model = Post template_name = "blog_update_post.html" form_class = BlogPost class BlogDeleteView(PermissionRequiredMixin,DeleteView): raise_exception = True permission_required = "blog.delete_post" model = Post template_name = "delete_blog_post.html" success_url = reverse_lazy('blog') urls.py path('blog-post', BlogPublishView.as_view(), name='blog-post'), path('blog-update/<slug:slug>', BlogUpdateView.as_view(), name='blog-update'), path('blog-delete/<slug:slug>', BlogDeleteView.as_view(), name='blog-delete'), html {% if user.is_authenticated %}{% if user.id == post.author.id %} <a href="{% url 'blog-update' post.slug %}"><b>(Edit Blog)</b></a>&nbsp;<a href="{% url 'blog-delete' post.slug %}"><b>(Delete Blog)</b> </a>{% endif %}{% endif %} Let you explain little bit more if you still now don't understand my problem. Assume I have three user in my djano admin panel "A", "B" and "C". user "A" is Admin and user "B" and "C" is staff-user. User "B" and "C" have permission only edit, delete and publish post from admin panel. The problem is user "A" can edit and delete user "B" … -
Django QuerySet filter on inverse relationship
Really struggling with this one and could appreciate some help. I have the following model... class Booking(models.Model): property = models.ForeignKey(Property, related_name='booking', on_delete=models.SET_NULL, null=True) check_in_date = models.DateField() check_out_date = models.DateField() def __str__(self): return f"{self.property}" class Property(models.Model): name = models.CharField(max_length=100, blank = False) def __str__(self): return f"{self.name}" But when I run the following (below) to retrieve property bookings with a date equal to 2021-05-14, instead of just the bookings with a check_in_date of 2021-05-14 being returned, all the bookings for each property are returned even if they don't have a check_in_date of 2021-05-14 Property.objects.filter(booking__check_in_date='2021-05-14') Probably something really simple, but I'm new to Django have been stuck on this all morning and could appreciate some help. Thanks -
How to handle receiving duplicate and out of order webhook events in Django
I am interfacing with some systems that have webhooks set up where they push new and updated events to my Django system. I have the endpoints set up (REST based) and I can receive the incoming data. However, with some of the interfaces, they say that events can come out of order (within a 60 second window), and there can also be duplicate events. Out of order events can be detected by checking the "modified" timestamp in the incoming message, and duplicate messages can be detected by checking the eventId (which is unique). These issues seem to be fairly common with data sent from external systems via webhooks, so before I start architecting and writing something to handle this, is there an existing module/package/best practices for dealing with this within Django? Thanks. -
Django doesn't receive cookies from request
I'm working on a Nuxt/Vue app that uses Django on the backend. I'm using the standard Django Session authentication. The problem with my code is that the user's are always logged out, according to Django, because Django doesn't see any cookie in the request. Basically i created an API endpoin that should return whether or not the user is authenticated, but since Django doesn't see any sessionid cookie in the request, the user will always be unauthenticated to the backend. def checkAuth(request): print(request.COOKIES) response = {'state': str(request.user.is_authenticated), 'username': str(request.user)} return JsonResponse(response, safe=False) If i print request.COOKIES it returns {}. Here is how i send the request from the frontend, where i'm using Axios: return axios({ method: 'get', url: 'http://127.0.0.1:8000/checkAuth', withCredentials: true, }).then(function (response) { console.log(response) }).catch(function (error) { console.log(error) }); The problem should not be from the frontend, since on Chrome i can see the session cookie and the csrf cookie correctly. I already tried to disable any possible CORS security setting on Django. The frontend is running on 127.0.0.1:3000 and the Django app on 127.0.0.1:8000. Why doesn't Django see the cookies? Any kind of advice is appreciated -
Django site suddenly requiring users to clear their cookies to get a CSRF token
I run a Django site that hasn't undergone any updates in the last few months, yet all of a sudden I'm receiving a bunch of emails from users saying they're getting the following error: CSRF Failed: CSRF cookie not set. The bizarre thing is that refreshing the page does not fix the issue. The only way to resolve it is to have them manually clear their browser's cookies. Bear in mind that they are still logged in after refreshing. So even though they aren't getting a CSRF cookie, Django is acknowledging their session. While I'm glad they can clear their cookies to fix it, it's concerning to me as I can't fathom what is happening. It started happening around the same time that iOS 14.5 came out, so I initially thought it may somehow be related to that, but I just received a report from an Android user. Has anyone run into this before? Is there any way to resolve this without putting a banner on the site explaining to clear cookies if you see the error? Thanks! -
How to do custom error messages in Django Forms
I want to make custom error messages for my InstellingenForm, but no matter what I do, I keep getting the browser's standard error messages. The error messages that should be displayed can be seen in choicefield_errors and charfield_errors. Am I missing something cause I feel like it should be working. I want the error messages to be displayed in red above the concerned input field, right next to the label. At the bottom of the page, I put a few pictures of how it looks now. views.py: def instellingenDatabase(request): if request.method == "POST": form = InstellingenForm(request.POST) if form.is_valid(): request.session['data'] = request.POST spelmodus = request.POST.get('spelmodus') if spelmodus == 'woorden': return redirect('speelscherm-woorden') else: return redirect('speelscherm-tijd') else: form = InstellingenForm() return render(request, 'instellingenDatabase.html', {'formulier': form}) forms.py: from django import forms SPELMODUS = [ ('', ''), ('tijd', 'Tijd'), ('woorden', 'Woorden'), ] TIJD = [ ('', ''), ('60', '1 minuut'), ('120', '2 minuten'), ('300', '5 minuten'), ] WOORDEN = [ ('', ''), ('50', '50 woorden'), ('100', '100 woorden'), ('150', '150 woorden'), ] TALEN = [ ('', ''), ('nederlands', 'Nederlands'), ('engels', 'Engels'), ] MOEILIJKHEID = [ ('', ''), ('makkelijk', 'Makkelijk'), ('gemiddeld', 'Gemiddeld'), ('moeilijk', 'Moeilijk'), ] charfield_errors = { 'required': 'Dit veld is verplicht en mag alleen … -
NoReverseMatch at 'url' in Django, Reverse for 'my_app' not found. 'my_app' is not a valid view function or pattern name
I'm new to Django, and today when I tried to run a website with a database, I have encountered this error. I have searched for all solutions on StackOverflow and Django documents, but I can not fix it. This is the problem that similar to me, but it doesn't work. I want to create a link that moves user from user.html in user to index.html in citizens Here is my project structure. I'm sorry because I can't attach an image, so I will try to explain it in easiest way. [MYPROJECT] ->manage.py ->citizens (folder) -->templates (inside this folder I have citizen.html, index.html, layout.html) -->admin.py -->models.py -->tests.py -->urls.py -->views.py ->myproject (folder) -->setting.py -->urls.py -->etc that I think not important ->user (folder) -->templates (inside this folder I have login.html, user.html, layout.html) -->urls.py -->views.py -->etc that I think not important As you can see, I have user.html inside templates folder of user, and index.html inside templates folder of citizens. Here is my code: index.html inside citizens {% extends "citizens/layout.html" %} {% block body %} <h1>Hệ thống quản lý XNC</h1> <table class="table"> <thead> <tr> <th scope="col">Số TT</th> <th scope="col">Họ và tên công dân</th> <th scope="col">Giới tính</th> <th scope="col">Số Hộ chiếu</th> <th scope="col">Chi tiết</th> </tr> … -
Ajax is not sending selected items to django views
I am quite new to Django so bare with me. I'm working on a Django view where I upload a dataframe and the user has a dropdown list to select the target variable. The problem I'm facing is that I can't fetch the selected item on my views: def profile_upload(request): template = "profile_upload.html" my_class = MyClass() if request.method == "GET": prompt = {'order': 'First Page'} return render(request, template, prompt) if request.method == 'POST': csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') df = pd.read_csv(csv_file) my_class.df=df head = df.head(n=5) head = head.to_html(classes='table table-striped') thrsh = 0.1 dataframe_stats = utils.DfStats(df,thrsh) df_stats = dataframe_stats.get_df_stats() cat_cols,num_cols = dataframe_stats.get_type_var() my_class.quali_col = cat_cols my_class.quanti_col = num_cols dtype_counts = {"Variables qualitatives: ": len(cat_cols), "Variables quantitatives: ": len(num_cols)} context = {'table': head, 'stats': df_stats, "dtypes": dtype_counts, 'vars': df.columns} return render(request, template, context) if request.is_ajax() and request.method== "POST" : data = request.POST.get['mydata'] my_class.target_var = data return HttpResponse('<h1> Page was found</h1>') The views above work fine but the last if statement is not executed I don't know where things go wrong. Here is the dropdown script <label for="tar_col"> Select target variable <select class="js-example-basic-single js-states form-control" id="tar_col" name="tar_col" title="tar_col" style="width: 50%"> {% for col in vars … -
Django Bootstrap module in ubuntu
So deploying my django app into an unbuntu 20.04 with apache. I've got everything worked out(mostly). The latest kink is bootstrap. Now when I run the app through the built in django web server, it works beautifully. But when I try through apache, it gives an error that it can't find bootstrap: Error I've verified the syntax is right in my HTML files as that is the most common issue via google. I thought maybe apache needed to have jquery installed, which I did sudo apt-get install libjs-jquery to get installed but that did not resolve the issue. So any help would be appreciated. -
I want to create Django and React Music App but spotify api seem to not working for I tried with vpn too but no response
why spotify api doesn't response back this my view.py file from django.shortcuts import render, redirect from .credentials import REDIRECT_URI, CLIENT_ID, CLIENT_SECRET from rest_framework.views import APIView from requests import Request, post from rest_framework import status from rest_framework.response import Response from .util import * from api.models import Room class AuthURL(APIView): def get(self, request, format=None): # what information we want to access are scopes scopes = 'user-read-playback-state user-modify-playback-state user-read-currently-playing' url = Request('GET', 'https://accounts.spotify.com/authorize', params={ 'scope': scopes, 'response_type': 'code', 'redirect_uri': REDIRECT_URI, 'client_id': CLIENT_ID }).prepare().url return Response({'url': url}, status=status.HTTP_200_OK) def spotify_callback(request, format=None): code = request.GET.get('code') error = request.GET.get('error') response = post('https://accounts.spotify.com/api/token', data={ 'grant_type': 'authorization_code', 'code': code, 'redirect_uri': REDIRECT_URI, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET }).json() access_token = response.get('access_token') token_type = response.get('token_type') refresh_token = response.get('refresh_token') expires_in = response.get('expires_in') error = response.get('error') if not request.session.exists(request.session.session_key): request.session.create() update_or_create_user_tokens(request.session.session_key, access_token, token_type, expires_in, refresh_token) return redirect('frontend:') class IsAuthenticated(APIView): def get(self, request, format=None): is_authenticated = is_spotify_authenticated(self.request.session.session_key) return Response({'status': is_authenticated}, status=status.HTTP_200_OK) class CurrentSong(APIView): def get(self, request, format=None): room_code = self.request.session.get('room_code') room = Room.objects.filter(code=room_code) if room.exists(): room = room[0] else: return Response({}, status=status.HTTP_404_NOT_FOUND) host = room.host endpoint = 'player/currently-playing' response = execute_spotify_api_request(host, endpoint) if 'error' in response or 'item' not in response: return Response({}, status=status.HTTP_204_NO_CONTENT) item = response.get('item') duration = item.get('duration_ms') progress = item.get('progress_ms') album_cover … -
(Django) Validation Forms in class based View doesn't work
I've created a view where user can sign up that use form with validation functions. However, those functions don't work. class SignUpPage(View): def get(self, request): form = SignUpForm() return render(request, "signup.html", {'form': form}) def post(self, request): form = SignUpForm(request.POST or None) if form.is_valid(): redirect('/signup') else: form = SignUpForm() ctx = {"form": form} return render(request, "signup.html", ctx) The form: class SignUpForm(forms.Form): first_name = forms.CharField(max_length=32, required=True) last_name = forms.CharField(max_length=32, required=True) username = forms.CharField(max_length=32, required=True) email = forms.CharField(label="email") password1 = forms.CharField(label="Password", max_length=32, widget=forms.PasswordInput(attrs={'class': 'password'})) password2 = forms.CharField(label="Password Again", max_length=32, widget=forms.PasswordInput(attrs={'class': 'password'})) date_of_birth = forms.DateField(label="Date of birth", required=True, widget=forms.SelectDateWidget(years=YEARS, attrs={'class': 'date-select'})) def validate_email(self): data = self.cleaned_data.get('email') if User.objects.filter(email=data).exists(): raise forms.ValidationError("This email is already registered") return data def validate_age(self): user_date = str(self.cleaned_data['date_of_birth']) year = int(user_date[0:4]) month = int(user_date[5:7]) day = int(user_date[8:10]) today = dt.today() if int(today.year) - year < 18: raise forms.ValidationError("You must be 18 years old to have an account") elif int(today.year) - year == 18 and int(today.month) - month < 0: raise forms.ValidationError("You must be 18 years old to have an account") elif int(today.year) - year == 18 and int(today.month) - month == 0 and int(today.day) - day < 0: raise forms.ValidationError("You must be 18 years old to have an account") else: return … -
getting bad request 401 even after adding link to ALLOWED_HOST
I'm getting a bad request 401 when trying to access the server, which is deployed to Heroku and my react app is on netlify added to ALLOWED_HOST, and CORS still can't figure out. Please help. -
Django checkbox data navigation
I am using simple bootstrap form. <div class="form-check"> <input class="form-check-input" type="checkbox" value="Resource" id="defaultCheck1" name="APP"> <label class="form-check-label" for="defaultCheck1"> ABC </label> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" value="TC" id="defaultCheck2" name="APP" > <label class="form-check-label" for="defaultCheck2"> DEF </label> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" value="CM" id="defaultCheck3" name="APP"> <label class="form-check-label" for="defaultCheck2"> GHI </label> </div> when i am submitting the form i am accessing it in view.py below function is defined in view.py and in function getdata i am parsing the input submitted. def getdata(request): if request.method == "POST": print(request.POST) print(request.POST['APP']) app=request.POST['APP'] print(app) in this code i am using post to check the request type if it is true i am accessing request object and parsing it. output of above is : <QueryDict: {'csrfmiddlewaretoken': ['cdcdcdcdcd'],'APP': ['ABC', 'DEF', 'GHI']}> RPL RPL -
Django cannot find staticfiles
When I try to run my localhost server I get the following error: FileNotFoundError: [Errno 2] No such file or directory: '/static/CSV/ExtractedTweets.csv' This error is due to the line the line with open(staticfiles_storage.url('/CSV/ExtractedTweets.csv'), 'r', newline='', encoding="utf8") as csvfile: This line of code can be found in a custom python module within my app folder. I have copies of /static/CSV/ExtractedTweets.csv in my project root folder, my app folder and in the folder enclosing my project root and app folders. I also have an additional copy of ExtractedTweets.csv within my app folder. My staticfile settings are configured as follows: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' It have placed the file in all possible locations yet django cannot seem to find it. If anyone has any idea how to resolve this error, please let me know. -
Как передать django forms все поля кроме одного?
У меня есть форма пользователя, и мне нужно в view передать все поля кроме пароля, как это сделать? -
Managing form state during navigation - Django
CONTEXT I'm working on an application with Django. I have to stick pretty close to an existing desktop app for it, which constraints the way I can build the user experience with forms. My issue is this. Say I have a form to fill in order to build a new Contract in the db. The "New Contract" page contains 5 tabs/pages in the original desktop app. 3 tabs can take inputs from users. The 2 other tabs contain related data the user might want to consult in order to fill out his form. Those 2 tabs may contain non-trivial amount of data. The "New Contract" form has an equivalent "Show Contract" page which has the same structure. That "Show Contract" page is implement as 5 different URL (e.g. 1 GET request for each, e.g. myapp/contracts/create/page1, myapp/contracts/create/page2, ...). I do not think that I can just build the html for the whole 5 tabs in a single request because of that. Otherwise building the whole thing, including the queries & rendering for the last 2 tabs takes too long, and most users would not necessarily need to refer to them anyways. WHAT I NEED Obviously, I do not expect a full … -
Django app CORS not working properly in production
this is my first time deploying django rest app. In the development i used CORS middle-ware to develop my front-end in reactjs. Now in production the CORS problem came back, and in the browser console i see thisconsole log. The problem is that the middle-ware still consider localhost, meanwhile the django app is running on remote server now. Anyone have an idea how to solve this ? Thanks ! -
Is there away of creating an end point for the Model Choices filed in Django rest framework
Hi I have a model in Django like this class MyModel(models.Model): CATEGORY = [ (1, 'Governments'), (2, 'Non Governments'), (3, 'Private Sector'), ] category = models.IntegerField(choices=CATEGORY, default=1 ) And to avoid having to change both the backend and frontend of the project every time I add a category I would like to have an endpoint that returns JSON of value and displays only these categories using the Django Rest Framework? result: [ { value:1, display:"Goverment" }, { value:1, display:"Non Gorverment" }, { value:1, display:"Private Sector" } ] Here is a serializer that I tried but I noticed Imay not be doing t the right way. class CategorySerializer(serializers.ModelSerializer): label = serializers.CharField(source='get_category_display') value = serializers.SerializerMethodField('get_value_number') def get_value_number(self, obj): return obj.category class Meta: models = myModel fields = ('value', 'label') -
Get value before template
How can i get input value after load template? i need to pass maquina value (not 189, need to pass {{qs.nombre}} or input value='maquina') before load template to run sentence sql. def show_trabajos(request): hostname = socket.gethostname() ip_add = socket.gethostbyname(hostname) qs = info_equipos.objects.all().filter(ip=ip_add) maquina= 189 codusuari = '161' ## sentencia = "exec [Empresa].[dbo].[PT_GET_ORDENES]" + str(maquina) + "," + codusuari cursor.execute(sentencia) results = namedtuplefetchall(cursor) <fieldset class="scheduler-border"> <legend class="scheduler-border">EMPLEADO</legend> <b><p class="black">IDENTIFICADO: </b><input class="sinborde" type="text" name="empleado" value="{{ user.username }}" readonly /></p></p> <b><p class="black">EMPLEADO: </b><input class="sinborde" type="text" name="empleado" value="{{ user.first_name }} {{ user.last_name }}" readonly /></p> <b><p class="black">IP: </b><input class="sinborde" type="text" name="ip" value="{{ qs.ip }}" readonly /></p> <b><p class="black">M&Aacute;QUINA: </b><input class="sinborde" type="text" name="maquina" value="{{ qs.nombre }}" readonly /></p> <b><p class="black">Nº M&Aacute;QUINA: </b><input class="sinborde" type="text" name="rec_sistrade" value="{{ qs.rec_sistrade }}" readonly /></p> <b><p class="black">USUARIO SITRADE: </b><input type="text" class="sinborde" name="user_sistrade" value="{{ user.user_sistrade }}" readonly /></p> </fieldset> -
Django left join (only two models)
I'm stack on it, please need your help. I have two models and a want to select all (or filtered) fields from Channel and left join last_published video from Video model. Need good solution using django ORM. class Channel(models.Model): name = models.CharField(max_length=150, blank=False, null=False) url = models.CharField(max_length=100, blank=False, null=False) def __str__(self): return self.name class Video(models.Model): channel = models.ForeignKey(Channel, on_delete=models.CASCADE) title = models.CharField(max_length=150, blank=False, null=False) url = models.CharField(max_length=50, blank=False, null=False, unique=True) publish_date = models.DateTimeField(blank=True, null=True, auto_created=False) embedurl = models.CharField(max_length=50, blank=True, null=True, unique=True) def __str__(self): return self.title -
Why am I getting error 404 on my django server?
I'm trying to test my django app on production server but static files are not found. I spent many hours trying to solve this issue but ended up with nothing. So, in settings.py I have this: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' Then I put all static files in a folder named 'static' in django project folder and I did python manage.py collectstatic, I got a warning that files will be overwritten then I confirmed this and files were successfully copied but i keep getting error 404. I tried adding static path to urls like this: urlpatterns = [] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) But it did nothing. -
How to run scrapy spider with celery
I'm trying to run a scrapy spider which takes some argument and runing it with os.system. But the celery task(scraper) doesn't gets executed untill it finishes. Spider class SpecificAuthorQuotesSpider(scrapy.Spider): """Extracts the quotes from specific author""" start_urls = ['https://quotes.toscrape.com/'] name = "some-quotes" def __init__(self, author=None, **kwargs): self.author = author super().__init__(**kwargs) def parse(self, response, **kwargs): item = QuotesItem() all_div_quotes = response.css('div.quote') for quote in all_div_quotes: title = quote.css('span.text::text').extract_first().replace('”', '').replace("“", "") author = quote.css('.author::text').extract_first() # Check if author's name matches if author.strip().lower() == self.author.strip().lower(): item['text'] = title item['author'] = author yield item # Crawl Next Page next_page = response.css('li.next a::attr(href)').get() if next_page is not None: yield response.follow(next_page, callback=self.parse) Task @shared_task def task_scrape_from_author(author_name): """Scrape quotes from author""" django_path = Path(__file__).resolve().parent.parent os.chdir(str(django_path)+"/scraper") os.system( "scrapy crawl some-quotes -a author='{}'".format(author_name)) View def scrape_quotes_from_author(request): if request.user.is_superuser: author_name = request.POST.get("athr_name") task_scrape_from_author.delay(author_name) messages.add_message( request, messages.INFO, 'Started crawling quotes from {}'.format(author_name)) return HttpResponseRedirect(reverse("admin:index")) else: return HttpResponseRedirect("../") I don't understand why is the task not getting completed and interrupted with any messages. I tried setting max timeout also but that din't worked. -
Django form.is_valid returns false for valid email
I am grabbing the user's entered email and using form.is_valid(). It returns False, I checked with the django shell validation for email, and it returns Invalid emailfor every email I could think of. For ex. test@gmail.com. How can I make the email pass the form.is_valid()? #forms.py class SendEmailForm(forms.Form): to = forms.CharField() subject = forms.EmailField() content = forms.CharField(widget=forms.Textarea) class Meta: fields = ['to', 'subject', 'content'] #views.py def home_view(request): print(f'Logged in as {request.user.username}') if request.method == 'POST': form = SendEmailForm(data=request.POST) if form.is_valid(): # returns False for any email print('ok') print(request.POST) else: print('not ok') print(request.POST) -
Problems Unit Testing Django Code which uses ThreadPoolExecutor
I'm writing unit test cases for some django code which is using the ThreadPoolExecutors executor.map function to map a function which makes calls to the database while testing the code there is a problem while tearing down the database OK Destroying test database for alias 'default'... C:\Users\KaushalKulkarni\Desktop\Python\guidance\venv\lib\site-packages\django\db\backends\postgresql\base.py:304: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. warnings.warn( Traceback (most recent call last): File "C:\Users\KaushalKulkarni\Desktop\Python\guidance\venv\lib\site-packages\django\db\backends\utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.ObjectInUse: database "test_guidance" is being accessed by other users DETAIL: There is 1 other session using the database. any tips on how to test this code without getting errors -
How to add tags when add a page to a known parent programatically in wagtail?
I would like to create programatically a sub page for a known parent. here is the code. parent_page = Page.objects.get(title='index02').specific news_page = BlogPage( title = 'title test 08', slug = 'title_test_08', body='Something pleasant to hear.', intro="desc", ) parent_page.add_child(instance=news_page) news_page.save() It works, but I added tags = '[tag01,tag02]' in news_page , It failed to add tags, Could sb tell me how to add tags? thanks.