# Django-Rest-Framework

**URL:** <https://forum.djangoproject.com/t/django-rest-framework/19322>\
**Category:** Forms & APIs\
**Created:** [March 7, 2023, 8:50am UTC](https://forum.djangoproject.com/t/django-rest-framework/19322 "2023-03-07T08:50:08Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mihirpatel535](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mihirpatel535/32/9366_2.png) [@Mihirpatel535](https://forum.djangoproject.com/u/Mihirpatel535)\
**Post date:** [March 7, 2023, 8:50am UTC](https://forum.djangoproject.com/t/django-rest-framework/19322/1 "2023-03-07T08:50:08Z")

</div>

How To Render Blank Form In HTML using Django Rest Framework, I followed As Shown In Original Documentation on DRF Website But I Am Unable To Render Blank Form Using Get Method By APIview

**Here Is My Apiview**

```auto
class signup(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'usersignup.html'

    def get(self,request):
        
        serializer = jobglobeluser_serializer(request)
        return Response({'form': serializer})

```

_ **Here Is My Html Form** _

```auto
{% load rest_framework %}
{% load static %}

<div class="div5">
        <form class="form1" action="" method="POST" novalidate enctype="multipart/formdata">{% csrf_token %}
            
            {% render_form form %}
            <div class="formdiv14"><button type="submit" class="subbtn1">SUBMIT</button></div>
        </form>
    </div>

```

---

<div class="post-metadata">

**Author:** ![leandrodesouzadev](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/leandrodesouzadev/32/8981_2.png) [@leandrodesouzadev](https://forum.djangoproject.com/u/leandrodesouzadev)\
**Post date:** [March 7, 2023, 10:12am UTC](https://forum.djangoproject.com/t/django-rest-framework/19322/2 "2023-03-07T10:12:43Z")

</div>

Are you receiving any errors or warnings on the console? If so, post the errors and traceback.  
Are anything being rendered on the screen, or you’re seeing a blank page?

---

<div class="post-metadata">

**Author:** ![Mihirpatel535](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mihirpatel535/32/9366_2.png) [@Mihirpatel535](https://forum.djangoproject.com/u/Mihirpatel535)\
**Post date:** [March 7, 2023, 10:14am UTC](https://forum.djangoproject.com/t/django-rest-framework/19322/3 "2023-03-07T10:14:47Z")

</div>

problem is solved but i am having issues with rendering form, do you have any idea How to render form fields manually with thier respective labels and errors in django rest framework?

---

<div class="post-metadata">

**Author:** ![leandrodesouzadev](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/leandrodesouzadev/32/8981_2.png) [@leandrodesouzadev](https://forum.djangoproject.com/u/leandrodesouzadev)\
**Post date:** [March 7, 2023, 10:39am UTC](https://forum.djangoproject.com/t/django-rest-framework/19322/4 "2023-03-07T10:39:55Z")

</div>

This is not a documented feature i believe.  
I was digging into the source code, and basically if you want to override this feature of rendering the form, there’s two main things you need to look at:

- The [render\_form](https://github.com/encode/django-rest-framework/blob/master/rest_framework/templatetags/rest_framework.py#L78) template tag. This template tag is what you’re using on the template. Note that it’s using a class to render the serializer into a form;
- The [HTMLFormRenderer](https://github.com/encode/django-rest-framework/blob/master/rest_framework/renderers.py#L238) class is what defines how the serializer is turn into a form.

Note that on the `render_form` template\_tag the class is hardcoded there, so you probably going to need to create your own template tag to reference a different class of HTMLFormRenderer. Then you can create your own HTMLFormRenderer child class to handle this as you want.

---

<div class="post-metadata">

**Author:** ![Mihirpatel535](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mihirpatel535/32/9366_2.png) [@Mihirpatel535](https://forum.djangoproject.com/u/Mihirpatel535)\
**Post date:** [March 7, 2023, 11:54am UTC](https://forum.djangoproject.com/t/django-rest-framework/19322/5 "2023-03-07T11:54:58Z")

</div>

I tried this way but it is throwing an error that ’ AttributeError at /

‘str’ object has no attribute ‘get’’

```auto
{% load rest_framework %}
{% load static %}
<div class="div5">
        <form class="form1" action="" method="POST" novalidate ">{% csrf_token %}
            
            {% render_field form.useris style=style %}
            
            <div class="formdiv14"><button type="submit" class="subbtn1">SUBMIT</button></div>
        </form>
    </div>

```

---

<div class="post-metadata">

**Author:** ![leandrodesouzadev](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/leandrodesouzadev/32/8981_2.png) [@leandrodesouzadev](https://forum.djangoproject.com/u/leandrodesouzadev)\
**Post date:** [March 7, 2023, 11:59am UTC](https://forum.djangoproject.com/t/django-rest-framework/19322/6 "2023-03-07T11:59:23Z")

</div>

Have you read carefully and understand my previous response?  
Also, you’re going under narrow corners here, this is not a documented feature as i said. You’re going to need to tweak, change, try a different things and expect errors.  
I never done this myself, i’m trying to point you to the right direction, but now onwards it’s going to be trial and error.

---

<div class="post-metadata">

**Author:** ![Mihirpatel535](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mihirpatel535/32/9366_2.png) [@Mihirpatel535](https://forum.djangoproject.com/u/Mihirpatel535)\
**Post date:** [March 7, 2023, 12:03pm UTC](https://forum.djangoproject.com/t/django-rest-framework/19322/7 "2023-03-07T12:03:52Z")

</div>

So Do You Have Any Idea what Should i do ? bcz what i want to do actually i want to use common serializer for both mobile app and web app.

---

<div class="post-metadata">

**Author:** ![leandrodesouzadev](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/leandrodesouzadev/32/8981_2.png) [@leandrodesouzadev](https://forum.djangoproject.com/u/leandrodesouzadev)\
**Post date:** [March 7, 2023, 12:08pm UTC](https://forum.djangoproject.com/t/django-rest-framework/19322/8 "2023-03-07T12:08:25Z")

</div>

I think you should [create a template tag](https://docs.djangoproject.com/en/4.1/howto/custom-template-tags/), similar to the `render_form` tag from rest\_framework. The reference source code could be good as a starting point. After that, you want to create your own `HTMLFormRenderer` class that will do that custom.

---

<div class="post-metadata">

**Author:** ![Mihirpatel535](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mihirpatel535/32/9366_2.png) [@Mihirpatel535](https://forum.djangoproject.com/u/Mihirpatel535)\
**Post date:** [March 7, 2023, 12:11pm UTC](https://forum.djangoproject.com/t/django-rest-framework/19322/9 "2023-03-07T12:11:33Z")

</div>

By This way I am able to render entire form but i am having issues with serializer errors, bcz there are lot of fields there in my serializer which are dependant on each other

```auto
{% load rest_framework %}

<html><body>

<h1>Profile - {{ profile.name }}</h1>

<form action="{% url 'profile-detail' pk=profile.pk %}" method="POST">
    {% csrf_token %}
    {% render_form serializer %}
    <input type="submit" value="Save">
</form>

</body></html>

```

---

<div class="post-metadata">

**Author:** ![leandrodesouzadev](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/leandrodesouzadev/32/8981_2.png) [@leandrodesouzadev](https://forum.djangoproject.com/u/leandrodesouzadev)\
**Post date:** [March 7, 2023, 12:13pm UTC](https://forum.djangoproject.com/t/django-rest-framework/19322/10 "2023-03-07T12:13:25Z")

</div>

Which issues?  
Are the errors not being displayed?

---

<div class="post-metadata">

**Author:** ![Mihirpatel535](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mihirpatel535/32/9366_2.png) [@Mihirpatel535](https://forum.djangoproject.com/u/Mihirpatel535)\
**Post date:** [March 7, 2023, 12:14pm UTC](https://forum.djangoproject.com/t/django-rest-framework/19322/11 "2023-03-07T12:14:38Z")

</div>

I am trying this way to handle form errors but non of any error being display by this way

```auto
def validate(self, data):
        valctn = 'Select'
        email_exists = jobglobeluser.objects.filter(email=email)
        mobile_exists = jobglobeluser.objects.filter(mobile=mobile)

        useris = data.get('useris')
        sector_type = data.get('sector_type')
        FirstName = data.get('FirstName')
        LastName = data.get('LastName')
        email = data.get('email')
        mobile = data.get('mobile')
        country = data.get('country')
        state = data.get('state')
        city = data.get('city')
        password = data.get('password')
        password2 = data.get('password2')

        if useris == valctn:
            raise serializers.ValidationError(
                {'useris': 'Select Jobseeker Or Recruiter'})
        if useris == 'Recruiter':
            if sector_type == 'Select Sector Type':
                raise serializers.ValidationError(
                    {"sector_type": 'Select Sector Type'})
        if len(FirstName) < 3:
            raise serializers.ValidationError(
                {'FirstName': 'Name Is Too Short'})
        if LastName == FirstName:
            raise serializers.ValidationError(
                {'LastName': "First & Last Name Should'nt Be Same"})
        if email_exists:
            raise serializers.ValidationError(
                {'email': 'User Already Registered : Try To Reset Password'})
        if len(mobile) < 8:
            raise serializers.ValidationError({'mobile': 'Mobile Too Short'})
        if len(mobile) > 13:
            raise serializers.ValidationError({'mobile': 'Mobile Too Long'})
        if mobile_exists:
            raise serializers.ValidationError(
                {'mobile': 'Mobile Already Registered : Enter Another One'})
        if len(password) < 8:
            raise serializers.ValidationError(
                {'password': 'Password Must Contain 8 Characters'})
        if password2 != password:
            raise serializers.ValidationError(
                {'password2': 'Password Does Not Match'})
        if country == valctn:
            raise serializers.ValidationError({'country': 'Select Country'})
        if state == valctn:
            raise serializers.ValidationError({'state': 'Select State'})
        if city == valctn:
            raise serializers.ValidationError({'city': 'Select City'})
        return data

```

---

<div class="post-metadata">

**Author:** ![leandrodesouzadev](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/leandrodesouzadev/32/8981_2.png) [@leandrodesouzadev](https://forum.djangoproject.com/u/leandrodesouzadev)\
**Post date:** [March 7, 2023, 12:34pm UTC](https://forum.djangoproject.com/t/django-rest-framework/19322/12 "2023-03-07T12:34:19Z")

</div>

Can you post your complete serializer and view here?

---

<div class="post-metadata">

**Author:** ![Mihirpatel535](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mihirpatel535/32/9366_2.png) [@Mihirpatel535](https://forum.djangoproject.com/u/Mihirpatel535)\
**Post date:** [March 7, 2023, 12:44pm UTC](https://forum.djangoproject.com/t/django-rest-framework/19322/13 "2023-03-07T12:44:33Z")

</div>

_ **Serializer.py** _\*\*\*

```auto
class jobglobeluser_serializer(serializers.ModelSerializer):
    class Meta:
        model = jobglobeluser
        fields = ' __all__'

    useris = serializers.ChoiceField(label='I Am:',
                                   choices=USER_TYPE_CHOICES,
                                   style={'class': 'useris'},
                                   help_text='Choose Jobseeker Or Recruiter')
    sector_type = serializers.ChoiceField(label='Sector Type',
                                          required=False,
                                          choices=SECTOR_TYPE,
                                          style={'class': 'sector_type1'})
    FirstName = serializers.CharField(
        error_messages={'required': 'First Name Required'},
        label='First Name',
        style={
            'placeholder': 'Your First Name',
            'class': 'input1'
        })
    LastName = serializers.CharField(
        error_messages={'required': 'Last Name Required'},
        label='Last Name',
        style={
            'placeholder': 'Your Last Name',
            'class': 'input2'
        })
    email = serializers.EmailField(error_messages={'required': 'Email Id Required'},
                                   label='Email Id',
                                   style={
        'placeholder': 'Your Email ID',
        'class': 'input3'
    })
    code = serializers.CharField(
        
        initial='(+3455)',
        label='Code',
        style={'class': 'countrycode'})
    mobile = serializers.CharField(
        error_messages={'required': 'Mobile Number Required'},
        label='Mobile',
        style={
            'placeholder': 'Your Mobile Number',
            'class': 'input4'
        })
    country = serializers.ChoiceField(label='Country',
                                      choices=COUNTRY,
                                      style={'class': 'select'},
                                      help_text='Choose Country First')
    state = serializers.ChoiceField(label='State',
                                    choices=STATES,
                                    style={'class': 'select2'})
    city = serializers.ChoiceField(label='City',
                                   choices=CITY,
                                   style={'class': 'select3'})
    Gender = serializers.ChoiceField(error_messages={'required': 'Select Gender'},
                                     label='Gender :- ',
                                     choices=CHOICES, style={'class': 'radio1'})
    password = serializers.CharField(
        error_messages={'required': 'Choose Password'},
        label='Password',
        style={
            'placeholder': 'Choose Password',
            'class': 'input5',
            'input_type': 'password'
        })
    password2 = serializers.CharField(
        label='Reenter Password',
        style={
            'placeholder': 'Choose Same Password Again',
            'class': 'input6',
            'input_type': 'password'
        })

    def validate(self, data):
        valctn = 'Select'
        email_exists = jobglobeluser.objects.filter(email=email)
        mobile_exists = jobglobeluser.objects.filter(mobile=mobile)

        useris = data.get('useris')
        sector_type = data.get('sector_type')
        FirstName = data.get('FirstName')
        LastName = data.get('LastName')
        email = data.get('email')
        mobile = data.get('mobile')
        country = data.get('country')
        state = data.get('state')
        city = data.get('city')
        password = data.get('password')
        password2 = data.get('password2')

        if useris == valctn:
            raise serializers.ValidationError(
                {'useris': 'Select Jobseeker Or Recruiter'})
        if useris == 'Recruiter':
            if sector_type == 'Select Sector Type':
                raise serializers.ValidationError(
                    {"sector_type": 'Select Sector Type'})
        if len(FirstName) < 3:
            raise serializers.ValidationError(
                {'FirstName': 'Name Is Too Short'})
        if LastName == FirstName:
            raise serializers.ValidationError(
                {'LastName': "First & Last Name Should'nt Be Same"})
        if email_exists:
            raise serializers.ValidationError(
                {'email': 'User Already Registered : Try To Reset Password'})
        if len(mobile) < 8:
            raise serializers.ValidationError({'mobile': 'Mobile Too Short'})
        if len(mobile) > 13:
            raise serializers.ValidationError({'mobile': 'Mobile Too Long'})
        if mobile_exists:
            raise serializers.ValidationError(
                {'mobile': 'Mobile Already Registered : Enter Another One'})
        if len(password) < 8:
            raise serializers.ValidationError(
                {'password': 'Password Must Contain 8 Characters'})
        if password2 != password:
            raise serializers.ValidationError(
                {'password2': 'Password Does Not Match'})
        if country == valctn:
            raise serializers.ValidationError({'country': 'Select Country'})
        if state == valctn:
            raise serializers.ValidationError({'state': 'Select State'})
        if city == valctn:
            raise serializers.ValidationError({'city': 'Select City'})
        return data

```

\ ***View.py**

```auto
class signup(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'usersignup.html'
    style = {'template_pack':'rest_framework/vertical/'}

    def get(self,request):
        
        serializer = jobglobeluser_serializer()
        return Response({'form': serializer})

    def post(self, request):
        serializer = jobglobeluser_serializer(data=request.data)
        if not serializer.is_valid():
            return Response({'form': serializer})
        serializer.save()
        return Response({'form': serializer})

```
