programing

리액트와 함께 장고를 형성하다JS

cafebook 2023. 4. 3. 21:44
반응형

리액트와 함께 장고를 형성하다JS

저는 장고 템플릿을 사용하여 렌더링된 장고 양식을 가지고 있습니다.이제 양식 필드 중 하나(장기적으로는 둘 이상의 필드)에 React 구성 요소를 추가합니다.

지금까지 읽은 내용에 따르면, Django 템플릿과 React 렌더링을 혼합하지 않고 React에 JSON 데이터를 전송하는 백엔드 API로만 기능하도록 하는 것이 가장 좋은 방법인 것 같습니다.그래서 나는 지금 완전히 React를 통해 나의 양식을 다시 렌더링하려고 한다.

이제 forms.py 대신 serializers.py을 만들어 React로 전송할 데이터를 정의하고 환경에 Django Rest Framework를 설정했습니다.이제 이 데이터를 전송하는 방법을 알아보려고 합니다.Django/DRF와 React의 통합에 대해 설명하는 몇 가지 좋은 온라인 튜토리얼(및 SO 포스트)이 있지만 React와 DRF를 통해 엔드 투 엔드 폼 렌더링의 예를 찾을 수 없었습니다.구체적으로, 폼 데이터를 가져오려는 React의 GET 요청에 유용하게 사용할 수 있는 내 뷰에 실제로 무엇을 써야 하는지 알려주실 수 있나요?웹 참조 또는 필요한 광범위한 절차만 있으면 시작할 수 있습니다(그리고 문서를 더 자세히 볼 수 있습니다).

업데이트: 또한 serializers.py 코드의 간단한 버전을 여기에 추가합니다.

from .models import Entity
from rest_framework import serializers


class EntitySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Entity
        fields = ['name', 'role', 'location']
      

먼저 입력이 여러 개인 양식에 대한 관련 React 문서를 확인해야 합니다.리액트측에서 어떻게 구성되어야 하는지에 대한 기본적인 정보를 제공합니다.

서버로부터의 데이터 취득에 대해서는, 다음과 같은 조작을 실시할 수 있습니다.componentDidMount:

componentDidMount() {
    // Assuming you are using jQuery,
    // if not, try fetch().
    // Note that 2 is hardcoded, get your user id from 
    // URL or session or somewhere else.
    $.get('/api/profile/2/', (data) => {
        this.setState({
            formFields: data.fields // fields is an array
        });
    });
}

그런 다음 html 입력 요소를 생성할 수 있습니다.render다음과 같은 방법을 사용합니다.

render () {
    let fields = this.state.formFields.map((field) => {
        return (
            <input type="text" value={field.value} onChange={(newValue) => {/* update your  state here with new value */ }} name={field.name}/>
        )
    });
    return (
        <div className="container">
            <form action="">
                {fields}
                <button onClick={this.submitForm.bind(this)}>Save</button>
            </form>
        </div>
    )
}

그리고 여기 당신의submitForm방법:

submitForm() {
    $.post('/api/profile/2/', {/* put your updated fields' data here */}, (response) => {
       // check if things done successfully.
    });
}

업데이트:

여기 있습니다.untested-but-should-workDRF 뷰의 예:

from rest_framework.decorators import api_view
from django.http import JsonResponse
from rest_framework.views import APIView


class ProfileFormView(APIView):
    # Assume you have a model named UserProfile
    # And a serializer for that model named UserSerializer
    # This is the view to let users update their profile info.
    # Like E-Mail, Birth Date etc.

    def get_object(self, pk):
        try:
            return UserProfile.objects.get(pk=pk)
        except:
            return None

    # this method will be called when your request is GET
    # we will use this to fetch field names and values while creating our form on React side
    def get(self, request, pk, format=None):
        user = self.get_object(pk)
        if not user:
            return JsonResponse({'status': 0, 'message': 'User with this id not found'})

        # You have a serializer that you specified which fields should be available in fo
        serializer = UserSerializer(user)
        # And here we send it those fields to our react component as json
        # Check this json data on React side, parse it, render it as form.
        return JsonResponse(serializer.data, safe=False)

    # this method will be used when user try to update or save their profile
    # for POST requests.
    def post(self, request, pk, format=None):
        try:
            user = self.get_object(pk)
        except:
            return JsonResponse({'status': 0, 'message': 'User with this id not found'})

        e_mail = request.data.get("email", None)
        birth_date = request.data.get('birth_date', None)
        job = request.data.get('job', None)

        user.email = e_mail
        user.birth_date = birth_date
        user.job = job

        try:
            user.save()
            return JsonResponse({'status': 1, 'message': 'Your profile updated successfully!'})
        except:
            return JsonResponse({'status': 0, 'message': 'There was something wrong while updating your profile.'})

이 뷰와 관련된 URL은 다음과 같습니다.

urlpatterns = [
    url(r'^api/profile/(?P<pk>[0-9]+)/$', ProfileFormView.as_view()),
]

언급URL : https://stackoverflow.com/questions/42297614/django-forms-with-reactjs

반응형