file URL missing project name

59 views
Skip to first unread message

Jeff Williams

unread,
Nov 18, 2018, 3:18:04 PM11/18/18
to django...@googlegroups.com
Hi All,
I'm new to django, so sorry if this is a newbie issue.

I've managed to upload an ImageField....but when I try to display it in my template using object.pic.url...the URL I'm getting back is missing my project name from the URL and the pic is not loading.


http://127.0.0.1:8000/oldgrub/media/media/56288852934__75FACD12-1711-4655-96D5-716198FE10B7.JPG

back to have it work.  

What am I missing?  I've poured over my configs.
Jeff 

Joel Mathew

unread,
Nov 18, 2018, 3:24:01 PM11/18/18
to django...@googlegroups.com
It's anybody's guess unless you post your code.
Sincerely yours,

 Joel G Mathew



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAMgbqCe3UzvrWFg4fiRSPXp6HtLJoPJmGs8oPSZjAd%3Dxx4ygNQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Jeff Williams

unread,
Nov 18, 2018, 3:37:14 PM11/18/18
to django...@googlegroups.com
OK here are what I think are the relevant parts:

settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = (
                os.path.join(BASE_DIR,'static'), # if your static files folder is named "staticfiles"
)

# Redirect to home URL after login (Default redirects to /accounts/profile/)
LOGIN_REDIRECT_URL = '/'

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


urls.py


urlpatterns = [
path('', views.index, name='index'),
path('cookbooks/', views.CookBookListView.as_view(), name='cookbooks'),
path('cookbook/<uuid:pk>', views.CookBookDetailView.as_view(), name='cookbook'),
path('recipe/', views.RecipeListView.as_view(), name='recipes'),
path('recipe/<uuid:pk>', views.RecipeDetailView.as_view(), name='recipe'),
path('family/', views.FamilyDetailView.as_view(), name='family'),
path('recipe/add/', views.RecipeAdd, name='addrecipe'),
#Add Django site authentication urls (for login, logout, password management)
]

if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py

