开发者社区> 问答> 正文

Django:使用html更改Django模型

我试图使一个按钮/图像在HTML页面改变一个特定的值a 使用Django将模型传递到该HTML页面。 我设置它的方式是,我们获得一个请求一个特定的URL,它去我们的视图。py,它告诉我们抓取三个随机的和唯一的模型。我们将这三个惟一的模型传递到render()中指定的.html页面,.html页面负责显示关于这些模型的哪些属性。 index . html

{%  load static %}
<figure><img src="/media/{{ f1.Img }}" width="200" height="180" alt="">
  <figcaption>
    <h2>{{ f1.Desc }}</h2>
    <p>Score: {{ f1.Score }}</p>
    <footer class="bottomButton"><img src="{% static 'site-logo.jpg'%}" width="50%" height="50%" alt=""></footer>
  </figcaption>
</figure>

figtitle是我想要修改的内容和按钮/图像的容器。页脚是我放置图像/按钮的地方,你可以点击它。该图是我放置实际模型图像的地方,不需要更改。 到目前为止,这个问题一直试图找到一种方法来改变特定模型的分数值。我试图让图像本身有一个属性来做onClick,但这并没有奏效,我愿意尝试一切让它工作。 不幸的是,我所知道的就是如何在修改属性值后使用aFile.save()操作views.py中的字段。

views.py

from django.http import HttpResponse
from django.shortcuts import render, render
from .forms import MForm
from .models import MModel

#Imports for random files
import os, os.path
import random

def home_view(request):

    #This is stuff from previous work where I needed to be able to submit files as new models
    form = MForm(request.POST or None)
    if form.is_valid():
        form.save()

    #This is stuff from previous work where I needed to be able to submit files as new models
    if request.method == 'POST': 
        form = MForm(request.POST, request.FILES)
        if form.is_valid(): 
                form.save()

    #Grab all models from MModel
    object_list = MModel.objects.all()

    #Get unique file 1
    file1 = random.choice(object_list)

    #Get unique file 2
    file2 = random.choice(object_list)
    while(file2 == file1):
        file2 = random.choice(object_list)

    #Get unique file 3
    file3 = random.choice(object_list)
    while(file3 == file1 or file3 == file2):
        file3 = random.choice(object_list)

    context = {
        'form': form,
        'f1': file1,
        'f2': file2,
        'f3': file3,
    }

    return render(request, "index.html", context)

问题来源StackOverflow 地址:/questions/59383105/django-using-the-html-to-change-a-django-model

展开
收起
kun坤 2019-12-27 11:23:06 536 0
1 条回答
写回答
取消 提交回答
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
《零基础HTML入门教程》 立即下载
天猫 HTML5 互动技术实践 立即下载
天猫HTML5互动技术实践 立即下载