欢迎朋友
我需要你的帮助。
我无法从表单中将数据保存到我的数据库中。
当然可能很简单,但我不知道如何做到这一点。
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.product_list, name='product_list'),
url(r'^busy/', views.product_busy, name='product_busy'),
]
models.py
from django.db import models
from django.core.urlresolvers import reverse
class Busy(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
verbose_name = 'busy'
verbose_name_plural = 'busy'
def __str__(self):
return self.nazwa
def get_absolute_url(self):
return reverse('konfigurator:product_busy',
args=[self.id, self.slug])
forms.py
from django import forms
from django.utils.translation import ugettext_lazy as _, ugettext
from crispy_forms import layout, bootstrap
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit, MultiField, Div, Field, Button
from .models import Busy
class Konfig(forms.ModelForm):
class Meta:
model = Busy
fields = ['name','slug']
def __init__(self, *args, **kwargs):
super(Konfig, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = "."
self.helper.form_method = "POST"
self.helper.form_class = 'order-form'
self.helper.layout = layout.Layout(
layout.Fieldset(
_("XXX"),
layout.Field("name"),
layout.Field("slug"),
),
bootstrap.FormActions(
layout.Submit("submit", _("Send"),
css_class="right"),
)
)
views.py
from django.shortcuts import render, get_object_or_404
from .models import Busy
from django.shortcuts import render
from .forms import Konfig
from django.conf import settings
from django.http import HttpResponse
from django.template.loader import render_to_string
def product_list(request):
return render(request,'konfig/product/list.html')
def product_busy(request):
return render(request,'konfig/product/busy.html', {'form': Konfig()})
def konfig(request):
form = Konfig()
return render(request, "konfig/product/busy.html", {'form': form})
busy.html
{% extends "konfig/base.html" %}
{% load crispy_forms_tags %}
{% crispy konfig_form konfig_form.helper %}
{% block title %}
XX
{% endblock %}
{% block content %}
<div class="order-info2">
{% crispy form %}
</div>
{% endblock %}
如何解决问题?
感谢您的帮助。
更新views.py
def konfig(request):
if request.method == 'POST':
form = Konfig(request.POST)
if form.is_valid():
name = form.save()
name.save()
name = Busy.objects.create(name=name)
return render(request,
'konfig/product/busy.html',
{'name': name})
else:
form = Konfig()
return render(request,
'konfig/product/busy.html',
{'form': form})
我尝试但它仍然无效。 也许与Context处理器有关。
答案 0 :(得分:2)
您正在初始化表单,没关系,但您不接受POST请求中的任何内容。
如果您在django中阅读有关http请求的更多信息,那就更好了。
无论如何,我做这样的事情......
def konfig(request):
if request.method == "POST":
form = Konfig(request.POST)
if form.is_valid():
form.save()
else:
form = Konfig()
return render ( request, 'your_template', {'form':form})