简体   繁体   English

如何在 Django 问卷中显示图像

[英]How to display images in Django questionnaire

I am working on a Django app where the user will be able to take any survey they pick from a list of surveys.我正在开发一个 Django 应用程序,用户可以在其中进行他们从调查列表中选择的任何调查。 For one of the surveys, they are supposed to select an image that best represents their mood.对于其中一项调查,他们应该选择最能代表他们心情的图像。 For their answer I do not need to record the image they selected, just the name of the mood it represents (for example, "cheerful").对于他们的回答,我不需要记录他们选择的图像,只需要记录它所代表的心情的名称(例如,“开朗”)。 Therefore, I have not yet added an "image" field to the model.因此,我还没有向模型添加“图像”字段。 However, the user should be able to see the image and select it.但是,用户应该能够看到图像并选择它。 At the moment I am not able to display the images, only getting the names.目前我无法显示图像,只能获取名称。 I have checked my code and still unable to find the mistake.我已经检查了我的代码,但仍然无法找到错误。 By the way, not getting any technical error messages.顺便说一句,没有收到任何技术错误消息。 Any recommendations you have are appreciated.感谢您的任何建议。 Below are my models, views, and HTML.下面是我的模型、视图和 HTML。 I apologize for the lengthy files.对于冗长的文件,我深表歉意。

Thank you!谢谢!

Models楷模

User = settings.AUTH_USER_MODEL

class Questionnaire(models.Model): 
    name = models.CharField(max_length=255) 
    text = models.CharField(max_length=200)

    def __str__(self):
        return self.name

class Question(models.Model):
    text = models.CharField(max_length=200)
    questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE, related_name='questions')
    def __str__(self):
        return self.text

class Answer(models.Model):
    questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE, related_name='answers', default='')
    text = models.CharField(max_length=200)

    def __str__(self):
        return self.text
 
class Response(models.Model):
    user = models.ForeignKey(User, on_delete = models.CASCADE)  
    date = models.DateTimeField(auto_now_add=True)
    question = models.ForeignKey(Question, on_delete = models.CASCADE)
    answer = models.ForeignKey(Answer, on_delete = models.CASCADE)
    def __str__(self):
        return '%s - %s - %s - %s' % (self.user, self.question, self.answer, self.date)

Views观看次数

from django.forms import ModelForm
class ResponseForm(ModelForm):
    class Meta:
        model = Response
        fields = ['question', 'answer']
        # widgets= {'answer': RadioSelect}
    
    def __init__(self, *args, user=None, **kwargs):
        self.user = user
        super().__init__(*args, **kwargs)

    def save(self, commit=True):
        response = super().save(commit=False)
        response.user = self.user
        return response.save()


def take_questionnaire_fs(request, questionnaire_id):

    ResponseFormSet = modelformset_factory(Response, form=ResponseForm, extra=0)
    if request.method == 'POST':
        formset = ResponseFormSet(request.POST or None, request.FILES, form_kwargs={'user': request.user})
        if formset.is_valid():
            print("Formset is valid")
            formset.save()
            return HttpResponseRedirect(reverse ('questionnaires:questionnaire_index'))
        else:
            print("Formset is NOT valid")
            print(formset.errors)
            print(formset.non_form_errors())

    questions = Question.objects.filter(questionnaire_id=questionnaire_id)
    answers = Answer.objects.filter(questionnaire_id=questionnaire_id)

    return render(request, 'questionnaires/take_questionnaire_fs.html', {
        'questions': questions,
        'answers': answers,
        })

HTML HTML

{% extends "base.html" %}
{% block page_content %}


{% if questionnaire.name == 'Pick-a-Mood' %}
<form action="{{ request.url }}" method="post">
{% csrf_token %} 
  <style>

    .circle-container {
            position: relative;
            width: 24em;
            height: 24em;
            padding: 2.8em;
            /*2.8em = 2em*1.4 (2em = half the width of a link with img, 1.4 = sqrt(2))*/
            /* border: dashed 1px; */
            border-radius: 50%;
            margin: 1.75em auto 0;
        }
        .circle-container label {
            display: block;
            position: absolute;
            top: 50%; left: 50%;
            width: 8em; height: 8em;
            margin: -2em;
        }
        .circle-container img { display: block; width: 100%; }
        .deg22_5 { transform: rotate(22.5deg) translate(12em) rotate(-22.5deg); }
        .deg67_5 { transform: rotate(67.5deg) translate(12em) rotate(-67.5deg); }
        .deg112_5 { transform: rotate(112.5deg) translate(12em) rotate(-112.5deg); }
        .deg157_5 { transform: rotate(157.5deg) translate(12em) rotate(-157.5deg); }
        .deg202_5 { transform: rotate(202.5deg) translate(12em) rotate(-202.5deg); }
        .deg247_5 { transform: rotate(247.5deg) translate(12em) rotate(-247.5deg); }
        .deg292_5 { transform: rotate(292.5deg) translate(12em) rotate(-292.5deg); }
        .deg337_5 { transform: rotate(337.5deg) translate(12em) rotate(-337.5deg); }
    
    
    /* HIDE RADIO */
    [type=radio] { 
      position: absolute;
      opacity: 0;
      width: 0;
      height: 0;
    }
    
    /* IMAGE STYLES */
    [type=radio] + img {
      cursor: pointer;
    }
    
    /* CHECKED STYLES */
    [type=radio]:checked + img {
      border: 2px solid #f00;
      
    }
    [type=radio]:not(:checked) + img {
      border: none;
    }
    
    </style>

    <div class="circle-container">
        <label class='center'>
            <input type="radio" name="pickamood" value="Neutral">
            <img src="/static/mysurveys/female_neutral.png">
        </label>
    
        <label class='deg22_5'>
            <input type="radio" name="pickamood" value="Relaxed">
            <img src="/static/mysurveys/female_relaxed.png">
        </label>
    
        <label class='deg67_5'>
            <input type="radio" name="pickamood" value="Calm">
            <img src="/static/mysurveys/female_calm.png">
        </label>
    
        <label class='deg112_5'>
            <input type="radio" name="pickamood" value="Bored">
            <img src="/static/mysurveys/female_bored.png">
        </label> 
        
        <label class='deg157_5'>
            <input type="radio" name="pickamood" value="Sad">
            <img src="/static/mysurveys/female_sad.png">
        </label>
    
        <label class='deg202_5'>
            <input type="radio" name="pickamood" value="Irritated">
            <img src="/static/mysurveys/female_irritated.png">
        </label>
    
        <label class='deg247_5'>
            <input type="radio" name="pickamood" value="Tense">
            <img src="/static/mysurveys/female_tense.png">
        </label>
    
        <label class='deg292_5'>
            <input type="radio" name="pickamood" value="Excited">
            <img src="/static/mysurveys/female_excited.png">
        </label>     
    
        <label class='deg337_5'>
            <input type="radio" name="pickamood" value="Cheerful">
            <img src="/static/mysurveys/female_cheerful.png">
        </label>     
    </div>
