Home > Software design >  Prepopulate Django ModelForm With all records
Prepopulate Django ModelForm With all records

Time:01-20

I am trying to prepopulate my form with all records but i am receiving error 'QuerySet' object has no attribute '_meta' , I tried just passing my queryset through initial while i get no error the fields in my template aren't rendering initial={runninghours}

my views.py:

def runninghours(request):
    runninghours = RunningHours.objects.all()
    form = RunningHoursModelForm()
    form_populated =  RunningHoursModelForm(initial={runninghours})
    if request.method == 'POST' and 'form-create' in request.POST:
        form = RunningHoursModelForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect(request.path_info)
    context = {"form": form,
               "rhs": form_populated}
    return render(request, 'runninghours.html', context)

The template:

<form method="POST" action="">
                        {% csrf_token %}
                       <td>{% render_field rhs.name  %}</td>
                       <td>{% render_field rhs.current_runninghours %}</td>
                       <td>{% render_field rhs.last_runninghours %}</td>
                       <td>{% render_field rhs.last_modified %}</td>
                       <td> <input type="hidden" name="update_runninghours_id" value="{{ rhs.pk }}" />
                        <input name="form-delete" type="submit"  value='Update Runninghours' /></td>
                    </form>

the models.py:

class RunningHours(models.Model):
    name = models.CharField(max_length=100)
    current_runninghours = models.IntegerField(blank=True,null=True)
    last_runninghours = models.IntegerField(blank=True,null=True,default=0)
    last_modified = models.DateField(("Date"), default=datetime.date.today)

forms.py:

class RunningHoursModelForm(forms.ModelForm):
        model = RunningHours
        fields = ("name",
                  "current_runninghours",
                  "last_runninghours",)

CodePudding user response:

I don't think you can pass a queryset, runninghours by using initial. That takes a dictionary as argument. What you might be able to do is use the queryset in making the form.

# forms.py

class RunningHoursModelForm(ModelForm):

    def __init__(self,company,*args,**kwargs):
        super (RunningHoursModelForm,self ).__init__(*args,**kwargs)
        self.fields['the_field_you_want'].queryset = RunningHours.objects.all()

    class Meta:
        model = RunningHours

If you want to populate the form with an instance of RunningHours, you can just do

    particularRunningHours = RunningHours.objects.get(name=name)
    form_populated =  RunningHoursModelForm(initial={
        'current_runninghours': particularRunningHours.current_runninghours,
        ...
        })
  •  Tags:  
  • Related