无法在我的模态上显示表单 - Django

问题描述 投票:0回答:1

我试图让我的模式包含一个可以将任务添加到待办事项列表的表单。我尚未对表格进行更改以使其正常工作。我只想让表单显示在我的模态上。

这是我正在制作的一个待办事项列表网站,我想要一个模式,我可以通过导航栏下拉菜单中的模式直接输入我的任务详细信息。

非常感谢任何帮助

views.py:

from django.shortcuts import render
from .models import to_do
from .forms import AddTaskForm

def add_task(request):
    form = AddTaskForm()
    return render(request, 'navbar.html', {'form': form})

模型.py

from django.db import models

class to_do(models.Model):
    title = models.CharField('Title', max_length=120)
    description = models.TextField(blank=True)
    created_on = models.DateTimeField('Created On')
    due_by = models.DateTimeField('Due By')
    status = models.BooleanField('Status', default=False)

    def __str__(self):
        return self.title

表格.py

from django import forms
from django.forms import ModelForm
from .models import to_do

class AddTaskForm(ModelForm):
    class Meta:
        model = to_do
        fields = ("title", "description", "created_on", "due_by")

url.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('to-do', views.to_do_list, name='list'),
]

navbar.html

{% load static %}

<nav class="navbar navbar-expand-lg bg-tertiary nav justify-content-center" style="background: linear-gradient(to top, #5A99FF, #3D5AFE);">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
            <!--<img src="{% static 'to-do-list.svg' %}" alt="To-Do List">--> To-Do
          </a>
          <ul class="dropdown-menu">
            <li><a class="dropdown-item" href="{% url 'list' %}" style="color: #000000 !important;"> To-Do List </a></li>
            <li><a class="dropdown-item" href="#" style="color: #000000 !important;" data-bs-target="#AddTaskForm" data-bs-toggle="modal"> Add Task </a></li>
          </ul>
          <div class="modal fade" id="AddTaskForm" aria-hidden="true" aria-labelledby="AddTaskFormLabel" tabindex="-1">
            <div class="modal-dialog modal-dialog-centered">
              <div class="modal-content">
                <div class="modal-body">
                  <form action="" method=POST>
                    {% csrf_token %}


                    {{ form.as_p }}
                    <input type="submit" value="Submit" class="btn btn-success">
                  </form>
                </div>
              </div>
            </div>
          </div>
        </li>
      </ul>
    </div>
  </div>
</nav>
</br>





<style>
  .navbar-nav li a,
  .navbar-brand,
  .navbar-toggler-icon {
    color: #FFFFFF !important;
  }
</style>
python django django-forms bootstrap-5
1个回答
0
投票

我会尽力为您指明正确的方向,您可能已经知道......完成任务的方法不止一种。

首先,我会更改views.py:

class AddToDo(View):
    def __build_context(self, form):       
        return  {
            'form': form,
            # whatever else you need...
        }

    def __get_initial_parameters(self, request):
        return {
            # here you can initialize form dropdowns and other 
            # fields however you want them to appear when a user 
            # first visits the form/page (for instance your 
            # datetime fields could be prefilled with current 
            # date and time
    }

    def get(self, request):
        request.session.setdefault('back_url',request.META.get('HTTP_REFERER'))
        request.session['back_url'] =request.META.get('HTTP_REFERER')

        form =AddTaskForm(initial=self.__get_initial_parameters(request))

       context = self.__build_context(form)
       return render(request, 'navbar.html', context)

    def post(self, request):
        form = AddTaskForm(request.POST, 
        initial=self.__get_initial_parameters(request))

        if form.is_valid():
            form.save()
            return redirect(request.session['back_url'])

        # Form was not valid, rebuild context
        context = self.__build_context(form)
        return render(request, 'navbar.html', context)

然后,更改您的表单,以便通过在元数据下方添加 init 来按照您想要的方式初始化它:

from django import forms
from django.forms import ModelForm
from .models import to_do

class AddTaskForm(ModelForm):
    class Meta:
        model = to_do
        fields = ("title", "description", "created_on", "due_by")

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # since it sounds like you'll be assigning tasks with due # dates, you'll want to know when a task is being created
# and when a task is already created... I recommend using 'instance'
        instance = getattr(self, 'instance', None)

        if instance or instance.pk:
            # this is for all forms... so task already exist.. important because you can lock fields this way to prevent users 
            # from changing things (i.e.)
            self.fields['title'].label = 'Name your task'
            self.fields['title'].required = True
            self.fields['title'].readonly = True
            # etc...
            # do this with all your fields that you've included on your form... as you deem necessary

        if not instance.pk:
            # this is for the creation of Brand New Tasks...
            self.fields['title'].label = 'Name your task'
            self.fields['title'].required = True
            self.fields['title'].readonly = False
            # etc...
            # do this with all your fields that you've included on your form... as you deem necessary
    

然后,在你的 urls.py 中:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('todo', views.to_do_list.as_view(), name='todolist'),
]

对于你的 html...我建议研究 django 的表单模板: https://docs.djangoproject.com/en/5.0/ref/templates/language/

我希望这有帮助。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.