ReactJS & django-forms

I have a model in the django backend with validators, select fields, etc. I would like to convey it in order to respond and display it. First, is it possible? I would like to get it completely using validators, but just the html is still great. The reason of that:

  • Avoid double permanent ads on the front and back. For example, select options: "man", "woman", "???" must be on the backend for validation and validation for display and validation.
  • Building the full html in the interface for the form again, despite the fact that all this can also be easily created by django. The main problem is again selecting options with many different custom values.

There is a package called drf-braces that has a FormSerializer, but it seems to have a problem, I constantly get the error 500 "is not a JSON serializable error," for example:

name_or_event = CharFormSerializerField(error_messages={u'required': <django.utils.functional.__proxy__ object>}, help_text='', initial=None, label='Name', required=True, validators=[]) is not JSON serializable 

This is a drf-based serializer, as shown in the drf-braces serialization example:

 from drf_braces.serializers.form_serializer import FormSerializer from myapp.forms import SignupDataForm class MySerializer(FormSerializer): class Meta(object): form = SignupDataForm 

and a rest-auth RegisterView - based API view:

 from myapp.serializers import MySerializer class TestView(RegisterView): permission_classes = (AllowAny,) allowed_methods = ('GET', ) serializer_class = MySerializer def get(self, *args, **kwargs): serializer = self.serializer_class() return Response({'serializer': serializer}, status=status.HTTP_200_OK) 

If I open the url assigned by TestView in the browser, I will see the form fields. But when loading ajax from the reaction, I get 500 with a "not JSON serializable error" above. The call is made from the React.component constructor, as shown below. I am not saying that he displayed the field correctly while I tried to print the answer to the console and see what error it was giving, but it does not get to this:

 loadUserDetail() { this.serverRequest = $.get("myUrl", function (result) { console.log(result); this.setState({ username: result.name_or_event, email: result.email }); }.bind(this)); } 

Any other ideas how to do this? I completely disagree with my approach, right ?:-)

+5
source share
2 answers

In my opinion, mixing the forms created by the django and React will be messy. A cleaner approach would be to let React handle the third-party and use Django to simply open the JSON api. It is not possible to display the server side of the form, and then allow React to "pick up" if you are not using Nodejs and React on the server either (React supports server-side rendering).

The problem with your Python code is that DRF serializers must read the input sent to the server and serialize the data you want to send in response. ModelSerializer knows how to json-encode a Django model in the code that you are trying to JSON encode a serializer object that does not work, since there is no magic way to turn this object into json.

I understand that you do not want to duplicate the definitions and parameters of your form, but you can just say that you need to change the options / options that you need to use in the form. You can usually achieve this by rendering the script tag in a template, where you pass any source data as JSON, and you read it from the Js side.

 class TestView(RegisterView): permission_classes = (AllowAny,) allowed_methods = ('GET', ) def get(self, *args, **kwargs): initial_data = {'gender_options': [...]} # anything you need to render the form, must be json-serialisable. return Response({'initial_data': json.dumps(initial_data)}, status=status.HTTP_200_OK) 

Then in the Django template that you render (before loading the js application files):

 <script>var INITIAL_DATA = {{ initial_data|escapejs }};</script> 

Be careful with escapejs , this could be a security issue if you are not sure that initial_data contains only trusted data.

Then at this point you have INITIAL_DATA available around the world for your js code, so you can base your React components on this.

You can use Django form definitions for server side validation.

+6
source

Thanks to Fabio, I now see how my approach cannot work :-) Not sure if I take this advice, but it seems likely.

Note. I have server side rendering.

Note2: a complete newbie for reacting and serializing and django-rest-framework

What I originally tried to achieve was the solution to this part of my reactive jsx files:

 import React from 'react'; import {Router, Route, Link} from 'react-router'; class GenderField extends React.Component { render() { return ( <div className="form-group"> <label htmlFor="gender">Gender</label> <input type="text" className="form-control" id="gender" placeholder="Gender" ref="gender"/> </div> ) } } export default GenderField; 

Everything contained in the render can be created from the django backend and actually is. Why record it again? Isn't there a way to use ajax and get it from the back? I think this probably contradicts the philosophy of reacting to receiving static content from the server again and again ...

But, wider. I am looking for a way to do this from the developer's point of view, only once before deployment: the server generates html and populates the jsx files with it and goes on to production or something like that. As a django application ... This is also impossible, is still the wrong way to think about it?

0
source

Source: https://habr.com/ru/post/1258010/


All Articles