Django invalid form when using modelchoicefield -
i new django , have been struggling selected value of forms.modelchoicefield
in views. form (post) not valid , noticed request.post returns possible values in modelchoicefield. how model selected user? thank in advance help.
model
i have sensor model measurements model...
class sensor(models.model): # contains information sensor, type, location, , other type = models.charfield(max_length=16) ... class measurement(models.model): #this contains measurements of sensors @ given date sensor = models.foreignkey('sensor') date = models.datefield() temperature = models.floatfield() pressure = models.floatfield() ... class meta: unique_together = ('sensor', 'date')
form
... , form allows user choose sensor , date:
class measurementform(forms.modelform): #the user allowed choose sensor related measurement table sensor = forms.modelchoicefield(queryset=sensor.objects.exclude(measurement=none)) date = forms.datefield(widget=dateinput(attrs={'format':'%y-%m-%d'}), initial=datetime.today)
so far good, gets rendered method , user able select both sensor , date. however, following view fails @ post, after submitting:
views
class measurementview(view): form_class = measurementform my_template = "measurement.html" def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.my_template, {'form': form, 'data':none}) def post(self, request, *args, **kwargs): print(request.post) print(new_form.errors) new_form = self.form_class(data=request.post) if new_form.is_valid(): print('form valid') data = get_data_for_sensor_date( new_form.cleaned_data['sensor'], new_form.cleaned_data['date'])) return render(request, self.my_template, {'form':new_form, 'data':data}) else: return render(request, self.my_template, {'form':new_form, 'data':none})
console output
<querydict: {'sensor': ['', '1'], 'csrfmiddlewaretoken': ['yupfrdhdbqdaa7eynx2sjehdbxmqxttw'], 'date': ['2016-11-07']}> <ul class="errorlist"> <li>__all__ <ul class="errorlist nonfield"> <li>measurement sensor , date exists. </li> </ul> </li> </ul>
i found link django formview returns object exists error modelform
to quote: "ok. found solution error. caused model exists error modelform checkproductform. codename attribute unique, validation returned false. did change orginal modelform form. solved whole issue. , form_invalid in form_valid issue. i've overwritten form's clean_codename function raise validationerror if product doesnt exist."
i still not understand why had error in first place. however, changing form code below made trick.
form
class measurementform(forms.form): #the user allowed choose sensor related measurement table sensor = forms.modelchoicefield(queryset=sensor.objects.exclude(measurement=none)) date = forms.datefield(widget=dateinput(attrs={'format':'%y-%m-%d'}), initial=datetime.today)
Comments
Post a Comment