我对Django相当陌生,并且遵循youtube上CodingEntrepreneurs的try django 1.10系列,因此无法解决问题。我只看到提交按钮,而输入字段没有显示。下面是我正在处理的代码。
forms.py
from django import forms
class SubmitUrlForm(forms.Form):
url = forms.CharField(label="Submit Url")
views.py
from .forms import SubmitUrlForm
def home_view_fbv(request, *args, **kwargs):
if request.method == 'POST':
print(request.POST)
return render(request, "app/home.html", {})
class HomeView(View):
def get(self, request, *args, **kwargs):
the_form = SubmitUrlForm()
context = {
"title": "Submit Url",
"form": the_form
}
return render(request, "app/home.html", context)
def post(self, request, *args, **kwargs):
form = SubmitUrlForm(request.POST)
if form.is_valid():
print(form.cleaned_data)
return render(request, "app/home.html", {})
app / home.html
<div style= 'width: 800px; margin: 0 auto;'>
<h1> {{ title }} </h1>
<form method = 'POST' action = '.'> {% csrf_token %}
{{form.as_p}}
<input type= 'submit' value= 'Shorten' >
</form>
</div>
models.py
from django.db import models
from .utils import code_generator, create_shortcode
from django.conf import settings
SHORTCODE_MAX = getattr(settings, "SHORTCODE_MAX", 15)
class surlShortManager(models.Manager):
def all(self, *args,**kwargs):
qs_main = super(surlShortManager,self).all(*args, **kwargs)
qs = qs_main.filter(active = True)
return as
def refresh_shortcodes(self, items= 100):
qs = surlShort.objects.filter(id__gte = 1)
if items is not None and isinstance(items, int):
qs = qs.order_by('-id')[:items]
new_codes = 0
for q in qs:
q.shortcode = create_shortcode(q)
print(q.id)
q.save()
new_codes += 1
return "New codes made: {i}".format(i = new_codes)
class surlShort(models.Model):
url = models.CharField(max_length = 500)
shortcode = models.CharField(max_length = SHORTCODE_MAX, unique = True, null
= False, blank = True)
updated = models.DateTimeField(auto_now = True)
timestamp = models.DateTimeField(auto_now_add = True)
active = models.BooleanField(default = True)
objects = surlShortManager()
def save(self, *args, **kwargs):
if self.shortcode is None or self.shortcode == '':
self.shortcode = code_generator()
super(surlShort, self).save(*args, **kwargs)
def __str__(self):
return str(self.url)
答案 0 :(得分:1)
将HomeView更改为此
from django.views import View
from django.http import HttpResponseRedirect
from .forms import SubmitUrlForm
class HomeView(View):
form_class = SubmitUrlForm
context = {
"title": "Submit Url",
"form": form_class
}
template_name = 'app/home.html'
def get(self, request, *args, **kwargs):
return render(request, self.template_name, context)
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
print(form.cleaned_data)
return HttpResponseRedirect('/success/')
return render(request, self.template_name, context)