0

I want to save data from a html form rather than from modelForm in django. I am using MySQL database.

create.html

<form action="QACreate/qa_create/" method="post" id="createform">
{% csrf_token  %}

<label>Topic :</label>
<input type="text" name="topic"/><br /><br />

<label>Description :</label>
<textarea name="decsription"> </textarea>  <br /><br />

<label>Topic type :</label>
<select>
    <option value="Descriptive"> Descriptive</option>
    <option value="Objective">Objective</option>
</select> <br /><br />

<label>Question :</label>
<textarea name="question"> </textarea><br /><br />

<label>Answer :</label>
<textarea name="answer"> </textarea><br /><br />

<a href="#">Add another question</a><br/><br />

<label>Tags :</label>
<input type="text" name="tags"/><br /><br />

<input type="submit" value="Submit" name="submit" />
<input type="reset"  value="Reset" name="reset"/>

</form>

my topic and question are in different models.

How do i make changes in view file. Pls help Thanks in advance.

4

2 回答 2

0

您应该创建一个处理 POST 数据的视图,对其进行验证并(可选)创建新的模型对象。

快速示例:

def qa_create(request):
    if request.method == 'POST':
        # process the form
        data = request.POST
        topic = data.get('topic')
        #... rest of the form fields

        #Assuiming you have model specified, lets name it QA_Model
        #remember to assign rest of the fields
        qa_object = QA_Model(topic=topic).save()

        #Object has been saved to database

    else:
        # display template with HTML code
于 2013-06-18T07:12:46.387 回答
0

在您的视图中获取提交的数据Post并保存在模型中:

def myView(request):
    if request.method == 'POST':
        question = request.POST.get('question')
        answer = request.POST.get('answer')
        # some other fields
        # do validation
        # if everything ok save in model
        MyModel.objects.create(question=question, answer=answer, )

但我强烈建议您使用 Djangoforms.Formforms.ModelForm.

于 2013-06-18T07:12:55.467 回答