0

I'm new to django. I've been stuck for a while. I believe everything is configured correctly. However, when my objects are created it is not creating the media directory or storing the files/images. I have done the settings file, urls, views, models, forms everything.

Here are relevant files:


// setting.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

// models.py
class Trip(models.Model):
    city = models.CharField(max_length= 255)
    country = models.CharField(max_length= 255)
    description = models.CharField(max_length= 255)
    creator = models.ForeignKey(User, related_name = 'trips_uploaded',on_delete= CASCADE, null=True)
    favoriter = models.ManyToManyField(User, related_name= 'fav_trips')
    photo = models.ImageField(null=True, blank =True, upload_to='trips/')

// urls.py ( there were 2 ways to write media according to tutorial)
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('travelsiteapp.urls'))
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 

# urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 

// views.py (lastly)
def tripAdd(request):
    form = TripForm()
    if request.method == 'POST':
        form = TripForm(request.POST, request.FILES)
        if form.is_valid():
            form.photo = form.cleaned_data["photo"]
            form.save()

    context = { 'form': form}
    return render(request, 'tripAdd.html', context)

// html/ form

    <form action="/createTrip"method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{form.as_p}}
        <input type="submit" value="submit">
    </form>

// forms.py 

from django import forms
from django.forms import ModelForm
from .models import Trip
from django import forms

class TripForm(ModelForm):
    class Meta:
        model = Trip
        fields = ['city', 'country', 'description', 'photo']


// I have hit all the steps not sure whats wrong? & and installed pip pillow

Keith Coye
  • 75
  • 1
  • 7

1 Answers1

0

Which url is serving the tripAdd() view? If it is /createTrip as in your form, then add a trailling slash in the action like this: /createTrip/. When you post to an URL, Django expects a trailing slash by default. You can customize that behavior if you like. Also, don't forget to declare this URL (since it is not in the example you provided).

Sakib Hasan
  • 391
  • 1
  • 7