<a>
  <input type="submit" value="Submit" >
</a>
 
</form>

{% else %}
<form method="post" action="{{ request.url }}">
    {% csrf_token %}

    {% for question in questions %}
        <h1>{{question.text}}</h1> 
    
        <label hidden="" for="id_form-{{ forloop.counter0 }}-question">Question:</label>
        <select hidden="" name="form-{{ forloop.counter0 }}-question" id="id_form-{{ forloop.counter0 }}-question">
            <option value="{{question.id}}" selected="">{{question.text}}</option>
        </select>

        <label for="id_form-{{ forloop.counter0 }}-answer">Answer:</label>
        <select required="" name="form-{{ forloop.counter0 }}-answer" id="id_form-{{ forloop.counter0 }}-answer">
            <option value="" selected="">---------</option>
            {% for answer in answers %}
                <option value="{{answer.id}}">{{answer.text}}</option>
            {% endfor %}
        </select>
        
        <input type="hidden" name="form-{{ forloop.counter0 }}-id" value="{{ forloop.counter }}" id="id_form-{{ forloop.counter0 }}-id">
           
        <input type="hidden" name="form-TOTAL_FORMS" value="{{questions|length}}" id="id_form-TOTAL_FORMS" />
        <input type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS" />
        <input type="hidden" name="form-MAX_NUM_FORMS" value="{{questions|length}}" id="id_form-MAX_NUM_FORMS" />

    {% endfor %}


    <br />
    <br />
    <input type="submit" value="Submit">
</form>
{% endif %}

{% endblock %}

You need to use static files .您需要使用静态文件

Make sure it's set up in your settings.py and then in the html load static and use it to get your files.确保它已在您的 settings.py 中设置,然后在 html load static 中设置并使用它来获取您的文件。

Eg.例如。 Assuming your files are in a static folder and that is set up in settings.py假设您的文件位于静态文件夹中,并且在 settings.py 中设置

<img src="{% static 'mysurveys/female_irritated.png' %}">

Try these steps in order:按顺序尝试以下步骤:

  1. Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS .确保django.contrib.staticfiles包含在您的INSTALLED_APPS 中

  2. In your settings file, define STATIC_URL:在您的设置文件中,定义 STATIC_URL:

     STATIC_URL = '/static/'
  3. In your template file在您的模板文件中

     {% load static %} <img src="{% static 'mysurveys/female_irritated.png' %}" alt="image alt">
  4. Store your static files in a folder called static in your app.将您的静态文件存储在您的应用程序中名为 static 的文件夹中。 For example my_app/static/mysurveys/female_bored.png .例如my_app/static/mysurveys/female_bored.png As you done already正如你所做的那样

More informations in Django doc . Django 文档中的更多信息

thank you for the suggestions!感谢你的建议! The static files were set up correctly, the error was that I needed to add the field 'questionnaire' to my views.静态文件设置正确,错误是我需要将“问卷”字段添加到我的视图中。 The syntax is now:现在的语法是:

def take_questionnaire_fs(request, questionnaire_id):

ResponseFormSet = modelformset_factory(Response, form=ResponseForm, extra=0)

if request.method == 'POST':
    formset = ResponseFormSet(request.POST or None, request.FILES, form_kwargs={'user': request.user})
    if formset.is_valid():
        # do something with the formset.cleaned_data
        print("Formset is valid")
        formset.save()
        return HttpResponseRedirect(reverse ('questionnaires:questionnaire_index'))
      
    else:
        print("Formset is NOT valid")
        print(formset.errors)
        print(formset.non_form_errors())
         


questionnaire = Questionnaire.objects.get(id=questionnaire_id)
questions = Question.objects.filter(questionnaire_id=questionnaire_id)
answers = Answer.objects.filter(questionnaire_id=questionnaire_id)



return render(request, 'questionnaires/questionnaire_lec.html', {
    'questions': questions,
    'answers': answers,
    'questionnaire': questionnaire,
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM