Django:modelformset不反映初始数据

时间:2019-01-02 13:53:56

标签: django django-models django-forms

我正在尝试创建一个表格来编辑已保存多个编号的用户的技能。技能。渲染模板后,输入字段为空,但没有。按查询集创建的表单的格式正确。

forms.py

class skillform(forms.ModelForm):
    name = forms.CharField(label='Skill',widget=forms.TextInput(attrs={'class': 'form-control',}))
    level = forms.ChoiceField(choices=(('Novice','Novice'),('Beginner','Beginner'),('Skillful','Skillful'),('Experienced','Experienced'),('Expert','Expert')),label="level",initial='Skillful',widget=forms.Select(),required=False)
    class Meta:
        model = userskills_model
        fields = ('name','level')
skillformset =  modelformset_factory(userskills_model, form = skillform, extra=0, can_delete=False)

models.py

class userskills_model(models.Model):
    userid = models.ForeignKey(user_model, on_delete=models.PROTECT)
    skills =models.CharField(max_length=264,unique=False,blank=False,null=False)
    skills_level = models.CharField(max_length=264,unique=False,blank=False,null=False)
    def __str__(self):
        return str(self.userid)

views.py

def skillview(request):
    qset=userskills_model.objects.filter( userid=user_model.objects.get(userid=userid))
    skillformset(queryset = qset)
    if request.method == 'GET':
        formset = skillformset(request.GET or None)
    elif request.method == 'POST':
        formset = skillformset(request.POST)
        #validating and saving
    return render(request, template_name, {
    'formset': formset,
})

template / skills.html

{% extends 'app/base.html' %}
{% load staticfiles%}
{% block head %}
<link href="{% static "/css/skills.css" %}" rel="stylesheet" 
type="text/css"/>
{% endblock %}
{% block content %}
<div class="heading_text">SKILLS</div>
<form class="form-horizontal" method="POST" action="">
    {% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
<div class="row form-row spacer">
    <div class="col-5">
        <label>{{form.name.label}}</label>
        <div class="input-group">
            {{form.name}}
            </div>


    </div>
    <div class="col-5">
        <label>{{form.level.label}}</label>
        <div class="input-group">
            {{form.level}}
            <!-- <div class="input-group-append">
                <button class="btn btn-success add-form-row">+</button>
            </div> -->
        </div>
    </div>
    <div class="input-group-append">
        <button class="btn btn-success add-form-row">+</button>
    </div>
</div>

{% endfor %}
<div class="row spacer">
    <div class="col-3 button1">
        <button type="submit" class="btn3">Save and Continue</button>
    </div>
</div>
</form>


{% endblock %}
{% block custom_js %}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script type="text/javascript">
     function updateElementIndex(el, prefix, ndx) {
var id_regex = new RegExp('(' + prefix + '-\\d+)');
var replacement = prefix + '-' + ndx;
if ($(el).attr("for")) $(el).attr("for", 
$(el).attr("for").replace(id_regex, replacement));
if (el.id) el.id = el.id.replace(id_regex, replacement);
if (el.name) el.name = el.name.replace(id_regex, replacement);}
function cloneMore(selector, prefix) {
var newElement = $(selector).clone(true);
var total = $('#id_' + prefix + '-TOTAL_FORMS').val();
newElement.find(':input').each(function() {
    var name = $(this).attr('name')
    if(name) {
        name = name.replace('-' + (total-1) + '-', '-' + total + '-');
        var id = 'id_' + name;
        $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');}});
total++;
$('#id_' + prefix + '-TOTAL_FORMS').val(total);
$(selector).after(newElement);
var conditionRow = $('.form-row:not(:last)');
conditionRow.find('.btn.add-form-row')
.removeClass('btn-success').addClass('btn-danger')
.removeClass('add-form-row').addClass('remove-form-row')
.html('-');
return false;}
function deleteForm(prefix, btn) {
var total = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
if (total > 1){
    btn.closest('.form-row').remove();
    var forms = $('.form-row');
    $('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
    for (var i=0, formCount=forms.length; i<formCount; i++) {
        $(forms.get(i)).find(':input').each(function() {
            updateElementIndex(this, prefix, i);
        });
    }
}
return false;}
$(document).on('click', '.add-form-row', function(e){
e.preventDefault();
cloneMore('.form-row:last', 'form');
return false;});
 $(document).on('click', '.remove-form-row', function(e){
 e.preventDefault();
deleteForm('form', $(this));
return false;});
</script>
{% endblock %}

edit:添加了template / skills.html。我对此感到困惑,请在这里帮助我

2 个答案:

答案 0 :(得分:1)

您在skillform上声明的字段在userskills_model上不存在,因此不会填充任何内容。尝试将表单上的字段重命名为skillsskills_model,以便它们与您的模型匹配:

class skillform(forms.ModelForm):
    skills = forms.CharField(label='Skill',widget=forms.TextInput(attrs={'class': 'form-control',}))
    skills_level = forms.ChoiceField(choices=(('Novice','Novice'),('Beginner','Beginner'),('Skillful','Skillful'),('Experienced','Experienced'),('Expert','Expert')),label="level",initial='Skillful',widget=forms.Select(),required=False)
    class Meta:
        model = userskills_model
        fields = ('skills','skills_level')

并更新您的模板以引用form.skillsform.skills_level

...
{% for form in formset %}
<div class="row form-row spacer">
    <div class="col-5">
        <label>{{form.skills.label}}</label>
        <div class="input-group">
            {{form.skills}}
            </div>


    </div>
    <div class="col-5">
        <label>{{form.skills_level.label}}</label>
        <div class="input-group">
            {{form.skills_level}}
            ...

答案 1 :(得分:1)

我猜你的qset是空的,试试这个- qset = userskills_model.objects.filter(userid = self.request.user)#用于登录用户

对于更新案例- 用户= get_object_or_404(user_model,userid = userid) qset = userskills_model.objects.filter(userid = user)