我有一個django 1.11.4應用程序運行在MySQL 5.6.16在Windows上。當我添加新數據或更新現有數據時,直到重新啓動後纔會顯示新信息。我試圖提供db_name建議here,但它並沒有解決我的情況。Django沒有顯示來自數據庫的更新數據
我該怎麼解決呢? 我正在使用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',
}
}
這是創建構件
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})
然後形式views.py類用於上述視圖中使用的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 %}
這看起來很不尋常。你能舉一個數據如何不更新的例子嗎? [mcve] –
例如,如果我添加一個新成員,則轉到所有成員的列表,新成員不會顯示。當我通過phpmyadmin添加新成員時會發生同樣的情況。新的數據只會在重新啓動django服務器後纔會顯示。 –
我試過從mysql切換到sqlite3。仍然存在同樣的問題。 –