Django没有显示来自数据库的更新数据
Posted
技术标签:
【中文标题】Django没有显示来自数据库的更新数据【英文标题】:Django not showing updated data from database 【发布时间】:2018-02-08 14:45:21 【问题描述】:我有一个 django 1.11.4 应用程序在 windows 上的 mysql 5.6.16 上运行。当我添加新数据或更新现有数据时,直到我重新启动后才会显示新信息。我已经尝试按照here 的建议提供 db_name,但它并没有解决我的问题。
我还能如何解决这个问题? 我正在使用 django 附带的默认 Web 服务器。 我的完整模型如下图
class Member(AbstractUser):
first_name = models.CharField(verbose_name=_('First Name'), blank=False, max_length=100)
last_name = models.CharField(verbose_name=_('Last Name'), blank=False, max_length=100)
member_number = models.IntegerField(blank=False, unique=True)
national_id = models.IntegerField(verbose_name=_('National ID Number'), blank=False, unique=True)
phone_number = models.CharField(max_length=50, verbose_name=_('Phone Number'))
email = models.EmailField(verbose_name=_('Email'), unique=True, max_length=100, blank=False)
username = models.CharField(verbose_name=_('User name'), max_length=50, blank=True, null=True)
position = models.CharField(verbose_name=_('Position in Society'),
max_length=100,
choices=(
('MEMBER', 'Member'), ('COMMITTEE', 'Committee'), ('STAFF', 'Staff'),
))
employer = models.CharField(verbose_name=_('Employer'), max_length=250, blank=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['member_number', 'national_id', 'first_name', 'last_name']
class Meta:
verbose_name = _('member')
verbose_name_plural = _('members')
db_table = 'members_member'
def get_short_name(self):
return self.last_name
def __str__(self):
return self.get_full_name()
我的数据库连接设置如下所示
DATABASES =
'default':
'ENGINE': 'django.db.backends.mysql',
'NAME': 'open_db',
'USER': 'root',
'PASSWORD': 'rootpass',
'HOST': 'localhost',
'PORT': '3306',
这是创建成员的 views.py 类
class CreateMember(LoginRequiredMixin, PermissionRequiredMixin, CreateView):
model = Member
form_class = MemberCreationForm
permission_required = ('members.add_member',)
permission_denied_message = "Permission denied"
def get(self, request, *args, **kwargs):
return render(request, 'members/create_member.html', 'form': self.form_class)
def post(self, request, *args, **kwargs):
form = MemberCreationForm(data=request.POST,)
if form.is_valid():
form.save()
messages.success(self.request, 'Success, member was added.', extra_tags='alert alert-success')
return redirect(to='/members/directory')
else:
messages.error(self.request, 'Errors occurred.', extra_tags='alert alert-danger')
return render(request, 'members/create_member.html', 'form': form)
然后是上面视图中使用的forms.py中使用的表单
class MemberCreationForm(UserCreationForm):
def __init__(self, *args, **kwargs):
super(MemberCreationForm, self).__init__(*args, **kwargs)
self.fields['email'].widget.attrs['class'] = 'form-control'
self.fields['first_name'].widget.attrs['class'] = 'form-control'
self.fields['last_name'].widget.attrs['class'] = 'form-control'
self.fields['national_id'].widget.attrs['class'] = 'form-control'
self.fields['member_number'].widget.attrs['class'] = 'form-control'
self.fields['phone_number'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.attrs['class'] = 'form-control'
self.fields['email'].widget.attrs.pop("autofocus", None)
class Meta(UserCreationForm.Meta):
model = Member
fields = ('email', 'first_name', 'last_name', 'national_id', 'member_number', 'phone_number',)
然后是添加新成员后我重定向到的views.py中的ListView。
class MemberDirectory(LoginRequiredMixin, ListView, FormView):
model = Member
template_name = 'members/directory.html'
paginate_by = 5
try:
context =
'total_members': Member.objects.all().count(),
'active_members': Member.objects.filter(is_active=True).count(),
'staff_members': Member.objects.filter(is_staff=True).count(),
'members_list': Member.objects.all().order_by('-date_joined')
except Exception:
context =
def get(self, request, *args, **kwargs):
return render(request, self.template_name, self.context)
def post(self, request, *args, **kwargs):
member_number = int(self.request.POST['member_number'])
if not member_number or not isinstance(member_number, int):
messages.error(request, 'errors occured ...', 'alert alert-danger')
return render(request, self.template_name, self.context)
self.context['members_list'] = Member.objects.filter(member_number__exact=member_number)
return render(request, self.template_name, self.context)
最后是列出数据库中所有成员的 directory.html 模板。
% if members_list.count > 0 %
% include 'members/filters-form.html' %
<table class="table table-responsive table-striped">
<thead>
<th>Name</th><th>Member number</th><th>Email</th><th>Phone</th><th>Actions</th>
</thead>
<tbody>
% for member in members_list %
<tr id="member-actions-tr">
<td>
<a title="% if member.is_active %Active member% else %Inactive member% endif %" href="% url 'members:member-details' pk=member.pk %">
<span class="glyphicon glyphicon-% if member.is_active %ok% else %alert% endif %" aria-hidden="true"></span>
member.get_full_name
</a>
</td>
<td> member.member_number </td>
<td> member.email </td>
<td> member.phone_number </td>
<td>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Select <span class="caret"> </span>
</button>
<ul class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenu2" style="margin-top: 0px;">
<li><a href="% url 'payments:pay' member_id=member.pk %">Make payment</a></li>
<li><a href="#" class="" data-toggle="modal" data-target="#delete-member- member.pk "> Delete </a></li>
</ul>
</div>
</td>
</tr>
% endfor %
</tbody>
</table>
% else %
<div class="panel panel-info"> No members were found. </div>
% endif %
【问题讨论】:
这似乎很不寻常。你能举个例子说明数据是如何不更新的吗? minimal reproducible example 例如,如果我添加了一个新成员,然后转到所有成员列表,则新成员不会出现。当我通过 phpmyadmin 添加新成员时,也会发生同样的情况。新数据只有在我重新启动 django 服务器后才会显示。 我试过从mysql切换到sqlite3。同样的问题仍然存在。 这不是一个完整且可验证的示例。您应该添加一些用于尝试添加成员和检索列表的代码。数据库交互有很多步骤,我们无法从模糊的描述中知道会发生什么。 @HåkenLid 感谢您一直以来的支持。我刚刚添加了更多我正在使用的代码。请让我知道它是否足够。谢谢。 【参考方案1】:这真的很容易。答案在文档here 和here 中。
因此,如下所示更改 MemberDirectory 列表视图确实有效!
class MemberDirectory(LoginRequiredMixin, ListView, FormView):
model = Member
template_name = 'members/directory.html'
paginate_by = 5
try:
context =
'total_members': Member.objects.all().count(),
'active_members': Member.objects.filter(is_active=True).count(),
'staff_members': Member.objects.filter(is_staff=True).count(),
except Exception:
context =
def get(self, request, *args, **kwargs):
self.context['members_list'] = Member.objects.all().order_by('-date_joined')
return render(request, self.template_name, self.context)
def post(self, request, *args, **kwargs):
member_number = int(self.request.POST['member_number'])
if not member_number or not isinstance(member_number, int):
messages.error(request, 'errors occured ...', 'alert alert-danger')
return render(request, self.template_name, self.context)
self.context['members_list'] = Member.objects.filter(member_number__exact=member_number)
return render(request, self.template_name, self.context)
简单地说,之前的列表视图使用了一个查询集,该查询集包含对数据库进行更改之前的缓存数据。
【讨论】:
而你遇到麻烦的主要原因是因为你使用了所有这些mixin,然后自己做。如果使用普通的get_context_data
方法,您就不会出现这种情况。
@Melvyn 您将如何使用get_context_data
以及get
和post
方法重写MemberDirectory 类?以上是关于Django没有显示来自数据库的更新数据的主要内容,如果未能解决你的问题,请参考以下文章
我在反应本机应用程序中使用 redux 来获取和显示数据,但它没有更新来自后端的数据更改