我使用主页构建了两个应用程序,用于普通博客的应用程序博客和用于异步消息传递的应用程序twit。表单已确认为已发布且也有效,但数据库未更新。
我的第一个猜测是用户和内容没有关联,并且尝试了很多徒劳的方法,希望能得到你们的帮助,谢谢
以下是代码:
主页:
<form method="POST" id="twit" action={% url 'twit:create' %}>
{% csrf_token %}
{{form|crispy}}
<div class="form-group">
<button type="submit">Post</button>
</div>
</form>
博客/观看次数:
def home_view(request):
form = TwitForm()
post_list = Post.objects.all()
context = {
'form': form,
'post_list':post_list,
}
return render(request, 'blog/blog_list.html', context)
twit /视图:
def twit_create(request):
if request.method == 'POST':
form = TwitForm(request.POST or None, instance=request.user)
print('inside post')
if form.is_valid():
print('inside valid')
form.save()
return redirect('blog:home')
else:
print('inside else')
form = TwitForm(instance=request.user)
post_list = Post.objects.all()
context = {
'post_list': post_list,
'form': form,
}
return render(request, 'blog/blog_list.html', context)
from django import forms
from .models import Twit
class TwitForm(forms.ModelForm):
class Meta:
model = Twit
fields = ['message']
twit /模型
from django.db import models
from django.contrib.auth.models import User
class Twit(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
message = models.TextField(max_length=100)
published = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = 'twits'
ordering = ['-published']
verbose_name = 'twit'
def __str__(self):
return self.message[:10]
twit /表格
from django import forms
from .models import Twit
class TwitForm(forms.ModelForm):
class Meta:
model = Twit
fields = ['message']
终端:
inside post
inside valid
[07/Feb/2019 21:23:21] "POST /twit/create/ HTTP/1.1" 302 0
[07/Feb/2019 21:23:21] "GET / HTTP/1.1" 200 10548
[07/Feb/2019 21:37:33] "GET / HTTP/1.1" 200 10722