在 django 模型表单中保存图像失败且没有错误

Saving image fails without error in django model form

我想尝试将图像保存到我的模型中:

def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'user_{0}/{1}'.format(instance.user.id, filename)
class Leverandor(models.Model):
    ID = models.AutoField(primary_key=True)
    UserID = models.ForeignKey('Stamdata', on_delete=models.CASCADE)
    Name = models.CharField('Name', max_length=200)
    URL = models.URLField('URL', max_length=200)
    ImageURL = models.ImageField('ImageURL',blank=True, null=True, upload_to=user_directory_path)

对此Form.py:

class EditLeverandorForm(forms.ModelForm):
    Name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True}))
    URL = forms.URLField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True}))
    ImageURL = forms.ImageField
    class Meta:
        model = Leverandor
        labels = {
            'Name' : 'Leverandør',
            'URL' : 'Webside',
            'ImageURL' : 'Logo',
            }
        fields = ['UserID', 'Name', 'URL', 'ImageURL']

并对此 view.py

进行渲染

def add_leverandorer(request):
    user_id = request.user.id
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        print (user_id)
        form = EditLeverandorForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/backend/leverandorer')
                
    else:
        print ('somethin goes wrong')
        print (user_id)
        form = EditLeverandorForm()
    return render(
        request,
        'backend/add_leverandorer.html', 
        {
            'title':'WestcoastShop - Backend',
            'form':  form,
        }
    )

问题是,在我添加 instance=request.user 部分之前,它保存了正确的条目但没有图像。现在,我将 Django 文档中的部分添加到可变路径中,但在我单击保存按钮后没有任何反应。

<form action="/backend/leverandorer/add" method="post" enctype="multipart/form-data">
                                    {% csrf_token %}
                                    <div class="form-group">
                                        <label for="simpleinput">Leverandør</label>
                                        {{ form.Name }}
                                    </div>

                                    <div class="form-group">
                                        <label for="simpleinput">Webside</label>
                                        {{ form.URL }}
                                    </div>
                                    <div class="form-group">
                                        <label for="simpleinput">Logo</label>
                                        {{ form.ImageURL }}
                                        <!--<input type="file" name="ImageURL" accept="image/*" required="" id="id_ImageURL" class="form-control-file">-->
                                    </div>
                                    <input type="hidden" id="UserID" name="UserID" value="{{ user.id }}">
                                    <button type="submit" class="btn btn-primary">Gem</button>
                                </form>

我没有看到错误,但现在如果 ImageField 为空,它也不会在模型中保存表单。

问候 克里斯托弗。

您正在使用 UserID 作为隐藏字段。隐藏字段不会通过表单验证。所以你下面的代码将是错误的。

    if form.is_valid():
        form.save()
        return HttpResponseRedirect('/backend/leverandorer')

解决方案之一是,从您的模板中删除 UserID 字段并更新您的视图,如下所示。

  if form.is_valid():
     user_form = form.save(commit=False)
     user_form.UserID = request.user
     user_form.save()

我把models.py中的函数改成:

def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'user_{0}/{1}'.format(instance.UserID, filename)
class Leverandor(models.Model):
    ID = models.AutoField(primary_key=True)
    UserID = models.ForeignKey('Stamdata', on_delete=models.CASCADE)
    Name = models.CharField('Name', max_length=200)
    URL = models.URLField('URL', max_length=200)
    ImageURL = models.ImageField('ImageURL',blank=True, null=True, upload_to=user_directory_path)

有效,但路径是用户名而不是 user.id