我正在尝试构建表单,该表单连接到PostgreSQL数据库并在其中保存信息。代码如下: models.py:
from django.db import models
from django import forms
from django.urls import reverse
from django.forms import ModelForm
class ForQuery(models.Model):
query_id = models.BigAutoField(primary_key=True)//I would like to have my own automatic int field
worker_name = models.CharField(max_length=35, blank=True, null=True)
dep_name = models.ForeignKey(Classification, models.DO_NOTHING, db_column='dep_name', blank=True,
null=True)
forms.py:
class ForQueryForm(forms.ModelForm):
class Meta:
model=ForQuery
fields=('work_name', 'dep_name')//only one field has to be entered while form. the other chosen.
urls.py:
urlpatterns = [
//both paths are extensions from generic page. Which is the main page for the program
path('', views.index, name='index'),
path('worker_ch/', views.worker_ch, name='worker_ch'),
]
views.py:
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, get_object_or_404, redirect
from scrap_site.models import ForQuery
from django.urls import reverse
from django.views.generic import TemplateView, ListView
from django.db.models import Q
from .forms import ForQueryForm
def doquery(request):
form=ForQueryForm()
return render(request, 'my_site/worker_ch.html', {'form':form})
worker_ch.html:
{% extends "generic.html" %}
{% load static %}
{% block css %}
<link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}">>
{% endblock %}
{% block content %}
<h2>Enter</h2>
<form method="post" class="for-query-form">
{% csrf_token %}
{{form.as_ch}}
<input type="submit" name="" value="Submit">
</form>
{% endblock %}
此故障出现:
File "C:\my_project\ch\ch_site\urls.py", line 22, in <module>
path('worker_ch/', views.worker_ch, name='worker_ch'),
AttributeError: module 'ch_site.views' has no attribute 'worker_ch'
感谢您提供的所有帮助!仍在研究Django并尝试找出答案。在我的程序中,我有一个错误,并且尝试了不同的方法来解决它,但是它仍然存在...而且我找不到任何类似的情况来解决它...如果可能,如果您看到我的错误在哪里,并且您看到了一个非常荒谬的明显现象,请让我知道我不明白的内容吗?感觉我不了解Django的重要知识...感觉就像我每次与Django战斗时一样:(,当我对我做不同和新颖的事情时...就像我以错误的方式摩擦猫一样。尽管我正在关注教程并阅读有关Django的文章和书籍,但是向右或向左移动Django却会给我一个接一个的错误。
答案 0 :(得分:1)
在这里我可以找到两个问题。一种是,没有名为work_ch
的视图,它应该是doquery
:
path('worker_ch/', views.doquery, name='worker_ch'),
两个,在模板中,您需要将{{form.as_ch}}
替换为{{ form.as_p }}
或仅{{ form }}
应该起作用。