alphadog
alphadog

Reputation: 11199

Upload File in Django (not working)

I am creating a bulletin here containing threads. Each thread includes one image and then the thread can be extended with posts. It's like 4chan.

The models isn't saved in the database. I followed this answer to create an file upload example.

The forum app contains a simple file upload example and the upload objects do get saved there.

Codebase (github)

The project tree

bookstore/
  chan/
    templates/chan/index.html
    forms.py
    admin.py
    views.py
    urls.py
  forum/
    ...
  bookstore/
    settings.py
    urls.py

Settings

.
.
.
MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Urls.py

from django.conf.urls import url, include

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^create_post/(?P<thread_id>[0-9]+)/$', views.create_post, name='create_post'),
    url(r'^create_thread/$', views.create_thread, name='create_thread'),
]

Views

from django.shortcuts import render, redirect

from . import models
from . import forms

def index(request):
    threads = models.Thread.objects.all()
    thread_form = forms.Thread()
    post_form = forms.Post()

    return render(request, 'chan/index.html',{
        'threads':threads,
        'thread_form':thread_form,
        'post_form':post_form,
    })

def create_post(request, thread_id):
    form = forms.Post(request.POST, request.FILES)
    if form.is_valid():
        post = Post(
            text=request.POST['text'],
            document=request.FILES['document'],
            thread=models.Thread.get(pk=thread_id),
        )
        post.save()
    return redirect('chan:index')

def create_thread(request):
    form = forms.Thread(request.POST, request.FILES)
    if form.is_valid():
        thread = Thread(
            text=request.POST['text'],
            document=request.FILES['document']
        )
        thread.save()
    return redirect('chan:index')

I've been on this for hours now checking for anything that I might've missed.

Upvotes: 1

Views: 496

Answers (1)

Raja Simon
Raja Simon

Reputation: 10315

Honestly I have no idea what's you are trying to do. But when I look into that repo the hole thing is messed up. I have a few questions for you...

  1. Why you don't have __init__.py? ( hole repo doesn't have, not good )

    Best practise: Place init.py file and call the module with from module import something

  2. Why you don't have action attribute ?

    You have url={% ...} but you should have action={%...}

Upvotes: 1

Related Questions