user8681386 user8681386 - 3 years ago 217
HTML Question

ModelForm has no model class specified How can I connect model&form?

I got an error,ValueError at /accounts/upload_save/
ModelForm has no model class specified.
I wrote in forms.py

class UserImageForm(forms.ModelForm):
owner = forms.CharField(max_length=20)
image = forms.FileField()


in models.py

class ImageAndUser(models.Model):
user = models.ForeignKey("auth.User", verbose_name="imageforegin")
image = models.ImageField(upload_to='images', null=True, blank=True,)


in views.py

@csrf_exempt
def upload_save(request):
if request.method == "POST":
form = UserImageForm(request.POST, request.FILES)
if form.is_valid():
data = UserImageForm()
data.owner = forms.cleaned_data['user']
data.image = request.FILES['image']
data.save()
else:
print(form.errors)
else:
form = UserImageForm()

return render(request, 'registration/accounts/photo.html', {'form': form})


in index.html

<form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}

<div class="input-group">
<label class="input-group-btn">
<span class="btn btn-primary btn-lg">
<input type="file" style="display:none" name="files[]" multiple>
</span>
</label>
<input type="text" class="form-control" readonly="">
</div>

<div class="form-group">
<input type="hidden" value="{{ p_id }}" name="p_id" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="SEND" class="form-control">
</div>
</form>


When I put SEND button, upload_save method is read.And my ideal system is image& user's data put in ImageAndUser model.What is wrong in my codes?How can I connect model&form?

Answer Source
class UserImageForm(forms.ModelForm):
    owner = forms.CharField(max_length=20)
    image = forms.FileField()

that isn't the way to refer a model the correct way is :

class UserImageForm(forms.ModelForm):
    class Meta:
        model = ImageAndUser

and in the views:

form = UserImageForm(request.POST, request.FILES)
        if form.is_valid():
            data = form.save(commit=False)#or just save if you dont need modify anything
            data.owner = forms.cleaned_data['user']
            data.image = request.FILES['image']
            data.save()

for more information read this https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download