将数据发送到网址-

时间:2020-06-29 00:24:13

标签: python html django django-views django-templates

这是我的html模板

const Parent = () => {
  const [value1, setValue1] = useState('')
  const [value2, setValue2] = useState('')
  const [value3, setValue3] = useState('') 


  const [editMode, setEditMode] = useState(false)

  return (
    <div>
      <ChildCustomInput value={value1} updateValue={setValue1} editMode={editMode} updateEditMode={setEditMode} />
      <ChildCustomInput value={value2} updateValue={setValue2} editMode={editMode} updateEditMode={setEditMode}/>
      <ChildCustomInput value={value3} updateValue={setValue3} editMode={editMode} updateEditMode={setEditMode}/>
    </div>
  )
}


const ChildCustomInput = (props)=> {
  // ref to update the input's value in the parent
  const textInputEl = useRef(null)

  // method to update the parent's values
  const updateComponentValue = () => {
    props.updateValue(textInputEl.current.value)
    props.updateEditMode(!props.editMode)
  }

  // Toggle Edit mode
  const changeEditMode = () => {
    props.updateEditMode(!props.editMode)
  }

  const renderEditView = () => {
    return (
      <div>
        <input ref={textInputEl}></input>
        <button onClick={updateComponentValue}>
          OK
        </button>
      </div>  
    )
  }


  const renderDefaultView = () => {
    return (
      <div>
        <div>
          {props.value}
        </div>

        <button onClick={changeEditMode}>
          EDIT
        </button>
      </div>
    )
  }


  return (
    <div>
    {
      props.editMode 
        ? renderEditView() 
        : renderDefaultView()
     }
    </div>
 )
} 



export default Parent;

如您所见,当按下按钮时,用户被重定向到消息URL。我有一个单独的消息视图来处理此URL。我想从该模板发送数据。单击该按钮时,我要发送i.user.first_name值,以便可以在消息视图中访问它。

1 个答案:

答案 0 :(得分:1)

您可以看到这样的视图。

urls.py

path('message/<str:first_name>', my_view, name='messages')

views.py

def my_view(request, fist_name):
    ... process  stuff here ...

html template

<button>
    <a href="{% url 'messages'  i.user.first_name %}">Send a message</a>
</button>

有关Django文档,请参见here