UpdateView 提供空白/空表单,而不是我编辑的以前的数据

Posted

技术标签:

【中文标题】UpdateView 提供空白/空表单,而不是我编辑的以前的数据【英文标题】:UpdateView gives blank/empty forms instead of previous data I edit 【发布时间】:2018-05-12 04:21:45 【问题描述】:

我正在使用 UpdateView 使用表单来编辑数据。

但是,当我单击编辑按钮时,表格是空白/空的,没有以前的数据。

我什至添加了 % with server.id as server_id % % with forms.id as edit_form % 在我的 index.html.. 任何人都知道我错过了什么吗?

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(带有编辑按钮的部分)-

                % 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>

&nbsp&nbsp&nbsp&nbsp
            <button type="button" class="btn btn-outline-danger" data-toggle="modal" href="#delete-server-server.id"
             data-target="#Delserver.id">Delete <i class="fa fa-trash-o"></i></button>&nbsp
            <button type="button" class="btn btn-outline-primary" data-toggle="modal" href="#edit-server-server.id"
             data-target="#Editserver.id"> &nbsp&nbspEdit&nbsp           <i class="fa fa-pencil"></i></button>
&nbsp






                        <div id ="Delserver.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">&times;</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="Editserver.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">&times;</span>
                                </button>
                        </div>
                                <div class="modal-body">

                                                                    % with server.id as server_id %
                                                                    % with forms.id as edit_form %

                                <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">
                            &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                            <h2><button type="submit" class="save btn btn-success btn-lg">Confirm</button></h2>&nbsp&nbsp&nbsp
                                <h2><button type="submit" class="btn btn-secondary btn-lg" data-dismiss="modal">Cancel</button></h2>
                     </div>
                </form>
                % endwith %
                % endwith %
            </td>
                </div>
        </tr>
                % endfor %
    </tbody>
</h5>
    </table>

【问题讨论】:

【参考方案1】:

您的示例中存在一些问题。

首先,您不是在复制状态。

现在,您创建的每个表单每次都将其值设置为None。这意味着您的输入将始终为空。您当前的方法确实需要替换 form 实例并手动创建 &lt;input 标记,或者重新考虑 modelforms paradigm。

其次,您没有有效的标记。

这会破坏大多数浏览器。例如,您有

<small><b> field.html_name <p align="left"></b>  field </small> </p>

这应该是:

 <small><b> field.html_name </b></small> <p align="left"> field  </p>

注意标签现在是如何平衡的?或者,甚至更好:

 <small>
   <strong> field.html_name </strong>
 </small>
 <p align="left"> field </p>

现在您可以清楚地看到标签的结构,从而更容易诊断任何问题。

第三,你使用过时的标签。

&lt;center&gt; 自 HTML 4 以来一直不是有效节点。&lt;b&gt; 不明智。请改用&lt;strong&gt;

第四,你有无效的字符序列。

&amp;nbsp&amp;nbsp 应该是&amp;nbsp;&amp;nbsp;

最后,调试代码也遍布各处。

与您已有的相比,这为您提供的东西很少,并且有破坏东西的风险:

<!--<center>     form.as_p  </center> -->

【讨论】:

太棒了。惊人的答案..我需要解决很多事情,我会做到的。但是表格问题..这就是我不明白的!我写了表单[post.id] = HomeForm(instance=post) 您能给我在索引和表单中需要更改的行吗?

以上是关于UpdateView 提供空白/空表单,而不是我编辑的以前的数据的主要内容,如果未能解决你的问题,请参考以下文章

Django 1.8 UpdateView 生成 405 错误和空白模板

如何在无需重新定义整个表单的情况下使用带有通用 UpdateView 的自定义小部件?

在UpdateView上获取删除按钮以重定向时出现问题

空白日期参数而不是使用“允许空”复选框

为啥javascript触发提交表单(方法获取,目标空白)打开弹出窗口而不是新标签?

Django 空请求对象