How to get an ImageField URL within a template?

前端 未结 4 398
执笔经年
执笔经年 2020-11-30 10:15

I\'ve got the following model in my Django app:

class Image(models.Model):
    image = models.ImageField(
        upload_to=\'images/\', 
        height_fiel         


        
相关标签:
4条回答
  • 2020-11-30 10:46

    Create a folder "static" in you're django project and add this to you're settings file

    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'static'),
    )
    

    If you don't have this line in you're settings file also add it

    BASE_DIR = os.path.dirname(os.path.dirname(__file__))
    

    Now in the template you can use

    {% static  image.image.url %}
    
    0 讨论(0)
  • 2020-11-30 10:49

    You need {{ image.image.url }} & {{ image.image.path }}, while {{ image }} - just an Image object

    0 讨论(0)
  • 2020-11-30 10:50

    Change your code to this:

    <ul>
    {% for image in article.image_set.all %}
        <li>Caption: "{{ image.caption }}", Credit: "{{ image.credit }}", URL: "<a href ='/{{ image.image }}'{{ image.image }}</a>"</li>
    {% endfor %}
    </ul>
    

    Change {{ image.url }} to {{ image.image }} because '.image' contains the location of the image. The reason that you don't get any value from '.url' is that you don't have a field url in your class Image in your models.

    0 讨论(0)
  • 2020-11-30 10:52

    if you have ImageForm in forms.py and passing Form Instance to your django template then src="{% get_media_prefix %}{{your-form-instance.instance.image}}" will solve your issue.

    models.py

    class Addon(models.Model):
        image = models.FileField(upload_to='addons/', null=True)
        addon_name = models.CharField(max_length=100, null=False, blank=False)
    

    forms.py

    class AddonForm(forms.ModelForm):
        addon_name = forms.CharField(max_length=100, required=True)
        image = forms.ImageField(required=False)
    

    views.py

    @require_http_methods(['GET'])
    def addons(request, ):
        addon_form_set = modelformset_factory(Addon, form=AddonForm, extra=1)
        addon_forms = addon_form_set(queryset=Addon.objects.all())
        return render(request, 'addons/addons.html', {'form': addon_forms)
    

    your_templates.html

    {% for data in form %}
       <img src="{% get_media_prefix %}{{data.instance.image}}"/>
    {% endfor %}
    
    0 讨论(0)
提交回复
热议问题