2

I'm New in Django 2. I was trying to upload a file in Django here is my code

View.py

def addBook(request):
    checkName = AddBook.objects.filter(title=request.POST.get('title'))
    if not checkName:
        bookAdd = AddBook(
            title=request.POST.get('title'),
            slug=slugify(request.POST.get('title')),
            description=request.POST.get('description'),
            cover_image=request.FILES.get('cover_image'),
            file=request.FILES.get('file'),
            category=request.POST.get('category'),
            created_by=request.user.id,
        )
        bookAdd.save()
        messages.add_message(request, messages.INFO, 'Book Saved Successfully')
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
    else:
        messages.add_message(request, messages.INFO, 'Book Title Already Exists')
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

Update As per Comment

Here is my template code bookSave.html

<form action="{% url 'addBook' %}" method="post" enctype="multipart/form-data">
                    {% csrf_token %}
                    <div class="modal-body">
                        <div class="col-lg-12 col-md-12 col-sm-12 col-xs 12">
                            <div class="form-group ic-cmp-int">
                                <div class="form-ic-cmp">
                                    <i class="notika-icon notika-edit"></i>
                                </div>
                                <div class="nk-int-st">
                                    <input type="text" class="form-control input-sm" required="required" name="title"
                                           Placeholder="Title">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-body">
                        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                            <div class="form-group ic-cmp-int">
                                <div class="form-ic-cmp">
                                    <i class="notika-icon notika-mail"></i>
                                </div>
                                <div class="nk-int-st">
                                <textarea class="form-control input-sm" required="required" name="description"
                                          placeholder="Description"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-body">
                        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                            <div class="form-group ic-cmp-int">
                                <div class="form-ic-cmp">
                                    <i class="notika-icon notika-dollar"></i>
                                </div>
                                <div class="nk-int-st">
                                    <input type="file" name="cover_image" required="required" class="form-control input-sm">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-body">
                        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                            <div class="form-group ic-cmp-int">
                                <div class="form-ic-cmp">
                                    <i class="notika-icon notika-house"></i>
                                </div>
                                <div class="nk-int-st">
                                    <input type="file" name="file" required="required" class="form-control input-sm">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-body">
                        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                            <div class="form-group ic-cmp-int">
                                <div class="form-ic-cmp">
                                    <i class="notika-icon notika-next"></i>
                                </div>
                                <div class="nk-int-st">
                                    <input type="text" name="category" required="required" class="form-control input-sm"
                                           Placeholder="Category">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-default">Save changes</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>
                </form>

I can save everything but I need to save the file path and save the file locally. I read their documentation but cannot help me out. Please help me to solve this problem

Community
  • 1
  • 1
Robot
  • 135
  • 1
  • 1
  • 6
  • 1
    show the form in the html too – Exprator Jan 25 '19 at 05:14
  • Dear @Exprator I just update my question – Robot Jan 25 '19 at 05:18
  • 2
    ok the form has file and cover_image as name for both the files, but you are taking title for all the cases, change them in your view with appropriate input names – Exprator Jan 25 '19 at 05:20
  • I am really sorry for that I was testing and forget to change when I ask this question – Robot Jan 25 '19 at 05:25
  • so you have problem still? – Exprator Jan 25 '19 at 05:28
  • I don't know how to load the file in my storage and save the file path name into the database and show the file. Would you please help to do that? – Robot Jan 25 '19 at 05:29
  • why dont you use a ModelForm as you have a Model associated, it will be easier. check ModelForm and how to upload files through it. – Exprator Jan 25 '19 at 05:31
  • I come from php background and now I'm new in Django I learn from this way to use my work I will learn this later but the problem is I need to work with this way for now. I need to solve this problem. – Robot Jan 25 '19 at 05:36

1 Answers1

3

The FileField in your Model, besides the other fields, should look like this:

class AddBook(models.Model):
    # file will be uploaded to MEDIA_ROOT/uploads
    file = models.FileField(upload_to='uploads/')
    # or...
    # file will be saved to MEDIA_ROOT/uploads/2015/01/30
    file = models.FileField(upload_to='uploads/%Y/%m/%d/')

In your settings file, you’ll need to define MEDIA_ROOT as the full path to a directory where you’d like Django to store uploaded files. (For performance, these files are not stored in the database.) Define MEDIA_URL as the base public URL of that directory. Make sure that this directory is writable by the Web server’s user account.

in settings.py you should set for example:

MEDIA_ROOT = '/home/foo/bar/yourproject/assets'

Also you might want to study and set static files storage in Django (besides the ‘static’ folder).

https://docs.djangoproject.com/en/2.0/howto/static-files/#configuring-static-files

In Django you can get any file with the File Object like:

from django.core.files import File

# Open an existing file using Python's built-in open()
f = open('/path/to/mybookfile.pdf')
myfile = File(f)
Zollie
  • 1,171
  • 7
  • 14
  • it saves information into the database but where is the file save? – Robot Jan 25 '19 at 07:31
  • The file is in default saved in the MEDIA_ROOT. In the above example you see the path where the file is saved, as it defined in the Model field with upload_to=' '. I do not see exactly what is your question. Please clarify. – Zollie Jan 25 '19 at 07:35
  • 1
    You can also define other directory in your settings file at/with MEDIA_ROOT= and you can define any folder you want for uploaded files' root. – Zollie Jan 25 '19 at 07:39
  • 1
    I also updated my answer with how to get a file back in Django. – Zollie Jan 25 '19 at 07:45
  • Thank you for your answer its work perfectly but I want to save my file into my assets folder how could I do that? – Robot Jan 25 '19 at 07:52
  • @Robot - I updated my answer with defining other MEDIA_ROOT folder. You have to give the full path to the directory where you want your files uploaded and stored. – Zollie Jan 25 '19 at 07:59