简体   繁体   English

从django中的模型链接2个字段

[英]Link 2 fields from a model in django

I am relatively new to Django and I made a Todo list where user can add a task and mark if its completed. 我是Django的新手,我制作了一个Todo列表,用户可以在其中添加任务并标记是否已完成。 I added a form field of priorities which is a radio select widget. 我添加了一个优先级的表单字段,这是一个无线电选择小部件。 Based on the priority the task field will have red, orange or green color. 根据优先级,任务字段将具有红色,橙色或绿色。

The radio buttons appear correctly and I cant post a task without giving an input priority. 单选按钮正确显示,我无法发送任务而不提供输入优先级。 But the priority is always taken as default(high). 但优先级始终被视为默认值(高)。

I tried a couple of things to change and display the priorities but nothing worked. 我尝试了一些改变和显示优先级但没有任何效果的东西。 I believe something in the views.py is to be modified to make it work but due to my lack of experience I cannot put a finger on it. 我相信views.py中的某些内容会被修改以使其正常工作,但由于我缺乏经验,我无法指责它。

Views.py Views.py

@require_POST
def addTodo(request):
    form = TodoForm(request.POST)

    #print(request.POST['text'])

    if form.is_valid():
        new_todo = Todo(text = request.POST['text'])
        new_todo.save()

    for item in form:


    return redirect('index')

def completeTodo(request, todo_id):
    todo = Todo.objects.get(pk=todo_id)
    todo.complete = True
    todo.save()

    return redirect('index')

form.py form.py

    from django import forms

prior_choice =[('high','High'),('mod','Mod'),('low','Low')]
class TodoForm(forms.Form):
    text = forms.CharField(max_length = 40,
        widget = forms.TextInput(
            attrs= {'class': 'form-control', 'placeholder': 'Enter todo e.g. Delete junk files', 'aria-label': 'Todo', 'aria-describedby':'add-btn'}))
    priority = forms.CharField(widget=forms.RadioSelect(choices=prior_choice))

models.py models.py

from django.db import models

class Todo(models.Model):
    text = models.CharField(max_length=40)
    complete = models.BooleanField(default = False)
    task_priority = models.CharField(max_length=40, default='high')
    def __str__(self):
        return self.text

index.html 的index.html

 <ul class="list-group t20"> {% for todo in todo_list %} {% if todo.task_priority == 'high'%} <a href=" {% url 'complete' todo.id %}" ><li class="list-group-item " style="background-color: red;"> {{ todo.text}}</li></a> {%elif todo.task_priority == 'mod'%} <a href=" {% url 'complete' todo.id %}" ><li class="list-group-item " style="background-color: orange;"> {{ todo.text}}</li></a> {%elif todo.task_priority == 'low'%} <a href=" {% url 'complete' todo.id %}" ><li class="list-group-item " style="background-color: yellow;"> {{ todo.text}}</li></a> {%else%} <div class="todo-completed"> <li class="list-group-item" style="background-color: green;"> {{ todo.text}}</li></div> {%endif%} {% endfor %} </ul> 

Heres a screenshot of the output app 下面是输出应用程序的屏幕截图

Please help me link the radio button to a task in the list and display accordingly. 请帮我链接单选按钮到列表中的任务并相应显示。 Thanks in advance. 提前致谢。

The problem is in your view. 问题出在您看来。 While you are creating your Todo object you are not passing the priority. 在创建Todo对象时,您没有传递优先级。

       new_todo = Todo(text = request.POST['text'], task_priority = request.POST['priority'])

The code above solves your problem. 上面的代码解决了您的问题。 But I DO NOT RECOMMEND it. 但我不推荐它。 You are not leveraging the Django forms. 你没有利用Django表格。 Please use Django forms.cleaned_data to get parameters instead of request.POST or use ModelForm which will allow you to save from form instance directly. 请使用Django forms.cleaned_data获取参数而不是request.POST或使用ModelForm,它允许您直接从表单实例保存。


Model Change Advice 模型变更建议

However this is not how i would like solve the issue. 然而,这不是我想要解决的问题。 You can change your model as following to have more djangoic way of doing it: 您可以按照以下方式更改模型,以获得更多的djangoic方法:

from django.utils.translation import ugettext_lazy as _

class Todo(models.Model):
    PRIORITY_NONE = 0
    PRIORITY_LOW = 1
    PRIORITY_MODERATE = 2
    PRIORITY_HIGH = 3
    PRIORITIES = (
        (PRIORITY_NONE, _('')),
        (PRIORITY_LOW, _('Low')),
        (PRIORITY_MODERATE, _('Moderate')),
        (PRIORITY_HIGH, _('High')),
    )
    ...
    task_priority = models.PositiveSmallIntegerField(choices=PRIORITIES, default=PRIORITY_NONE)

You may need to change your form with the choices Todo.PRIORITIES . 您可能需要使用选项Todo.PRIORITIES更改表单。 Also you may want to use ModelForm which will make things much easier for you. 此外,您可能希望使用ModelForm ,这将使您更容易。

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

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