首页 > 解决方案 > django 2.1 HTML表单提交到数据库错误

问题描述

我正在尝试将数据从 html 表单发布到我的数据库,但是我得到了 url 不存在的错误。我试图做的是稍后使用 HTML 和 Jquery 将测试表单转换为动态添加字段,而不是使用 formset 来简化 UI 设计并在 dango 后端处理它。

另请注意,我通过将其通过 url 传递给测试视图来分配作为 startup_name 的外键。

代码如下:

模型.py:

     class Startup(models.Model):
         author = models.ForeignKey(User, on_delete=models.CASCADE)
         startup_name = models.CharField('Startup Name', max_length = 32, null = False, blank = False)

     class Team (models.Model):
         str_team = models.ForeignKey(Startup, on_delete=models.CASCADE)
         name = models.CharField('Name',max_length = 32, null = False, blank = False)
         position = models.CharField('Title/Position', max_length = 32, null = False, blank = False)
         qualification = models.CharField('Degrees/Qualifications', max_length=32,null=False,blank=False)  

视图.py:

     def create_startupform(request):
         if request.method == 'POST':
             form = startupform(request.POST)
             if form.is_valid():
                 result = form.save(commit=False)
                 result.author = request.user
                 result.save()
                 return redirect('test', startup_id = result.pk)
         else:
             form = startupform()
         return render(request, 'str_name.html', {'form': form})

     def test (request, startup_id):
         e = Startup.objects.values('startup_name')

         if request.method == 'POST':
             na = request.POST.get("name")
             po = request.POST.get("position")
             qu = request.POST.get("qualification")

             ref = Team(name = na, position = po, qualification = qu, str_team = e)
             ref.save()
             return redirect('str_dashboard')
         return render(request, 'test.html')

表格.py:

     class startupform(forms.ModelForm):
         class Meta:
             model = Startup
             fields = ('startup_name',)
             widgets = {
                 'startup_name': forms.TextInput(attrs = {'class':'form-control'}),
             }

         def clean(self):
             super ( ).clean ( )
             startup_name = self.cleaned_data.get ( 'startup_name' )
             startup_qs = Startup.objects.filter ( startup_name = startup_name )
             if startup_qs.exists ( ):
                 raise forms.ValidationError ( 'This Startup Already Exist!' ) 

测试.html:

     <form id="add-extra" class="form" method="post" action = "{% url 'test' %}">{% csrf_token %}
<div class="form-row profile-row">
    <div class="col-md-8 col-lg-12">
        <hr />
        <h4>Startup Core Team</h4>
        <div class="form-row">
            <div class="col-sm-12 col-md-6 col-lg-12">
                <div class="form-group">
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Position</th>
                                    <th>Qualification</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><input class="form-control" type="text" name="candidate_name" /></td>
                                    <td><input class="form-control" type="text" name="position"/></td>
                                    <td><input class="form-control" type="text" name="qualification"/></td>
                                    <td><button class="btn btn-primary d-lg-flex align-items-lg-center" type="button" style="margin-top: 4px;margin-left: 15px;background-color: rgb(24,130,7);"><i class="fas fa-plus"></i></button></td>
                                </tr>
                                <tr></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <hr />
        <div class="form-row">
            <div class="col-md-12 content-right"><button class="btn btn-primary text-center border rounded d-lg-flex justify-content-lg-end align-items-lg-center form-btn" type="post" style="margin-left: 1040px;padding: 6px;">SAVE </button></div>
        </div>
    </div>
</div>

网址:

     from django.urls import path
     from . import views



     urlpatterns = [

         path ( 'str_dashboard/' , views.str_dashboard , name = 'str_dashboard' ),
         path ( 'create_startupform/' , views.create_startupform, name = 'create_startupform' ),
         path('test/', views.test, name='test'),

       ]   

错误:

     Page not found (404)
     Request Method:    GET
     Request URL:   http://127.0.0.1:8000/test/
     Using the URLconf defined in sourcing.urls, Django tried these URL patterns, in this order:

标签: django

解决方案


您正在尝试一个不在 urls.py 中的 url:

     urlpatterns = [
         ...
         path('test/<int:startup_id>/', views.test, name='test'),
         path('test/', views.test, name='test_base'),  # add this
       ]

网址“ http://127.0.0.1:8000/test/ ”将不匹配,因为它需要在您的 urls.py 中附加“startup_id”。 http://127.0.0.1:8000/test/ 1会起作用。

如果您确实像我上面写的那样,请确保您的视图将 startup_id 作为可选。或者在没有startup_id 的情况下使用另一个函数进行调用。


推荐阅读