class Recipe(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular recipe across whole library')
cookbook = models.ForeignKey(CookBook,on_delete=models.SET_NULL, null=True, related_name='recipies')
title = models.TextField(max_length=1000, help_text='Enter a brief description of the Recipe')
author = models.TextField(max_length=1000, help_text='Enter the creator of the Recipie', blank=True)
text = models.TextField(max_length=10000, help_text='Enter the recipe')
notes = models.TextField(max_length=10000, help_text='Enter notes on the recipe',blank=True)
pic = models.ImageField(upload_to='media/',blank=True, null=True)

views.py
def RecipeAdd(request):
template_name = 'recipe_add.html'

r = Recipe(cookbook=Family.objects.get(members=request.user).FamilyCookbook)
# If this is a POST request then process the Form data
if request.method == 'POST':

# Create a form instance and populate it with data from the request (binding):
add_recipe_form = AddRecipeForm(request.POST, request.FILES)

# Check if the form is valid:
if add_recipe_form.is_valid():
# process the data in form.cleaned_data as required (here we just write it to the model due_back field)
# book_instance.due_back = book_renewal_form.cleaned_data['renewal_date']
r.author = add_recipe_form.cleaned_data['author']
r.notes = add_recipe_form.cleaned_data['notes']
r.text = add_recipe_form.cleaned_data['text']
r.title = add_recipe_form.cleaned_data['title']
# r.pic=add_recipe_form.cleaned_data['pic'] # file not being returned here
# r.pic = add_recipe_form.data['pic'] # file not being returned here
r.pic = request.FILES['pic'] #file not here

add_recipe_form.save() # save the recipe

# redirect to a new URL:
return HttpResponseRedirect(reverse('recipes'))

# If this is a GET (or any other method) create the default form.
else:
# proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3)
add_recipe_form = AddRecipeForm()

context = {
'form': add_recipe_form,
}

return render(request, 'recipe_add.html', context)

forms.py
class AddRecipeForm( ModelForm ):
pic = ImageField(widget= FileInput) # was widget=PictureWidget

class Meta:
model = Recipe
fields = ('title', 'author', 'text', 'notes', 'pic')
widgets = {
'title': Textarea( attrs={'cols': 40, 'rows': 1} ),
'author': Textarea( attrs={'cols': 40, 'rows': 1} ),
'text': Textarea( attrs={'cols': 40, 'rows': 1} ),
'notes': Textarea( attrs={'cols': 40, 'rows': 1} ),
# 'pic': Textarea(attrs={'cols': 40, 'rows': 1}),
recipe_list.html
<h1>Recipe List</h1>
{% if recipe_list %}
<ul>
{% for recipe in recipe_list %}
<li>
<!-- <a href="{{ recipe.get_absolute_url }}">{{ recipe.title }}</a> {{recipe.author}} -->
<p>{{ recipe.title }}</p> {{recipe.author}}

<p> {{recipe.text}} <p>
<p>{{ recipe.notes }}</p>
{% load static %}
<div class="recipe_image">
{% if recipe.pic %}
<a href="{{ recipe.pic.url }}">{{ recipe.title }}</a>
<img src="{{ recipe.pic.url}}" alt="{{ recipe.title }}" />

{% endif %}
</div>
<p> {{ recipe.pic }}</p>
</li>
{% endfor %}

Akash Purandare

unread,
Nov 18, 2018, 3:52:06 PM11/18/18
to Django users
Hi Jeff

I believe that the URL that you want to show is completely irrelevant as the Django's FileField does that for you. However, in case you really want your project name to be included in your URL, you can change the MEDIA_URL in your settings.py to '/oldgrub/media' to reflect the necessary changes for you.

Also, I believe that the problem you are facing is because you want to serve your files online by using the MEDIA_URL and MEDIA_ROOT. Hence, you must add this URL pattern at the end of your urls.py file of your main project folder.

from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
...(Your Urls)
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Regards
Akash Purandare

Jeff Williams

unread,
Nov 18, 2018, 4:09:26 PM11/18/18
to django...@googlegroups.com
Thanks Akash.
Haven't quite fixed it yet but this is definitely the right area.  
Jeff 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

Jeff Williams

unread,
Nov 18, 2018, 4:26:13 PM11/18/18
to django...@googlegroups.com
OK this is almost fixed:

Why isn't this path matching?

Using the URLconf defined in familyrecipies.urls, Django tried these URL patterns, in this order:

  1. admin/
  2. oldgrub/ [name='index']
  3. oldgrub/ cookbooks/ [name='cookbooks']
  4. oldgrub/ cookbook/<uuid:pk> [name='cookbook']
  5. oldgrub/ recipe/ [name='recipes']
  6. oldgrub/ recipe/<uuid:pk> [name='recipe']
  7. oldgrub/ family/ [name='family']
  8. oldgrub/ recipe/add/ [name='addrecipe']
  9. oldgrub/ ^oldgrub/media/(?P<path>.*)$
  10. accounts/

The current path, oldgrub/media/56288852088__208FCEF9-5890-4633-8BF6-C5C9A82D87EE.JPG, didn't match any of these.

Akash Purandare

unread,
Nov 18, 2018, 4:30:01 PM11/18/18
to Django users
Hey Jeff

I think that you might need to upload the file again and try.

Let me know if it works out.

Regards
Akash Purandare

Jeff Williams

unread,
Nov 18, 2018, 5:27:31 PM11/18/18
to django...@googlegroups.com
Nope.  Same error.  I can see the file being loaded.  Doesn't like the URL still. 

Akash Purandare

unread,
Nov 18, 2018, 6:00:18 PM11/18/18
to Django users
Hey Jeff

I tried the models that you were creating and I found out the error that you are having is with the Model. The upload_to of the pic variable is set to 'media/', which uploads the file to the url http://localhost:8000/oldgrub/media/media/56288852088__208FCEF9-5890-4633-8BF6-C5C9A82D87EE.JPG. So if you change the upload_to to '', the URL will be http://localhost:8000/oldgrub/media/56288852088__208FCEF9-5890-4633-8BF6-C5C9A82D87EE.JPG.

Hope this fixes the issue that you are facing.

Regards
Akash Purandare

Jeff Williams

unread,
Nov 18, 2018, 6:03:51 PM11/18/18
to django...@googlegroups.com
Akash,
You are good.....but I already changed that to get to the error I have now.  Still not working :-(  
The file is in the right place but the URL matching is messing up somehow. 


Jason

unread,
Nov 18, 2018, 10:24:06 PM11/18/18
to Django users
Seems like there might be some confusion on what exactly `MEDIA_ROOT` means.

you can do 

import logging
logger = logging.getLogger(__name__)
logger.info(MEDIA_ROOT)

in settings after declaring MEDIA_ROOT

if that path lines up with what you have in the server, then I suspect permission issue might be at play as well.

Jeff Williams

unread,
Nov 18, 2018, 11:32:51 PM11/18/18
to django...@googlegroups.com
MEDIA_ROOT and MEDIA_URL both seem fine.....and the URL I'm getting in the template looks fine.......but URLS.PY is kicking it out.  
I changed the security on the directory to full access to everyone.  Any ideas on how to debug this?  I can't see why the path isn't matching the pattern.

Using the URLconf defined in familyrecipies.urls, Django tried these URL patterns, in this order:

  1. admin/
  2. oldgrub/ [name='index']
  3. oldgrub/ cookbooks/ [name='cookbooks']
  4. oldgrub/ cookbook/<uuid:pk> [name='cookbook']
  5. oldgrub/ recipe/ [name='recipes']
  6. oldgrub/ recipe/<uuid:pk> [name='recipe']
  7. oldgrub/ family/ [name='family']
  8. oldgrub/ recipe/add/ [name='addrecipe']
  1. oldgrub/ ^static/(?P<path>.*)$
  1. oldgrub/ ^oldgrub/media/(?P<path>.*)$
  2. accounts/

    The current path, oldgrub/media/56288593216__746F513A-D6F6-446D-949F-D0C09E7C4419_sU3W0z5.JPG, didn't match any of these.



    --
    You received this message because you are subscribed to the Google Groups "Django users" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
    To post to this group, send email to django...@googlegroups.com.
    Visit this group at https://groups.google.com/group/django-users.
    Message has been deleted

    Jeff Williams

    unread,
    Nov 19, 2018, 1:49:23 AM11/19/18
    to django...@googlegroups.com
    That part is added by urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)so I doubt that is the issue.

    This is going to sound odd.....but I've had some files display and then stop working when I don't think I changed anything.  very odd.


    On Sun, Nov 18, 2018 at 6:46 PM Jason <jjohn...@gmail.com> wrote:
    (?P<path>.*)

    in your url is probably the reason why.  remove that bit

    --
    You received this message because you are subscribed to the Google Groups "Django users" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
    To post to this group, send email to django...@googlegroups.com.
    Visit this group at https://groups.google.com/group/django-users.

    Akash Purandare

    unread,
    Nov 20, 2018, 1:15:05 AM11/20/18
    to Django users
    Hey Jeff

    Can you send me the URL of the file and the Location of the uploaded media file?

    Regards
    Akash Purandare

    On Sunday, November 18, 2018 at 8:48:04 PM UTC+5:30, Jeff Williams wrote:

    Jeff Williams

    unread,
    Nov 20, 2018, 1:34:02 AM11/20/18
    to django...@googlegroups.com
    Hey Akash,
    Appreciate you still thinking about this.  I've tried moving my Media folder to copy a working project (still no luck).

    Here is the file: http://127.0.0.1:8000/media/documents/dsBuffer_rQWWvO9.jpg


    This is the media folder: D:\DjangoStuff\familyrecipies\media\documents

    My current guess is that I have something wrong in my HTML that is somehow causing an error....I think I've noticed that Dango gives a 404 error if it sees an HTML error (?).

    I copied a small working file-upload example and it worked.  I can't see any difference between the example and my code.
    Jeff 


    --
    You received this message because you are subscribed to the Google Groups "Django users" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
    To post to this group, send email to django...@googlegroups.com.
    Visit this group at https://groups.google.com/group/django-users.

    Akash Purandare

    unread,
    Nov 20, 2018, 8:06:10 AM11/20/18
    to Django users
    Hey Jeff

    It is completely alright to try until we find a solution to this.
    I quote from the Django Documentation:
    Note that request.FILES will only contain data if the request method was POST and the <form> that posted the request has the attribute enctype="multipart/form-data". Otherwise, request.FILES will be empty.

    Can you ensure that the particular requirements are fulfilled?

    Also, I would like to ask you to try to upload a file from the Django admin panel and tell me if it is working. If not, can you send me the URL and the uploaded path of the Admin panel uploaded file?

    Regards
    Akash Purandare

    On Sunday, November 18, 2018 at 8:48:04 PM UTC+5:30, Jeff Williams wrote:

    Jeff Williams

    unread,
    Nov 21, 2018, 1:09:11 AM11/21/18
    to django...@googlegroups.com
    Hey Akash,
    I did figure out the enctype="multipart/form-data" issue (I had that for a while but figured it out).  My files are loading.....they just aren't displaying.

    I just loaded an image using the Admin interface as you suggested (I hadn't thought of trying that) and the load is working.  The URL and path are still (relatively) the same:
    D:\DjangoStuff\familyrecipies\media\documents\reciper_rK1KS3j.jpg

    Still getting this when I try to display.  

    Page not found (404)

    Request Method:GET
    Request URL:http://127.0.0.1:8000/media/documents/reciper_rK1KS3j.jpg

    Using the URLconf defined in familyrecipies.urls, Django tried these URL patterns, in this order:

    1. admin/
    2. oldgrub/
    3. accounts/

    The current path, media/documents/reciper_rK1KS3j.jpg, didn't match any of these.

    You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.


    I think I mentioned before that I took another picture-upload project, built it, and made it work (which it did).
    When I took the relevant parts into my own app....it stopped working :-(.

    --
    You received this message because you are subscribed to the Google Groups "Django users" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
    To post to this group, send email to django...@googlegroups.com.
    Visit this group at https://groups.google.com/group/django-users.

    رهام صادقی

    unread,
    Nov 21, 2018, 1:38:14 PM11/21/18
    to django...@googlegroups.com
    Hi,
    add these two lines to your settings.py file
    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    after that in your base urls.py (a file along with settings.py)
    add the following url:
    from django.conf.urls.static import static
    from django.conf import settings


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

    ‫‪Jeff Williams‬‏ <‪jeff99w...@gmail.com‬‏> در تاریخ چهارشنبه ۲۱ نوامبر ۲۰۱۸ ساعت ۴:۳۸ نوشت:‬

    Jeff Williams

    unread,
    Nov 21, 2018, 10:49:03 PM11/21/18
    to django...@googlegroups.com
    I *had* added the above, but I put them in the 'lower down' URLS.PY file.  As soon as I added them to the higher-level one everything worked!!!!!

    Thanks Roham!  Thanks Akash!  I really appreciate your time and help here.
    Jeff 



    Reply all
    Reply to author
    Forward
    0 new messages