0

I am creating an image upload function with django. However, it is not uploaded. I don't know the code mistake, so I want to tell you. I tried variously, but if I specify default for imagefiled, default will be applied.

#form
class RecordCreateForm(BaseModelForm):

    class Meta:
        model = URC
        fields = ('image','UPRC','URN',)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(RecordCreateForm,self).__init__(*args, **kwargs)
        self.fields['URN'].queryset =  UPRM.objects.filter(user=user)
#view
class RecordCreate(CreateView):
    model = URC
    form_class = RecordCreateForm
    template_name = 'records/urcform.html'
    success_url = reverse_lazy('person:home')

    def get_form_kwargs(self):
      kwargs = super(RecordCreate, self).get_form_kwargs()
      # get users, note: you can access request using: self.request
      kwargs['user'] = self.request.user
      return kwargs

    def form_valid(self, form):
        user = self.request.user
        form.instance.user = user
        form.instance.group = belong.objects.get(user=user).group
        return super().form_valid(form)
#model
def get_upload_path(instance, filename):
  n = datetime.now()
  prefix = "records/"
  ymd='/'.join([n.strftime('%Y'), n.strftime('%m'), n.strftime('%d'), ""]) + "/"
  directory=str(instance.user.id) + "/"
  name=str(uuid.uuid4()).replace("-", "")
  extension=os.path.splitext(filename)[-1]
  return ''.join([prefix, directory, ymd, name, extension])

class URC(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    group = models.ForeignKey(group, on_delete=models.CASCADE, null=True)
    URN = models.ForeignKey(UPRM, on_delete=models.CASCADE)
    UPRC = models.CharField(max_length=300)
    image = models.ImageField(upload_to=get_upload_path)

    def __str__(self):
        return self.UPRC
#urls
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

I will post any other necessary code. Sorry for the poor English.

Postscript

The page is redirected without any error display. But admin screen was able to upload.

class BaseModelForm(forms.ModelForm):
  def __init__(self, *args, **kwargs):
    kwargs.setdefault('label_suffix', '')
    super(BaseModelForm, self).__init__(*args, **kwargs)
#template
<form method="post" action="">
    {% csrf_token %}
    {{form.image.label_tag}}
    {{form.image}}
    {{form.UPRC.label_tag}}
    {{form.UPRC}}
    {{form.URN.label_tag}}
    {{form.URN}}
    <input class="btn btn-primary" type="submit" value="submit">
</form>
16
  • Can you give some more details about what exactly is happening? Is the form_valid() method called? Is a URC object created in the database (check in your django admin site)? How do you notice the image is not uploaded? Are you seeing an error? When you submit the form, what happens in your browser, do you get redirected to the 'person:home' view? Commented Aug 23, 2019 at 14:38
  • And RecordCreateForm should subclass ModelForm, not BaseModelForm. Commented Aug 23, 2019 at 14:39
  • I added the necessary part. Commented Aug 23, 2019 at 15:01
  • what does it mean "admin screen was able to upload"? When you look at the URC object in admin, is it there? Do you see the image? Commented Aug 23, 2019 at 15:04
  • The template could not be uploaded at the moment, and the admin could upload it. Commented Aug 23, 2019 at 15:07

2 Answers 2

1

Your <form> tag misses the enctype, as explained here:

<form method="post" enctype="multipart/form-data">
Sign up to request clarification or add additional context in comments.

1 Comment

see here could be a permission issue if code is correct : stackoverflow.com/a/73045506/3904109
-1

You can take a look at this example. https://www.pythonsetup.com/simple-file-uploads-django-generic-createview/

def form_valid(self, form):
        self.object = Author(photo=self.get_form_kwargs().get('files')['photo'])
        self.object = form.save()
        return HttpResponseRedirect(self.get_success_url())

2 Comments

This code makes no sense. What does the first line self.object = ... do if you're going to then assign it to form.save()?
this shows you that using a ModelForm with an image field just works, you can just save the form and image is saved.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.