1 pièce(s) jointe(s)
Mettre des images dans un formulaire django
Bonjour,
j'aimerai réaliser un formulaire sur django afin de pouvoir voter parmis 2 images proposés.
Pour cela j'ai crée le model suivant comportant 2 tables, la table question et la table choix
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_image = models.ImageField()
def image_tag(self):
return mark_safe('<img src="%s" width="150" height="150" />' % (self.image))
image_tag.short_description = 'Image'
image_tag.allow_tags = True
votes = models.IntegerField(default=0) |
ensuite, via l'API de django, j'ai implémenté 2images dans ma base:
Code:
1 2 3 4 5 6 7
|
>>> from tryfit.models import Choice, Question
>>> from django.core.files import File
>>> q = Question.objects.get(pk=1)
>>> c = q.choice_set.create(choice_image=('static/media/point.jpg'), votes=0)
>>> c = q.choice_set.create(choice_image=('static/media/trait.jpg'), votes=0)
>>> c.save() |
pour finir, voici mon formulaire:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'tryfit/style.css' %}" />
<div id="detail" >
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'tryfit:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_image }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
</div> |
mais le problème c'est que les images ne s'affichent pas, voici ce que j'obtiens:
Pièce jointe 286286
A noter que je n'ai pas toucher a ma variable MEDIA_ROOT dans le setting.
Merci pour votre aide ;)