我使用UpdateView使用表单编辑数据。
点击编辑后popup
使用模态显示带有空白数据的表单!它不会检索数据库中的先前数据。
任何人都知道我应该添加什么?
我坚持这个编辑大约一个星期:(
如果有人有线索,我将不胜感激! 谢谢!
view.py -
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.shortcuts import render, redirect
from django.template import RequestContext
from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView
from DevOpsWeb.forms import HomeForm
from DevOpsWeb.models import serverlist
from django.core.urlresolvers import reverse_lazy
from simple_search import search_filter
from django.db.models import Q
class HomeView(TemplateView):
template_name = 'serverlist.html'
def get(self, request):
form = HomeForm()
query = request.GET.get("q")
posts = serverlist.objects.all()
if query:
posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query))
else:
posts = serverlist.objects.all()
args = {'form' : form, 'posts' : posts}
return render(request, self.template_name, args)
def post(self,request):
form = HomeForm(request.POST)
posts = serverlist.objects.all()
if form.is_valid(): # Checks if validation of the forms passed
post = form.save(commit=False)
#if not form.cleaned_data['ServerName']:
#post.servername = " "
post.save()
#text = form.cleaned_data['ServerName']
form = HomeForm()
return redirect('serverlist')
args = {'form': form, 'text' : text}
return render(request, self.template_name,args)
class PostDelete(DeleteView):
model = serverlist
success_url = reverse_lazy('serverlist')
class PostEdit(UpdateView):
model = serverlist
#post = serverlist.objetcs.get(server_id=server_id)
fields = ['ServerName','Owner','Project','Description','IP','ILO','Rack','Status']
success_url=reverse_lazy('serverlist')
urls.py -
from django.conf.urls import url, include
from DevOpsWeb.views import HomeView
from DevOpsWeb.views import PostDelete
from DevOpsWeb.views import PostEdit
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
# Examples:
url(r'^$', HomeView.as_view(), name='serverlist'),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
#DevOpsWeb:8000/Delete/
url(r'^delete/(?P<pk>\d+)/$', PostDelete.as_view(), name="delete_post"),
url(r'^django_popup_view_field/', include('django_popup_view_field.urls', namespace="django_popup_view_field")),
url(r'^admin/', include(admin.site.urls)),
#DevOpsWeb:8000/edit/
url(r'^edit/(?P<pk>\d+)/$', PostEdit.as_view(), name="edit_post"),
]
forms.py -
from django import forms
from DevOpsWeb.models import serverlist
class HomeForm(forms.ModelForm):
ServerName = forms.CharField(widget=forms.TextInput,max_length = 30,required=False)
Owner = forms.CharField(max_length = 50,required=False)
Project = forms.CharField(max_length = 30,required=False)
Description = forms.CharField(max_length = 255,required=False)
IP = forms.CharField(max_length = 30,required=False)
ILO = forms.CharField(max_length = 30,required=False)
Rack = forms.CharField(max_length = 30,required=False)
Status = forms.CharField(max_length = 30,required=False)
class Meta:
model = serverlist
fields = ('ServerName' ,'Owner','Project','Description','IP','ILO','Rack','Status',)
class AutoCompleteModelChoiceField(forms.ModelChoiceField):
widget = forms.TextInput
def clean(self, value):
value = super(AutoCompleteModelChoiceField, self).clean(value)
return value
class serverForm(forms.ModelForm):
hotel = AutoCompleteModelChoiceField(queryset=serverlist.objects.all())
index.html(带编辑按钮的部分) -
<div class="modal fade bd-example-modal-sm" id="Edit{{server.id}}" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Server <b>{{ server.ServerName }}</b> </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="{% url 'edit_post' server.id %}" method="post"> {% csrf_token %}
<!--<center> {{ form.as_p }} </center> -->
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
<!-- {{ field.label_tag }} -->
<small><b>{{ field.html_name }}<p align="left"></b> {{ field }}</small> </p>
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
</div>
<div class="wrapper">
      
