Search code examples
djangodjango-modelsimage-uploading

Saving image fails without error in django model form


I want to try to save an image to my model:

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)

To this 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']

And rendererd to this 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,
        }
    )

The problem is that before I add the instance=request.user part its saves the entry correct but without image. Now I add the part from Django documentation like provided for save to an variable path but nothing happened after i click to save button.

<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>

I didnt see an error but now its not saving the form in models also if ImageField is empty.

regards Christopher.


Solution

  • I I change the function in models.py to:

    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)

    its works, but the Path is Username and not user.id