Janek Podwysocki
Janek Podwysocki

Reputation: 593

django file upload doesn't work

Im working on web app project for study. I have a problem with file upload. It works for an admin, but for regular user files don't save. It must be a problem with mu views.py or template html

  1. forms.py

    class DocumentUpload(forms.ModelForm):
        class Meta:
            model = Form
            fields = ('file',)
    
  2. models.py

    class Form(TimeStampedModel, TitleSlugDescriptionModel):
        author = models.ForeignKey(User, on_delete=models.CASCADE)
        title = models.CharField(max_length=512)
        is_final = models.BooleanField(default=False)
        is_public = models.BooleanField(default=False)
        is_result_public = models.BooleanField(default=False)
        file = models.FileField(null=True, blank=True)
    
        def __str__(self):
            return self.title
    
        def get_absolute_url(self):
            return reverse('form-detail', kwargs={'slug': self.slug})
    
  3. views.py

    def create_form(request):
        if request.method == 'POST':
            user = request.user
            data = ParseRequest(request.POST)
            print(data.questions())
            print(data.form())
            parsed_form = data.form()
            parsed_questions = data.questions()
    
            # tworzy formularz o podanych parametrach
            formfile = DocumentUpload(request.POST, request.FILES or None)
            if formfile.is_valid():
                form = formfile.save(commit=False)
                print(form)
                form.author = user
                form.title = parsed_form['title']
                form.is_final = parsed_form['is_final']
                form.is_result_public = parsed_form['is_result_public']
                form.description = parsed_form['description']
                form.save()
                # zapisuje pytania z ankiety wraz z odpowienimi pytaniami
                for d in parsed_questions:
                    question = Question(form=form, question=d['question'])
                    question.save()
                    # dla kazdego pytania zapisz wszystkie opcje odpowiadania
                    for opt in d['options']:
                        option = Option(question=question, option=opt)
                        option.save()
                return render(request, 'forms/form_form.html', {})
        else:
            form = DocumentUpload()
            return render(request, 'forms/form_form.html', {'form': form})
    
  4. create_form.html

        {% block content %}
        <form method="post" id="form" enctype='multipart/form-data'>
        {%csrf_token %}
        <div class="form-group">
             {% csrf_token %}
             <label for="form-title">Tytuł formularza</label>
             <input id="form-title" class="form-control" type="text" 
                                      placeholder="Tytuł" required/>
         </div>
            {{ form.as_p }}
        <input class="btn btn-default" type="submit" value="zapisz"/>
        </form>
        {% endblock %}
    

    5.settings.py

    ....
    DATABASES = {
        'default': {
        'ENGINE': 'django.db.backends.sqlite3',
       'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
    STATIC_URL = '/static/'
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'static'),
    ]
    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')
    ...
    

    5.urls.py

    if settings.DEBUG:
        urlpatterns += 
         static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
        urlpatterns += static(settings.MEDIA_URL, 
             document_root=settings.MEDIA_ROOT)
    

Upvotes: 3

Views: 4266

Answers (2)

Horai Nuri
Horai Nuri

Reputation: 5578

You forgot to add action on your form just like so :

<form action="{% url 'name_of_your_function' %}" method="post" id="form" enctype='multipart/form-data'>
...
</form>

action must contain your url name, example :

url(url_regex, views.function, name="name_of_your_function"),

Upvotes: 2

zaidfazil
zaidfazil

Reputation: 9235

You haven't specified an upload_to attribute for your FileField in models.py.

Add a directory for your field, like,

file = models.FileField(upload_to='uploads/', null=True, blank=True)

Your form is all fine and the file has been sent through request, but Django does not know where to save the file, until you define it in your models.

Read more about it in the docs here

Upvotes: 0

Related Questions