Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO: How to get multiple inputs from multiple forms in views together?
In html,opening one form first by clicking on it and then it will open another form where I take user inputs. Finally I need both the inputs...which form user click first and then inputs from the second form in views. But first form information getting erased and only second form information passing to views. FORM1: <form method="post" enctype="multipart/form-data" > {% csrf_token %} {% for node in tuples %} <button class="open-button" onclick="openForm()" name="html_node_number" value= {{node.list1|safe}} type="button"> </button> </form> FORM2: <form class="form-container" method="post"> {% csrf_token %} <button type="submit" class="btn" onclick="closeForm()" name="edit_nd_decision" value=1> Prune Back </button> </form> VIEWS: if request.method == 'POST': html_node_number=request.POST.get('html_node_number') edit_nd_decision=request.POST.get('edit_nd_decision') if edit_nd_decision == '1': m_editnd_no = int(html_node_number) -
Cannot resolve keyword 'blg' into field. Choices are: content, email, id, name, post, post_id
there are similar questions but still i am not able to figure out my mistake.. i am trying to make a comment system.. the comment model is working fine.. but when i try to edit my post detail view from this .. def detailview(request, id=None): blg = get_object_or_404(BlogPost, id=id) context = {'blg': blg, 'comments': comments, } to this def detailview(request, id=None): blg = get_object_or_404(BlogPost, id=id) comments = Comment.objects.filter(blg = blg).order_by('-id') context = {'blg': blg, 'comments': comments, } i am getting this error Cannot resolve keyword 'blg' into field. Choices are: content, email, id, name, post, post_id here are my other files... models.. class BlogPost(models.Model): title = models.CharField(max_length=500) writer = models.CharField(max_length=150,default='my dept') category =models.CharField(max_length=150) image = models.ImageField(upload_to='images') post = models.TextField(max_length=2000) Date = models.DateField( default=datetime.date.today) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(BlogPost , on_delete=models.CASCADE) name = models.CharField (max_length = 150) email = models.CharField (max_length = 150) content = models.TextField () def __str__(self): return self.email forms.py from django import forms from.models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('content',) views.py def detailview(request, id=None): blg = get_object_or_404(BlogPost, id=id) comments = Comment.objects.filter(blg = blg).order_by('-id') context = {'blg': blg, 'comments': comments, } -
Can't add user into ManytoManyField in Django?
I have a model called Class which has ManyToManyField with Student. Student model has a OnetoOneField with CustomUser model. When the CustomUser is created, the Student object is also created but why I got error with Student instance expected? I don't know where is my mistake. Can u spot me the mistake? When the Class object is created, it will generates a code and student has to enter that code to join the Class via ManyToManyField. I got error on this line class_code.student.add(user) in forms.py and return super().form_valid(form) in views.py. Error I got TypeError: 'Student' instance expected, models.py class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) class Class(models.Model): teacher = models.ForeignKey(CustomUser, on_delete=models.CASCADE) student = models.ManyToManyField(Student) random_code = models.CharField(max_length=250, default=uuid.uuid4().hex[:6]) class EnterCode(models.Model): student = models.ForeignKey(CustomUser, on_delete=models.CASCADE) code = models.CharField(max_length=50) forms.py class EnterCodeForm(forms.ModelForm): class Meta: model = EnterCode fields = ['code', ] def save(self): user = super().save(commit=False) user.save() code = str(self.cleaned_data.get('code')) class_code = Class.objects.get(random_code=code) class_code.student.add(user) class_code.save() return (user, class_code) the view for join class class JoinClass(LoginRequiredMixin, CreateView): template_name = "attendance/content/student/enter_code.html" login_url = '/' form_class = EnterCodeForm success_url = '/home/' def form_valid(self, form): form.instance.student = self.request.user return super().form_valid(form) here is the forms how I create User class StudentRegisterForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields … -
How do I get the loop to show up in the form? Django
Now I can loop to display the date information of the item. I wrote it to an HTML file. I want to show the data that I looped in the form. How can I do it? My requirement is to display the date information in a format with the forms.RadioSelect date format so that it can be selected for confirmation on the form. My fils.html <div class="p-4"> <ul> {% for item in order.items.all %} <li> <span>{{ item }}</span><span>฿{{ item.price }}</span> </li> {% for i in item.meal.meal.dates_available %} {{i}}<br> {% endfor %}<br> {% endfor %} </ul> </div> <form method="post" class="pt-2"> {% csrf_token %} {{ form.non_field_errors }} <div class="py-2"> {{ form.note.errors }} <label for="{{ form.delivery_date.id_for_label }}">delivery date</label> <div> {{ form.delivery_date }} </div> </div> <div> {{ form.address.errors }} <label for="{{ form.address.id_for_label }}">Address</label> <div> {{ form.address }} </div> </div> <input type="submit" value="Order"> </form> </div> From the code it returns something like this: Young Coconut by Lunia ฿120.00 8 September 2020 9 September 2020 -------------------------------------------------- delivery date o ............. o ............. example: date 08/09/2020 o ............. Address | | text area Order <-- Submit button I need the date information of the item Show in the Delivery Date forms. My forms.py from django import forms … -
Retreaving data from postgresql by pg_trgm
I'm developing Django app. This app retrieves data from postgresql by pg_trgm to make it faster. In local environment, it works well and fast, but ec2 environment, it takes a long time to get data and display on the result page. below are the performance of the two environments. Local PC Sort (cost=283.37..283.52 rows=58 width=1413) Sort Key: image_amount DESC -> Bitmap Heap Scan on test_eu (cost=52.86..281.67 rows=58 width=1413) Recheck Cond: (eng_discription ~ '.*remote controller.*'::text) -> Bitmap Index Scan on text_index (cost=0.00..52.84 rows=58 width=0) Index Cond: (eng_discription ~ '.*remote controller.*'::text) ec2 Sort (cost=283.27..283.41 rows=58 width=1410) Sort Key: image_amount DESC -> Bitmap Heap Scan on test_eu (cost=52.86..281.57 rows=58 width=1410) Recheck Cond: (eng_discription ~ '.*remote controller.*'::text) -> Bitmap Index Scan on text_index (cost=0.00..52.84 rows=58 width=0) Index Cond: (eng_discription ~ '.*remote controller.*'::text) Results are close, so I wonder why ec2 environment is slow. Please teach me where should I check? PS. My local PC's memory is 8GB and ec2 uses instance type of "t2.micro" it means memory is 1GB.Does it related to this problem?? -
How is the super method to be used in Django?
I don't want you to think I would be lazy. I already read about the super method to override pre-existing methods in Django (and possibly also in Python in general). Still I must admit that I did not really understand everything. So, instead of asking for a particular application of the method, I wanted to ask how this method can be applied. Sounds weird or too broad? Perhaps it helps, if I describe my problem. Let's say I want to enhance a class-based view. My experience with them is also limited. Very often, pages on the web just say, "yeah, you have to override this or that method." Me, "Ehm, how do I actually know about the existence of this or that method?" So far, I have to come to know a few like get, post and form_valid, but I do not know in general which are available or where I have to read them up, as I guess that they are in subclasses of subclasses of subclasses in some general files and I don't even know where those are. So, imagine I have found the corresponding method, then I do not know how to handle that. Here is an … -
Activate or De-Activate Status in database through Ajax-JavaScript using Django (help)
I am trying to implement a function using Ajax-JavaScript in which when I click on Activate Option, the value in my Django database for this field changes to 'Active' and is displayed on the HTML page as active with Activate Message. If De-Activate is clicked, the text changes to De-Active along with it's value in the django database and show De-Activated message HTML page: <div class="col-sm-5"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Job activation status</h3> </div> <div class="panel-body"> <td> Campus Name </td> <td> hod_name </td> <td> <select name="status" class="form-control"> <option value="1">Active</option> <option value="2">Disabled</option> </select> </td> </div> </div> </div> Model: class Campus(models.Model): STATUS = ( ('Active', 'Active'), ('Disabled', 'Disabled'), ) campus_name = models.CharField(blank=True, max_length=30) hod_name = models.CharField(blank=True, max_length=25) status = models.CharField(max_length=10, choices=STATUS, default='Disabled', blank=True) def __str__(self): return self.campus_name View: def status_update(request, pk): campus_status = get_object_or_404(Campus, pk=pk) campus_status.status = 'Active' if campus_status.status == 'Disabled' else 'Disabled' campus_status.save(update_fields=['status']) messages.success(request, '{} Status: {} successfully'.format(campus_status.campus_name, campus_status.status)) return redirect('/dashboard/create_campus/') -
Version control with lightsail
I've uploaded the code on amazon lightsail with cloning from github It's a django My question is the code works but if i change and commit changes to the repo will i have to re upload and recreate the lightsail instance? -
Django-tenants Schema, need to create centralized authentication (django.contrib.auth)
My purpose is to create a multitenant application able to serve several companies. The requirements that I need are to have centralized authentication (django.contrib.auth) in order to have a central login page where after the user has correctly logged in, it will be redirected to the correct subdomain/schema. Each company will manage its own users but I want them to be stored in the public schema because I need to access also remotely using Web services to a centralized and fixed URL. In addition to that, I've to extend the User Model to add additional information. So in my public tenant, I want to have: Company User (django.contrib.auth) please help me out in this with your suggestion or any documents will be helpful for me. -
UpdateView define primary key
I am trying to set my primary key in a class based view to a unique value from my models. models.py from django.db import models from django.forms import model_to_dict class Stuff(models.Model): thing = models.CharField(max_length=100, verbose_name="Thing", unique=True) item = models.CharField(max_length=100, verbose_name="Item") def __str__(self): return self.thing def toJSON(self): item = model_to_dict(self) return item views.py from django.urls import reverse_lazy from django.views.generic import CreateView, UpdateView class NewStuff(CreateView): model = Stuff form_class = NewStuffForm template_name = 'stuff.html' success_url = reverse_lazy('search_stuff') def post(self, request, *args, **kwargs): data = {} try: action = request.POST['action'] if action == 'add': form = self.get_form() data = form.save() else: data['error'] = "No option has been selected" except Exception as e: data['error'] = str(e) return JsonResponse(data) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'New Stuff' context['stuff_url'] = reverse_lazy('search_stuff') context['action'] = 'add' return context class EditStuff(UpdateView): model = Stuff form_class = NewStuffForm template_name = 'stuff.html' success_url = reverse_lazy('search_stuff') def dispatch(self, request, *args, **kwargs): self.object = self.get_object() return super().dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): data = {} try: action = request.POST['action'] if action == 'edit': form = self.get_form() data = form.save() else: data['error'] = '"No option has been selected" except Exception as e: data['error'] = str(e) return JsonResponse(data) def get_context_data(self, **kwargs): … -
how to create side nav in djnago and load without reloading?
I am trying to create a sidenav in djnago and load menu in same page without reloading page. example ( about , contact , work load in same page ) Search a lot but and found AJAX but at last i cant figure out how to do this. can any one help me on this with code. I want to create something like this -
Which database design is better for django follow/unfollow?
I've been looking for a good database design for a twitter like social network site in my django project and I found two possibilities: This one down here class Following(models.Model): follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following') following = models.ForeignKey(User, on_delete=models.CASCADE, related_name='followers') And this other one class User(AbstractUser): follows = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followed_by') pass Are these the same? Is there any difference here? Which one should I choose? I'm kind of new to this so I can`t figure out which one is the best option. I find the first one easier to understand. -
Having posts separated by more than one category on the Home Page|Django
I want to divide the home page into categories. And categories should contain post titles. I can redirect categories in another url, but I can't show it on the home page. i have 2 models: blog and category models.py class Category(models.Model): parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children'); title = models.CharField(max_length=120, verbose_name='kategori') slug = models.SlugField(unique=True, editable=False) class Blog(models.Model): user = models.ForeignKey('auth.User', verbose_name='yazar', on_delete=models.CASCADE, related_name='blogs') title = models.CharField(max_length=120, verbose_name='başlık') # content = models.TextField(verbose_name = 'metin') content = RichTextField(verbose_name='metin') category = models.ForeignKey(Category, on_delete=models.CASCADE, default='') image = models.ImageField(null=True, blank=True, verbose_name='foto') publishing_date = models.DateTimeField(verbose_name='tarih') onem = models.BooleanField(default='True') slug = models.SlugField(unique=True, editable=False) view.py from django.shortcuts import render # Create your views here. from blog.models import Blog,Category def home_view(request): categorys = Category.objects.all() blogs = Blog.objects.all() r =Blog.objects.filter(category__title=Blog.category) return render(request,'index.html', {'blogs' : blogs, 'categorys' : categorys, 'r':r,}) def about_view(request): return render(request, 'about.html' , {}) def category_detail(request, cats): category_posts = Blog.objects.filter(category__title=cats) return render(request, 'category.html' , {'cats':cats, 'category_posts':category_posts, }) How should the index.html structure be? -
django.db.utils.IntegrityError: NOT NULL constraint failed: unesco_site.category_id
I am trying to populate database from data in the csv file using a python script. I did some research but couldn't find a relevant example rather I found python packages that would load csv. And there some articles guiding on how to upload csv file which isn't what I wanted. Following is a glimpse of load.csv file. There are 11 columns as you can see. # models.py from django.db import models class Category(models.Model): category = models.CharField(max_length=128) def __str__(self): return self.name class State(models.Model): state = models.CharField(max_length=25) def __str__(self): return self.name class Region(models.Model): region = models.CharField(max_length=25) def __str__(self): return self.region class Iso(models.Model): iso = models.CharField(max_length=5) def __str__(self): return self.iso class Site(models.Model): name = models.CharField(max_length=128) year = models.IntegerField(null=True) area = models.FloatField(null=True) describe = models.TextField(max_length=500) justify = models.TextField(max_length=500, null=True) longitude = models.TextField(max_length=25, null=True) latitude = models.TextField(max_length=25, null=True) #one to many field category = models.ForeignKey(Category, on_delete=models.CASCADE) state = models.ForeignKey(State, on_delete=models.CASCADE) region = models.ForeignKey(Region, on_delete=models.CASCADE) iso = models.ForeignKey(Iso, on_delete=models.CASCADE) def __str__(self): return self.name I'm not being able to make the relationship among the models while inserting data. Earlier, I had used get_or_create() method but I was recommended to not to use it as I had no defaultvalue to be given and used create() method. Somewhere … -
Deploying Django with Nginx, Gunicorn and Supervisor
I'm trying to deploy my Django app with Nginx and Gunicorn by following this tutorial, but I modified some steps so I can use Conda instead of ViritualEnv. The setup looks like this: Nginx replies with my Vue app Requests from Vue are made to api.mydomain.com Nginx listens to api.mydomain.com and directs requests to Gunicorn's unix socket Things I've checked: I can see the Vue requests in Nginx's access.log. I can also see those requests with journalctl -f -u gunicorn and in my supervisor.log. When my Django app starts, it's creates a log file, so I can see that Gunicorn starts it. But Django is not responding to requests from the unix socket. I can see a response from Django when I ssh in and run the following command: curl --no-buffer -XGET --unix-socket /var/www/mydomain/run/gunicorn.sock http://localhost/about. This command only gives a response when http://localhost is included. My Nginx, Supervisor and Gunicorn configurations all use the full path to gunicorn.sock. Should I see Django running on port 8000 or anything if I do something like nmap localhost? I saw another post mention that Nginx should point to port 8000 and that gunicorn should be run with either: gunicorn --bind 0.0.0.0:8000 <djangoapp>.wsgi --daemon … -
How to compare 2 fields from 2 different models in Django?
I want to compare 2 fields from 2 different models and here is the idea behind it. Teacher can create Class which has ManytoManyField with Student model. When the Class model is created it will generates a random_code and Students will have to enter that code via EnterCode model to join the Class model. models.py class Class(models.Model): teacher = models.ForeignKey(CustomUser, on_delete=models.CASCADE) student = models.ManyToManyField(Student) random_code = models.CharField(max_length=250, default=uuid.uuid4().hex[:6]) subject = models.CharField(max_length=150) class EnterCode(models.Model): student = models.ForeignKey(CustomUser, on_delete=models.CASCADE) code = models.CharField(max_length=50) class Teacher(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) So the Class object 1 will generates a code and when student enters that code it will adds that student to the student field (ManyToManyField) in Class Model. How can I compare code with random_code and add Student to ManytoManyField? -
Patch a class method used in a view
I'm trying to test my view given certain responses from AWS. To do this I want to patch a class I wrote to return certain things while running tests. @patch.object(CognitoInterface, "get_user_tokens", return_value=mocked_get_user_tokens_return) class TestLogin(TestCase): def test_login(self, mocked_get_user_tokens): print(CognitoInterface().get_user_tokens("blah", "blah")) # Works, it prints the patched return value login_data = {"email": "whatever@example.com", "password": "password"} response = self.client.post(reverse("my_app:login"), data=login_data) Inside the view from "my_app:login", I call... CognitoInterface().get_user_tokens(email, password) But this time, it uses the real method. I want it to use the patched return here as well. It seems my patch only applies inside the test file. How can I make my patch apply to all code during the test? -
Good option for Back end language [closed]
Is Go a good language to begin with Backend Development or other framework accept Express who uses React.js as Frontend? and which backend language do you use? -
I am working on a web app using Django, running on Nginx, and I am getting 111 connection refused, and I cant work out why
I have previously configured an app in the exact same way but when I updated Ubuntu, I broke my python install. I fixed python, and tried to set up another app in the exact same way, using the same tutorials, but I am getting a 111 error when I try to connect. I can connect if I run the app using gunicorn (which I only tried because it wasn't working using nginx), but I want to find the problem and fix it. As far as I can see everything is configured according to the documentation I went through. Here is the uwsgi config file # glossbox_uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = /usr/local/apps/glossbox/glossbox # Django's wsgi file wsgi-file = /usr/local/apps/glossbox/glossbox/glossbox/wsgi.py # the virtualenv (full path) home = /usr/local/apps/glossbox/venv plugins = python # process-related settings # master master = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe socket = server 127.0.0.1:8001 # ... with appropriate permissions - may be needed chmod-socket = 664 clear environment on exit vacuum = true here is the nginx conf file: # glossbox_nginx.conf # the upstream component … -
Django CharField as primary key still allow Null value to be save
Currently i have the following model that i would like to set CharField as primary key( my database is Mysql) class Customer(models.Model): class Meta: db_table = "customers" verbose_name = _('Customer') verbose_name_plural = _('Customers') customer_id = models.CharField(_('Customer ID'),max_length=255, primary_key=True) name = models.CharField(_('Name'), max_length=255) created_at = models.DateTimeField(auto_now_add=True) In the document it stated that : primary_key=True implies null=False and unique=True. Only one primary key is allowed on an object. In Mysql the primary key has the following structure: customer_id, type=varchar(255), collation=latin1_swedish_ci, Attributes=blank Null=No, Default=None,Comments=blank, Extra=blank but when i try to use the save() method with null value for primary key: Customer.objects.create(customer_id=None, name="abc") It still save Null value in the primary key without returning any error or validation, why is that? -
Using django as a RESTAPI, how to run some modules(.py or .exe) and return result?
I made my web site using node.js. If I clicked some button at website, modules(.exe files) are run and make some result. That results are applied in next page. In this situation, I want to change running modules using RESTAPI. Can I develop RESTAPI using django? And Is it possible? -
Django Object is Not Serializable CommandError using Dumpdata with Natural Keys
I am trying to use 'natural keys' for serialization (docs) in a "manage.py dumpdata" command: python manage.py dumpdata --natural-primary --natural-foreign --indent 4 --format json --verbosity 1 > tests\test_fixtures\test_db2.json and I am getting the following error when I use --natural-foreign on other apps that use the Project or Task model (which they all must by design): CommandError: Unable to serialize database: Object of type Project is not JSON serializable Exception ignored in: <generator object cursor_iter at 0x000001EF62481B48> Traceback (most recent call last): File "C:\Users\Andrew\anaconda3\envs\Acejet_development\lib\site-packages\django\db\models\sql\compiler.py", line 1586, in cursor_iter cursor.close() sqlite3.ProgrammingError: Cannot operate on a closed database. If I just dumpdata from this, the 'projects' app, it works, but other apps are built with entities related to Project or Task and there the --natural-foreign option fails. The problem occurs when a model (say Question) calls for a natural_key from Task, which includes a for a natural_key from Project. If I use the Pycharm Python Console to access querysets of Projects or Tasks ('q' here), this works: serializers.serialize('json', q, indent=2, use_natural_foreign_keys=True, use_natural_primary_keys=True) But if 'w' is a list of Question objects from another app that have a Task foreign key I get this error: Traceback (most recent call last): File "<input>", line 1, … -
How to check a radio button based on user input in a Django Template?
I'd like to check a specific radio button if one or two of the values of my two input fields exceeds a certain number. I am currently using Django Form to render both the textboxes and the radio buttons: Like this: The Radio Button: 'gap_result': HorizontalRadioSelect( choices=NG_gap, attrs={ 'default': 'OK', 'class': 'radio colorC', 'style': ' margin-top: 15px; margin-left: 25px;', 'name': 'radio_Gap', 'id ': 'radio_Gap_Result', }), The two textboxes: 'gap_X': forms.TextInput( attrs={ 'class': 'form-control cent ', 'placeholder': 'X', 'type': 'text', 'id': 'gap_X', # 'readonly': 'false', }), 'gap_Y': forms.TextInput( attrs={ 'class': 'form-control cent ', 'placeholder': 'Y', 'type': 'text', 'id': 'gap_Y', }), What I need is to change the radio button to be OK if neither of the values exceeds 8 and then NG if it does. Here's a visual representation: Here's what I have in my template using the django forms: <div class="row"> <div class = "col-3"> <div class="form-text"> {{form.gap_X}} </div> </div> <div class = "col-3"> <div class="form-text"> {{form.gap_Y}} </div> </div> {{form.gap_result}} </div> -
How to set a url pattern for year month and date?
I'm trying to create blog project using django I am getting this error. ValidationError at /^(?P2020\d{4})/(?P09\d{2})/(?P06\d{2})/(?Psoftware-industry[-\w]+)/$ ['“06” value has an invalid date format. It must be in YYYY-MM-DD format.'] -
I am studying DRF, and I have a question about specifying ManyToManyField in serializers
While creating a group, I want to add the User received in the request to the members column, the ManyToManyField of the group model. So I created a serializer and modified create to implement the desired functionality, but I'm not sure if this is a good way. I think there is a better way, so I post a question. I hope you can help. User # users.models class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) introduce = models.TextField(max_length=300, blank=True, default=None) attendGroups = models.ManyToManyField( "groups.Group", related_name="groups", blank=True ) # users.serialize class userSimpleInfoSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("id", "nickname") Group # groups.model class Group(TimeStampModel): category = models.CharField(max_length=50) title = models.CharField(max_length=300, blank=True, null=True) discription = models.TextField(blank=True, null=True) leader = models.ForeignKey( "users.User", related_name="leader", on_delete=models.CASCADE ) members = models.ManyToManyField("users.User", related_name="members", blank=True) attends = models.ManyToManyField("users.User", related_name="attends", blank=True) time = models.IntegerField(default=1) def __str__(self): return self.title # groups.serialize class GroupBaseSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=True) leader = UserBaseSerializer(read_only=True) time = serializers.IntegerField(read_only=True) members = userSimpleInfoSerializer(many=True, read_only=True) attends = userSimpleInfoSerializer(many=True, read_only=True) def __init__(self, leader, *args, **kwargs): super(GroupBaseSerializer, self).__init__(*args, **kwargs) self.leader = leader class Meta: model = Group fields = ("id", "category", "title", "discription", "leader", "time", "members", "attends",) def create(self, validated_data): group = Group.objects.create( category=validated_data["category"], title=validated_data["title"], discription=validated_data["discription"], leader=self.leader, ) group.members.add(self.leader) group.save() …