使用示例在django表单中无法编辑记录

2jcobegt  于 2022-11-18  发布在  Go
关注(0)|答案(2)|浏览(156)

使用以下方法时,数据库中的模型未更新。
这是视图中上载表单

def upload(request):
if request.method == 'POST':
    form = UploadForm(request.POST, request.FILES)
    if form.is_valid():
        upload = form.save(commit= False)
        upload.user = request.user
        upload.save()
        messages.info(request,"Added Successfully..!")
    return redirect("home")
return render(request, "upload.html", {'form': UploadForm})

这是我在视图中的编辑功能

def editbug(request, pk):
edit = bug.objects.get(id=pk)

if request.method == 'POST':
    form = UploadForm(request.POST, instance= edit)
    if form.is_valid():
        form.save()
        print("uploaded")
    messages.info('Record updated successfully..!')
    return redirect("home")
else:
    form = UploadForm(instance= edit)

return render(request, "upload.html", {'form': form})

urls.py

urlpatterns = [
    path('home',views.home, name='home'),
    path('index',views.index, name='index'),
    path("records/<int:pk>/", views.records, name="records"),
    path("", views.login_request, name="login"),
    path("logout", views.logout_request, name="logout"),
    path("upload", views.upload, name='upload'),
    path("edit/<int:pk>/", views.editbug, name="edit")
]

相关模板:

{% for bug in b %}
 <tr>
 <td>{{ forloop.counter }}</td>
 <td><a href="{% url 'records' pk=bug.pk %}">{{bug.name}}</a> 
</td>
<td>{{bug.created_at}}</td>
<td>{{bug.user}}</td>
<td>{{bug.status}}</td>
<td><a class="btn btn-sm btn-info" href="{% url 'edit' bug.id 
 %}">Edit</a></td>
</tr>
{% endfor %}

这是用于编辑表单的模板

<!DOCTYPE html>
<html>
<head>
<style>
table {
 font-family: arial, sans-serif;
 border-collapse: collapse;
 width: 60%;
 margin-left: auto;
 margin-right: auto;
 }
td, th {
border: 1px solid #dddddd;
 text-align: left;
  padding: 8px;
 }

tr:nth-child(even) {
background-color: #dddddd;
}

</style>
</head>
 <body>

<h2 style="text-align: center;">Bug List</h2>

<table>
<tr>
<th style="width: 5%;">Sl no.</th>
<th>Bug</th>
<th style="width: 20%;">Created at</th>
<th>Created by</th>
<th>Status</th>
</tr>
{% block content %}
{% for bug in b %}
<tr>
<td>{{ forloop.counter }}</td>
<td><a href="{% url 'records' pk=bug.pk %}">{{bug.name}}</a> 
</td>
<td>{{bug.created_at}}</td>
<td>{{bug.user}}</td>
<td>{{bug.status}}</td>
<td><a class="btn btn-sm btn-info" href="{% url 'edit' bug.id 
%}">Edit</a></td>
</tr>
  {% endfor %}
 {% endblock %}
 </table>

</body>
</html>

这是用于创建和编辑表单的上载表单。

class UploadForm(ModelForm):
name = forms.CharField(max_length=200)
info = forms.TextInput()
status = forms.ChoiceField(choices = status_choice, widget= 
forms.RadioSelect())
fixed_by = forms.CharField(max_length=30)
phn_number = PhoneNumberField()
#created_by = forms.CharField(max_length=30)
#created_at = forms.DateTimeField()
#updated_at = forms.DateTimeField()
screeenshot = forms.ImageField()

class Meta:
    model = bug
    fields = ['name', 'info', 'status', 'fixed_by', 
    'phn_number', 'screeenshot']

已尝试编辑记录,但未更新。请检查视图、模板和URL。

57hvy0tb

57hvy0tb1#

我有以下建议:
1.仅在表单有效时重定向。
1.编辑时也使用request.FILES
1.使用get_object_or_404()而不是get()
所以,上传视图应该是:

def upload(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            upload = form.save(commit= False)
            upload.user = request.user
            upload.save()
            messages.info(request,"Added Successfully..!")
            return redirect("home") #Only redirect if the form is valid.
    else:
        form=UploadForm()
    return render(request, "upload.html", {'form': form})

编辑视图应为:

def editbug(request, pk):
    edit = get_object_or_404(bug, id=pk)

    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES, instance= edit)
        if form.is_valid():
            form.save()
            print("uploaded")
            messages.info('Record updated successfully..!')
            return redirect("home")
    else:
        form = UploadForm(instance=edit)

    return render(request, "edit.html", {'form': form})

**注:**型号以PascalCase编写,因此最好将其命名为Bug,而不是bug

制作单独的模板进行编辑,例如edit.html

<body>
    <form method='POST'>
        {% crsf_token %}
        {{form.as_p}}
        <input type='submit'>
    </form>
</body>
wlzqhblo

wlzqhblo2#

也可以试试这样:
views.py:

def update(request, id):  
    edit = bug.objects.get(id=id)  
    form = Formname(request.POST,instance=edit)  
    if form.is_valid():  
       form.save()  
       return HttpResponseRedirect('/')  
    return render(request,'edit.html',{'edit': edit})

在模板中:
edit.html:

<form method='post' action=/update/{{edit.id}}>
   {% csrf_token %}
  <input value={{edit.fieldname}}/>
  <input type="submit"/>
</form>

urls.py:

path('update/<int:id>/',views.update)

相关问题