Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fetch data from manytomany field django
As i have many user. i want to fetch the name of users join a particular session in Players_Participating class MyUser(AbstractBaseUser): user_name=models.CharField(max_length=10,blank=True,null=True,unique=True) def __str__(self): return str(self.user_name) class Session(models.Model): Host=models.ForeignKey(MyUser,on_delete=models.CASCADE,related_name='host') game=( ('cricket','cricket'), ('football','football'), ('basketball','basketball'), ('hockey','hockey'), ('gym','gym'), ('baseball','baseball'), ) Sport=models.CharField(max_length=20,choices=game) Players_Participating=models.ManyToManyField(MyUser,related_name='related') def __str__(self): return str(self.Host) -
Need _id from mongodb in django from models where object id is exists
I am using MongoDB in Django. i need to return _id (the object field). in mongdb database for every entry their is a _id was created which is a 32 bit object id. i need that value. _id:ObjectId("5e6b77d580a32dff7bb1ef11") this value of every entry in mongodb. data1=Filter_data.objects.get(user_id=raw_data["user_id"],post_id=raw_data["post_id"]) -
Django - Select MAX of field of related query set
Say if I have models: class User(models.Model): name = ... dob = ... class Event(models.Model): user = models.ForeignKey(User, ...) timestamp = models.DateTimeField() And I want to query all Users and annotate with both Count of events and MAX of Events.timestamp I know for count I can do: Users.objects.all().annotate(event_count=models.Count('event_set')) But how do I do max of a related queryset field? I want it to be a single query, like: SELECT Users.*, MAX(Events.timestamp), COUNT(Events) FROM Users JOIN Events on Users.id = Events.user_id -
Partial search using wildcard in Elastic Search
I want to search on array value in Elastic search using wildcard. { "query": { "wildcard": { "short_message": { "value": "*nne*", "boost": 1.0, "rewrite": "constant_score" } } } } I am search on "short_messages", It's working for me. But I want to search on "messages.message" it's not working. { "query": { "wildcard": { "messages.message": { "value": "*nne*", "boost": 1.0, "rewrite": "constant_score" } } } } And I also want to search for multiple fields in an array. For Example:- fields: ["messages.message","messages.subject", "messages.email_search"] It is possible then to give me the best solutions. Thanks in Advance. -
How to Add Auti fields that user can edit
I am creating an model in this I need a autogenerated field other than id .... An AutoField Seequnce #. Auto increment # 10,20,30, - For sequencial ordering. (Auto Generated -but user can edit ) It need to increment on the basis of 10 also the user can able to edit it ..... It's my rquirement Here is my model : class Abc(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) order = models.AutoField() How to generate it on the basis of 10... Also how can user edit it -
Combination custom filter with many to many
class MyText(models.Model): myId = models.CharField(unique=True,null=False,max_length=20) tags1 = models.ManyToManyField(Tag1) tags2 = models.ManyToManyField(Tag2) I have model which has two many-to-many field. class MyTextFilter(filters.FilterSet): tags1 = filters.ModelMultipleChoiceFilter( field_name='tags1__name', queryset=Tag1.objects.all(), ) tags2 = filters.ModelMultipleChoiceFilter( field_name='tags2__name', queryset=Tag2.objects.all(), ) class Meta: model = MyText fields = ('myId','tags1','tags2') Now I want to make the filter that drop the rows which doesn't have either tags1 nor tags2. How can I make combination custom filter?? -
unhashable type: 'ReturnDict' drf django
I'm trying to add but getting this error: unhashable type: 'ReturnDict' models.py: class SumInsuredEntity(UUIDBase): field_name = CICharField(max_length=255,null=False,blank=False,verbose_name=_("Field Name"), unique=True) is_balance = models.ForeignKey(ValidChoice, to_field="key", db_column="is_balance", related_name="is_balance", null=True, blank=True, verbose_name=_("Is Balance"),default='no', on_delete=models.DO_NOTHING) is_thresold = models.ForeignKey(ValidChoice, to_field="key", db_column="is_thresold", related_name="is_thresold", null=True, blank=True, verbose_name=_("Is Thresold"),default='no', on_delete=models.DO_NOTHING) status = models.SmallIntegerField(_("Status:1 for Active; 0:InActive"), default=1) class Meta: db_table = "tpa_master_sieav" def __str__(self): return str(self.uid) Views.py: @api_view(['POST']) def sumInsuredEntityAdd(request): ''' sumInsuredEntity Create Api ''' data= decode_data(request.data.copy()) serializer_obj = SumInsuredEntitySerializer(data=data) if serializer_obj.is_valid(raise_exception=True): try: sumInsured_save = serializer_obj.save() return CustomeResponse(request=request, comment=SUM_INSURED_ENTITY_ADDED_SUCCESSFULLY,data=json.dumps({serializer_obj.data}, cls=UUIDEncoder), message= SUM_INSURED_ENTITY_ADDED_SUCCESSFULLY, status=status.HTTP_200_OK) except Exception as e: print(e) return CustomeResponse(request=request, log_data=json.dumps(str(e), cls=UUIDEncoder), comment=COULD_NOT_SAVE_SUM_INSURED_ENTITY, message=COULD_NOT_SAVE_SUM_INSURED_ENTITY, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) else: return CustomeResponse(request=request, comment=FIELDS_NOT_VALID, message=FIELDS_NOT_VALID, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) its working good but showing error when trying to dump serializer_obj.data -
How to model this relationship in Django Models
I’m developing a web application that is developing products, the issue is the products available should be activated at three levels. The company should be able to turn individual products on or off. Each organization should be able to turn the individual product (from only the allowed on the previous level) on or off. The administrator can activate the product availability on or off for a specific user. How would you recommend to design this at the level of models? -
Real-time audio streaming from javascrit to python-django
i want to record client's microphone in the browser with javascript and send it in real-time to process the audio stream in python. Is django able to do this in real-time? Thank you! -
What is the difference between django3 and django2 for the admin site
I created two python virtual environments on centos with django2 and django3 installed。 Python 3.7.0 Package Version ---------- ------- Django 2.2.2 pip 20.0.2 pytz 2019.3 setuptools 45.3.0 sqlparse 0.3.1 wheel 0.34.2 Package Version ---------- ------- asgiref 3.2.5 Django 3.0.3 pip 20.0.2 pytz 2019.3 setuptools 45.3.0 sqlparse 0.3.1 wheel 0.34.2 Enter the two virtual environments separately, and create the django project using the command django-admin startproject test_project, and then launch it using the command python manage.py runserver 0.0.0.0:8000. Access to the admin site using a browser, django version 2.2.2 success. version 3.0.3 program exit, I tried to add --noreload after the instruction, access again, the program exit, and terminal print segment error (vomit a nuclear). I tried switching to the virtual environment to launch the same django project, and the same thing happened. Access to the admin site with version 3.0.3 of django failed. After looking at the two settings.py, there seems to be no difference. So I'm a little confused. Is there any additional configuration parameter in settings.py for django3? """ Django settings for newrecord project. Generated by 'django-admin startproject' using Django 3.0.3. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, … -
Email forms do not match in Django Custom-User registration
I'm setting up a custom-user registration form to create an account on my Django project. I feel I'm missing something very simple that keeps me from registering for some reason. My registration form demands 4 fields to be filled before a new user can register. Of these 4 fields, two are just a confirmation of the email address. Here is a copy of my form.py: class UserRegisterForm(forms.ModelForm): username = forms.CharField(label='Username') email = forms.EmailField(label='Email Address') email2 = forms.EmailField(label='Confirm Email') password = forms.CharField(widget=forms.PasswordInput) class Meta: model = CustomUser fields = ['username', 'email', 'email2', 'password'] def clean_email(self): email = self.cleaned_data.get('email') email2 = self.cleaned_data.get('email2') if email != email2: raise forms.ValidationError("Emails do not match") And here is a copy of my view.py: def register_view(request): next = request.GET.get('next') form = UserRegisterForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get('password') user.set_password(password) user.save() new_user = authenticate(username=user.username, password=password) login(request, new_user) if next: return redirect(next) return redirect('/stocks/') Whenever I try to register as a new user, my form validation error is raised as is says that my two emails do not match (I copy-paste them to make sure they are identical). I feel I'm missing something that is right under my nose... Cheers to all of you and … -
Django, how to store and retrieve credit card information in Stripe and use it for later charges?
I am working on an e-commerce website project and I am stuck here. Although I looked at the documentation but it wasn't helpful for me using Django. All I learned was to store customer id in my side and use it for later charges. I don't know how to fetch customer cards from stripe API, whether they exists or not? save it and use for future purchase? Thank you for help and support! -
DRF hyperlinkedmodelserializer cannot find view name
I am converting from ModelSerializer to HyperlinkedModelSerializer, following this document(https://www.django-rest-framework.org/api-guide/relations/) board # board/urls.py app_name = 'board' urlpatterns = [ path('boards/', BoardList.as_view(), name='board-list'), path('boards/<int:pk>', BoardDetail.as_view(), name='board-detail'), path('', api_root), ] urlpatterns = format_suffix_patterns(urlpatterns) # board/views.py @api_view(['GET']) def api_root(request, format=None): return Response({ 'boards': reverse('board:board-list', request=request, format=format) }) class BoardList(generics.ListCreateAPIView): queryset = Board.objects.all() serializer_class = BoardSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] # author = serializers.PrimaryKeyRelatedField( # read_only=True, default=serializers.CurrentUserDefault() # ) author = serializers.HyperlinkedRelatedField( read_only=True, default=serializers.CurrentUserDefault() ) def perform_create(self, serializer): serializer.save(author=self.request.user) class BoardDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Board.objects.all() serializer_class = BoardSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsAuthorOrReadOnly] # board/serializers.py class BoardSerializer(serializers.HyperlinkedModelSerializer): # author = serializers.PrimaryKeyRelatedField( # read_only=True, default=serializers.CurrentUserDefault() # ) author = serializers.HyperlinkedRelatedField( view_name='user-detail', read_only=True, default=serializers.CurrentUserDefault() ) url = serializers.HyperlinkedIdentityField(view_name="board:board-detail") class Meta: model = Board # fields = ('id', 'author', 'title', 'body', 'image', 'created','updated') fields = ('url','id', 'author', 'title', 'body', 'image', 'created','updated') users # users/serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): # boards = serializers.PrimaryKeyRelatedField( # many=True, queryset=Board.objects.all() # ) boards = serializers.HyperlinkedRelatedField( view_name='user-detail', many=True, queryset=Board.objects.all() ) url = serializers.HyperlinkedIdentityField(view_name="users:user-detail") class Meta: model = User # fields = ('id', 'username', 'boards') fields = ('url', 'id', 'username', 'boards') I got this error, ImproperlyConfigured at /boards/ Could not resolve URL for hyperlinked relationship using view name "board-detail". You may have failed to include the related model in … -
Open link in new internal windows django, python
I need create web site with some links to another resources and I would like when visitor click in one of this links the new windows(pop up) is opened in the same page, and then visitor can close this window and open another link ... in python and django its possible? -
How can you query distinct values with Graphql?
I'm using django as back-end with a mongoDB and i'm trying to get distinct values with Graphql but i keep getting this error : "message": "Received incompatible instance \"{'subreddit': 'politics', 'score': 75799}\"." Here is my schema.py : class TopicType(DjangoObjectType): class Meta: model = Topic class Query(graphene.ObjectType): all_topics = graphene.List(TopicType) topic = graphene.Field(lambda: graphene.List(TopicType),subreddit=graphene.String(),score=graphene.String()) def resolve_all_topics(self, info,**kwargs): return Topic.objects.all() def resolve_topic(self,info,**kwargs): return Topic.objects.values("subreddit").order_by().annotate(score =Sum("score")) schema = graphene.Schema(query=Query) And here is my query query getTopics{ topic { subreddit }} -
how to serialize ArrayField on Django rest framework?
I'm trying to create some ArrayField on my model but when i try to send a POST request i get this error: File "path-to-env/lib/python3.8/site-packages/rest_framework/serializers.py", line 1072, in get_fields fields[field_name] = field_class(**field_kwargs) File "path-to-env/lib/python3.8/site-packages/rest_framework/fields.py", line 1442, in init super().init(**kwargs) TypeError: init() got an unexpected keyword argument 'child' The serializer class: (i've also tried with "all") class BenefitSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.id') class Meta: model = Benefit fields = ( 'name', 'description', 'is_active', 'is_cumulative', 'max_usage', 'start_at', 'end_at', 'active_days_week', 'discount_type', 'categories', 'categories_are_inclusive', 'brands', 'brands_are_inclusive', 'zip_code_ranges', 'user' ) The model: class Benefit(models.Model): user = models.ForeignKey(to='auth.User', on_delete=models.CASCADE) code = models.UUIDField(default=uuid.uuid4) name = models.CharField(max_length=255) description = models.CharField(max_length=255) is_active = models.BooleanField(default=False) is_cumulative = models.BooleanField(default=False) max_usage = models.IntegerField(default=0) start_at = models.DateTimeField(auto_now=True) end_at = models.DateTimeField(auto_now=True) active_days_week = ArrayField( base_field=models.CharField(max_length=3), choices=DAYS_OF_WEEK, default=list, verbose_name='active_days' ) discount_type = models.CharField( choices=DISCOUNT_TYPES, max_length=10, default='percent', verbose_name='discount_type' ) categories = ArrayField( base_field=models.CharField(max_length=50), default=list, verbose_name='categories' ) categories_are_inclusive = models.BooleanField(default=False) brands = ArrayField( base_field=models.CharField(max_length=50), default=list, verbose_name='brands' ) brands_are_inclusive = models.BooleanField(default=False) zip_code_ranges = ArrayField( base_field=models.IntegerField(), default=list, verbose_name='zip_code_ranges' ) -
Optimal Platform (Django, Rails, etc.) for Developing a Web Application With Plans for Native Mobile Applications?
I understand that this question may have several "correct" answers based on personal preferences, but I have spent a fair bit of time trying to find a setup that will work but have yet to come across a direct answer. I have a fair bit of experience with Ruby on Rails framework, some with Python based applications, and am more than willing to learn any web architecture needed. I have laid our the requirement of the application below. Application Requirements: + Connect to a single database (for both the web and mobile application) + Allow Authentication + Allow for the execution of python scraping script I -
Django - Insert data from uploaded excel file in the database model
I am trying to populate the database with data from uploaded xlsx file. I have followed the steps from this tutorial: https://buildmedia.readthedocs.org/media/pdf/django-excel/latest/django-excel.pdf In my case after upload the 404 error page occurs while the web server error log file only shows: [Sun Mar 15 20:31:11.075408 2020] [wsgi:error] [pid 6756] [remote 192.168.1.7:53883] Bad Request: /Project/store/ I am somehow stuck at this point ... I u/stand that thew form is not valid, but why? extract from models.py class Store(models.Model): code = models.CharField(max_length=100, unique=True) name = models.TextField() address = models.TextField() city = models.CharField(max_length=100) zip = models.IntegerField() def __str__(self): return self.cod+" "+self.nume class Meta: ordering = ["cod"] verbose_name_plural = "Stores" extract from view.py class UploadFileForm(forms.Form): file = forms.FileField() def store(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): request.FILES['file'].save_to_database( model=Store, mapdict=['code', 'name', 'address', 'city', 'zip']) return HttpResponse("OK") else: return HttpResponseBadRequest() else: return render(request, 'store.html', {}) extract from template - store.html <form action="{% url "store" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group mb-4 mt-3"> <label for="exampleFormControlFile1">Excel file ONLY !</label> <input type="file" title="Upload excel file" name="excel_file" class="form-control-file" id="exampleFormControlFile1" required="required"> </div> <input type="submit" value="Upload" name="time" class="mt-4 mb-4 btn btn-primary"> </form> -
Django REST Framework ApiView not allowing DELETE
I am new to Django and I am having a issue sending a DELETE request to a class based view which inherits from APIView. Here is my class: class PageDetail(APIView): def get(self, request, pk): page = get_object_or_404(Page, pk=pk) data = PageSerializer(page).data return Response(data) def put(self, request, pk): stream = io.BytesIO(request.body) response = JSONParser().parse(stream) page = Page.objects.get(pk=pk) page.title = response.get('title', page.title) page.content = response.get('content', page.content) user = User.objects.get(pk=response.get('author', page.author)) page.author = user page.save() return HttpResponseRedirect(reverse('pages_detail', args=(page.id,))) def delete(self, request, pk): page = Page.objects.get(pk=pk) page.delete() return HttpResponseRedirect(reverse('pages_list')) When I make the DELETE request, the resource is deleted, but the page responds with the message: {'detail':'Method 'DELETE' not allowed.'} Although in the header I have: Allow: GET, PUT, DELETE, HEAD, OPTIONS Anyone have any ideas? -
Django REST Framework - Saving phone with country prefix to database
Using my creating user endpoint, I want to take 'phone' value from request, and add it with country calling code before. Request data provides me country code, which is foreign key to Country model. Example request body: { ... 'phone':'000111222', 'country':'616', } In this case, '616' is Poland country code. I do following to implement all my logic in my UserViewSet create() method: class UserViewSet(ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() def create(self, request, format=None): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): # collecting country country_code = request.data['country'] country = Country.objects.get(code=country_code) # setting dial code before phone dial_code = country.calling_code #'48' phone = dial_code + request.data['phone'] #'48000111222' # checking if final phone number already exists in database if User.objects.filter(phone=phone).exists(): return Response({'phone': 'Phone number already exists.'}, status=status.HTTP_400_BAD_REQUEST) serializer.save(country=country, phone=phone) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Code works for now, but I have few issues. UserSerializer actually validate my fields before my create function does. It use raw phone value to validate uniqueness in database - in this case 000111222 instead of 48000111222, what can cause an unwanted error. My solution seems a bit too complicated for me, could any of the built-in functionalities help? If not, would it be a good idea to … -
Django framework, crud in grid row
I’ve been developing an app in djanog 3.0 for my wife. Got a nice modal ajax crud up and running for the grid, but she does not like the modal effect, she just wants to edit inside the row and always have an empty row at the bottom for new entries. I’ve looked at table2 and jqgrid but have not been able to find something that works like that. I’ve now been playing around with editablegrid.net js grid and I can display data and edit, but not save the edited data. Editablegrid is a good example of what my wife would like to do, without the empty new row, but should be able to hack that in. Obviously I’ll not be able to make a row a from, so I need to figure out how to make my data serial in something like json. I then also need the CSRF token as part of the json right? I’m way out of my depth as I develop embedded c for a living and this all is self taught as we go. Questions are: What is the best grid for something like this? Is it even possible? Is django even suited for … -
How can I implement this in? I want a employeee to enter a code that connect to the employer table on registration?
I want to create a company and employee relationship. So there going to be two table. The company won't be adding the employee to their list. A employee, on register will enter a company code(like the company primary key) on the form and it will link to the company. I am using django, postgresql -
Django load an imageField in a template
Essentially what I'm trying to do is load the thumbnail image from my Post model in my template. models.py class Post(models.Model): objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') thumbnail = models.ImageField(name="photo", upload_to='thumbnails/', null=True, default='default.png') class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) views.py class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 3 template_name = 'blog/post/list.html' def get_context_data(self, **kwargs): obj = Settings.objects.get(pk=1) context = super().get_context_data(**kwargs) context["blog_name"] = getattr(obj, "blog_name") context["footer"] = getattr(obj, "footer") context["description"] = getattr(obj, "description") context["keywords"] = getattr(obj, "keywords") return context I added <img src="{{post.thumbnail.url}}" alt="{{ post.title }}"> to my template to try and load the image but no luck. I can access the image if I load the path manually and i already added MEDIA_URL and MEDIA_ROOT to my settings.py If this question can be improved please let me know as I am knew to django. -
I try to add data from Admin pannel but it fails Django
I try to add data as admin. I go to the url /admin/festival/festival/add and it shows me the form.I complete it, but when i click on save it shows me the IntegrityError, saying that Foreign Key constraint failed. But i have no foreign key in the model. How can i fix this? IntegrityError at /admin/festival/festival/add/ FOREIGN KEY constraint failed Request Method: POST Request URL: http://127.0.0.1:8000/admin/festival/festival/add/ Django Version: 3.0.4 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed Exception Location: /home/anamaria/workspace/AllFest2/venv/lib/python3.6/site-packages/django/db/backends/base/base.py in _commit, line 243 Python Executable: /home/anamaria/workspace/AllFest2/venv/bin/python Python Version: 3.6.9 Python Path: ['/home/anamaria/workspace/AllFest2/festivals', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/anamaria/workspace/AllFest2/venv/lib/python3.6/site-packages'] here is the models.py: from django.db import models from jsonfield import JSONField class Festival(models.Model): name = models.CharField(max_length=100) start_date = models.DateTimeField(blank=True, null=True, default=None) end_date = models.DateTimeField(blank=True, null=True, default=None) number_of_tickets = models.IntegerField() location = JSONField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name in views.py i have: from .serializers import FestivalSerializer from .permissions import FestivalPermission from rest_framework import mixins, status from festival.models import Festival from rest_framework.viewsets import GenericViewSet class FestivalViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin,GenericViewSet): serializer_class = FestivalSerializer permission_classes = [FestivalPermission] queryset = Festival.objects.all() serializer in serializers.py: from rest_framework import serializers from festival.models import Festival class FestivalSerializer(serializers.BaseSerializer): class Meta: model = Festival fields = '__all__' … -
how to save a model that contains self-referential ForeignKey from form
I'm new in django ... I have a model with a self-referential field and i want to get this model from a form. but this self-referential have no value! what should i do?! models.py class agents(models.Model): name = models.CharField(max_length=100) address = models.TextField(blank=True, null=True) phone = models.CharField(max_length=20) is_producer = models.BooleanField(default=False) serial = models.TextField(default='') users = models.ManyToManyField(user_models.users, through='user_agent') def __str__(self): return self.name def get_absolute_url(self): return reverse('agent_detail', args=[str(self.id)]) class user_agent(models.Model): user = models.ForeignKey(user_models.users, on_delete=models.CASCADE) agent = models.ForeignKey(agents, on_delete=models.CASCADE) parent = models.ForeignKey("self", on_delete=models.CASCADE) forms.py class AgentSignUpForm(forms.ModelForm): class Meta: model = models.agents fields = ('name', 'address', 'phone', 'is_producer', 'serial', 'users', ) views.py @login_required def agent_register(request): if request.method == 'POST': form = forms.AgentSignUpForm(request.POST) if form.is_valid(): agent = form.save(commit=False) agent.save() form.save_m2m() return redirect('agent_list') else: form = forms.AgentSignUpForm() return render(request, 'agent/signup.html', {'form': form})