gpt4 book ai didi

mysql - Django 不显示来自数据库的更新数据

转载 作者:行者123 更新时间:2023-11-28 23:11:01 25 4
gpt4 key购买 nike

我有一个 django 1.11.4 应用程序在 Windows 的 mysql 5.6.16 上运行。当我添加新数据或更新现有数据时,新信息直到我重新启动后才会显示。我已尝试按照建议提供 db_name here但它并没有解决我的问题。

我还能如何解决这个问题?我使用的是 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})

然后是上面 View 中使用的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>
&nbsp;{{ 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 %}

最佳答案

真的很简单。答案在文档中 herehere .

因此,如下所示更改 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 使用的查询集包含对数据库进行更改之前的缓存数据。

关于mysql - Django 不显示来自数据库的更新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45967983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com