单击该按钮,然后将当前时间和默认值保存在数据库中(Django)

时间:2019-02-13 06:19:56

标签: python django button

单击浏览器中的“添加”按钮时,它将自动将名称(模块1),当前日期和位置(部门1)保存到数据库中。

到目前为止,这是我的代码:

models.py

from django.db import models
from django.utils import timezone

class Alert(models.Model):
    module = models.ForeignKey(Module, on_delete = models.CASCADE, default='Module 1')
    date = models.DateTimeField(default = timezone.now)
    location = models.CharField(max_length=10, default='Sector 1')

    def __str__(self):
        return self.module

views.py

from django.shortcuts import render
from django.contrib import messages
from django.views.generic import ListView
from .models import Alert, Module
from .forms import AlertForm

def home(request):
    context = {
        'modules': Module.objects.all(),
        'alerts': Alert.objects.all(),
    }

    if request.method == 'POST':
        form = AlertForm(request.POST or None)
        if form.is_valid():
            form.save()
            messages.success(request, ('Item has been successfully added to the database!'))
            return render(request, 'home/home.html', context)
    return render(request, 'home/home.html', context)

def alert(request, module_id):
    try:
        mdl = Module.objects.get(id=module_id)
    except Module.DoesNotExist:
        mdl = None

    context = {
        'module': mdl,
        'alerts': Alert.objects.all()
    }
    return render(request, 'home/alert.html', context)

home.html

<div class="container">
    <form method="POST">{% csrf_token %} 
        <input type="submit" value="Add">
    </form>
</div>

更新: 这是我的urls.py

代码
from django.urls import path
from . import views
from .views import AlertListView

urlpatterns = [
    path('', views.home, name='home'),
    path('alert/<int:module_id>/', views.alert, name='module'),
]

1 个答案:

答案 0 :(得分:0)

尝试一下:

Views.py

  

已更新,已测试-有效

def home(request):
    if request.method == 'POST':
        form = AlertForm(request.POST or None)
        if form.is_valid():
            abc = form.save(commit=False)
            abc.save()
            messages.success(request, ('Item has been successfully added to the database!'))
            return redirect('home')
    return render(request, 'home/home.html', {'form':form})

html

<form method='post'>{% csrf_token %}

    {{ form.as_p }}

    <input type="submit" value="Submit">

</form>

将此添加到您的 home.html

{% if messages %}
  <ul class="messages">
    {% for message in messages %}
      <li class="{{ message.tags }}">{{ message }}</li>
    {% endfor %}
  </ul>
{% endif %}