我在Windows上的mysql 5.6.16上运行了一个django 1.11.4应用程序。当我添加新数据或更新现有数据时,新信息在我重新启动之后才会显示。我尝试按照建议的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 %}
答案 0 :(得分:0)
因此,如下所示更改MemberDirectory 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(),
}
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)
简单地说,之前的listview在对数据库进行更改之前使用了包含缓存数据的查询集。