首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django模型表单可以保存到数据库,但无法在模板中显示

Django模型表单可以保存到数据库,但无法在模板中显示
EN

Stack Overflow用户
提问于 2020-05-23 02:24:21
回答 1查看 33关注 0票数 0

我试图保存我的模型表单的输入,它只将输入保存到数据库中,直到我转到数据库并单击保存按钮,它才会显示在模板上。我的表单和我显示提交的输入的位置在同一个HTML页面上。这一切为什么要发生?我似乎找不到原因。请容忍我,因为我是新来姜戈的。提前谢谢。

views.py:

代码语言:javascript
复制
def detail(request, pk):
    prof = get_object_or_404(Prof, pk=pk)
    ratings = Rating.objects.filter(slug=pk)

    paginator = Paginator(ratings, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    new_rating = None

    # rating posted
    if request.method == 'POST':
        rating_form = RatingForm(data=request.POST)
        if rating_form.is_valid():
            # Create Rating object but don't save to database yet
            new_rating = rating_form.save(commit=False)
            # Assign the current prof to the rating
            new_rating.name = prof
            # Save the rating to the database
            new_rating.save()

    else:
        rating_form = RatingForm()

    return render(request, 'rating/detail.html', {'prof': prof, 'ratings': ratings, 'new_rating': new_rating, 'rating_form': rating_form, 'page_obj': page_obj})

模板:

代码语言:javascript
复制
...

<p class="centerize mt-4">{{ ratings.count }} {% if ratings.count > 1 or ratings.count == 0 %} ratings {% else %} rating {% endif %}</p>
{% for rating in page_obj %}
    <div class="rating-container-detail">
        <div class="card border-secondary">
            <div class="card-header">{{ rating.subject }} - {{ rating.year }} <span class="float-right"> {{ rating.created_on|date:'F j, Y' }} </span></div>
            <div class="card-body">
                <p class="card-title">Helpfulness: <span class="badge badge-primary badge-pill"> {{ rating.helpfulness }}</span> &nbsp; &nbsp;
                                    Pedagogy: <span class="badge badge-primary badge-pill"> {{ rating.pedagogy }} </span> &nbsp; &nbsp;
                                    Easiness: <span class="badge badge-primary badge-pill"> {{ rating.easiness }} </span>
                </p>
                <p class="card-text">{{ rating.comment | linebreaks }}</p>
            </div>
        </div>
    </div>
{% empty %}

    <p class="centerize">No ratings were found for this professor. <br> You may create one if you like: <a class="nav-link" data-toggle="tab" href="#create"> create a review</a></p>
{% endfor %}


...

<div class="ml-auto mr-auto mt-4" style="width: 40%;">
    {% if new_rating %}
        <div class="alert alert-success" role="alert">
            Successfully created rating 
        </div>
    {% else %}
        <form method="post" action="{% url 'rating-detail' prof.pk %}">
            {{ rating_form | crispy }}
            {% csrf_token %}
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    {% endif %}
</div>

...

models.py:

代码语言:javascript
复制
class Rating(models.Model):
    helpfulness_choices = (
        (1, 'Very Unhelpful'),
        (2, 'Unhelpful'),
        (3, 'Moderate'),
        (4, 'Helpful'),
        (5, 'Very Helpful'),
    )

    pedagogy_choices = (
        (1, 'Very Low Pedagogy'),
        (2, 'Low Pedagogy'),
        (3, 'Moderate'),
        (4, 'High Pedagogy'),
        (5, 'Very High Pedagogy'),
    )

    easiness_choices = {
        (1, 'Very Difficult'),
        (2, 'Difficult'),
        (3, 'Moderate'),
        (4, 'Easy'),
        (5, 'Very Easy'),
    }

    name = models.ForeignKey(Prof, on_delete=models.CASCADE, related_name="ratings")
    slug = models.SlugField(max_length=110)
    subject = models.CharField(max_length=10)
    year = models.IntegerField(default=0)
    helpfulness = models.IntegerField(choices=helpfulness_choices)
    pedagogy = models.IntegerField(choices=pedagogy_choices)
    easiness = models.IntegerField(choices=easiness_choices)
    comment = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['created_on']

    def __str__(self):
        return str(self.name)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-23 03:24:54

我解决了这个问题:

我刚添加了

代码语言:javascript
复制
active = models.BooleanField(default=True)

,并将其设置为true。

然后在我的模型细节中进行“评分”,如下所示:

代码语言:javascript
复制
ratings = prof.ratings.filter(active=True)

我也可以通过这样的评分来做到这一点:

代码语言:javascript
复制
ratings = prof.ratings.all()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61961549

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档