Django-Rest-Framework

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

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

{% 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>

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?

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?

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 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 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.

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

‘str’ object has no attribute ‘get’’

{% 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>

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.

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.

I think you should create a template tag, 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.

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

{% 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>

Which issues?
Are the errors not being displayed?

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

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

Can you post your complete serializer and view here?

Serializer.py***

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

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})