<h2><button type="submit" class="save btn btn-success btn-lg">Confirm</button></h2>   
<h2><button type="submit" class="btn btn-secondary btn-lg" data-dismiss="modal">Cancel</button></h2>
</div>
</form>
</td>
</div>
</tr>
{% endfor %}
帖子和编辑按钮:
{% for server in posts %}
<tr>
<div class ="server">
<td></td>
<td><center>{{ server.ServerName }}</center></td>
<td><center>{{ server.Owner }}</center></td>
<td><center>{{ server.Project }}</center></td>
<td><center>{{ server.Description }}</center></td>
<td><center>{{ server.IP }}</center></td>
<td><center>{{ server.ILO }}</center></td>
<td><center>{{ server.Rack }}</center></td>
<td><h4><span class="badge badge-success">{{ server.Status }}</span></h4></td></center>
<td>
    
<button type="button" class="btn btn-outline-danger" data-toggle="modal" href="#delete-server-{{server.id}}"
data-target="#Del{{server.id}}">Delete <i class="fa fa-trash-o"></i></button> 
<button type="button" class="btn btn-outline-primary" data-toggle="modal" href="#edit-server-{{server.id}}"
data-target="#Edit{{server.id}}">   Edit  <i class="fa fa-pencil"></i></button>
 
<div id ="Del{{server.id}}" class="modal fade" role="document">
<div class="modal-dialog" id="delete-server-{{server.id}}">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Delete Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="{% url 'delete_post' server.id %}" method="post">{% csrf_token %}
<h6>Are you sure you want to delete {{ server.ServerName }}?</h6>
<br>
<center><input type="submit" class="btn btn-danger btn-md" value="Confirm"/>
<button type="submit" class="btn btn-secondary" data-dismiss="modal">Cancel</button></center>
</form>
</div>
</div>
</div>
</div>
<div class="modal fade bd-example-modal-sm" id="Edit{{server.id}}" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Server <b>{{ server.ServerName }}</b> </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="{% url 'edit_post' server.id %}" method="post"> {% csrf_token %}
<!--<center> {{ form.as_p }} </center> -->
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
<!-- {{ field.label_tag }} -->
<small><b>{{ field.html_name }}<p align="left"></b> {{ field }}</small> </p>
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
</div>
<div class="wrapper">
      
<h2><button type="submit" class="save btn btn-success btn-lg">Confirm</button></h2>   
<h2><button type="submit" class="btn btn-secondary btn-lg" data-dismiss="modal">Cancel</button></h2>
</div>
</form>
</td>
</div>
</tr>
{% endfor %}
</tbody>
</h5>
</table>
答案 0 :(得分:2)
您没有使用要更新的实例初始化您的表单:
form = HomeForm()
而是当你想要一个表格填充来自对象的数据时:
form = HomeForm(instance=my_object_to_update)
由于您希望为post
中显示的每个HomeView
执行此操作,因此您需要为每个post
初始化不同的表单。在HomeView.get()
和HomeView.post()
方法中,除了创建用于创建新HomeForm()
的空serverlist
之外:
for post in posts:
forms[post.id] = HomeForm(instance=post)
在模板渲染中(假设你的循环{% for server in posts %}
)
{% with server.id as id %}
{% with forms|get_by_key:id as edit_form %}
<form action="{% url 'edit_post' server.id %}" method="post">
... display the form: your current code {% for field in edit_form %} etc...
</form>
{% endwith %}
{% endwith %}
我使用自定义模板过滤器|get_by_key:variable
在使用变量时按键获取dict值:
@register.filter(name='get_by_key')
def get_by_key(dictionnary, key):
"""Return element in dictionnary corresponding to `key`."""
return dictionnary[key] if isinstance(dictionnary, dict) else ''
由于您有一个模板来创建新的服务器列表,但是为了显示所有现有的服务器列表对象并更新它们,您需要两种形式。因此,创建上面的forms
dict是另外以创建表单HomeForm()
。你的上下文应该有:
args = {
'form': form, # this is the serverlist creation form (empty)
'forms': forms, # these are all the forms for existing instances
'posts': posts}
另外,我不知道PostEdit
您指定form_class
UpdateView
的位置,这是ActiveSheet.UsedRange.Rows.Count
工作所必需的。