用django createview从表单和其他字段保存对象
我对如何在my_model中添加的其他字段,这些字段 在我的html表单中被排除在 forms.py 中,同时用 > CreateView !
models.py:views.py:mymodel.html
class My_model(models.Model):
# attrs in the form that are saved already with now problem
...
#attrs excluded in forms.py but I want to save them along with the form
attr_1=models.CharField(max_length=30)
attr_2_type=[('a','A'),('b','B')]
attr_2=models.Charfield(max_length=8,choices=attr_2_type)
...
def get_absolute_url(self):
return reverse("application:redirectin_pattern_name", kwargs={"pk":self.pk})
都是
class MyModelCreateView(CreateView):
model= My_model
form_class = MyModelForm
template_name = "application/mymodel.html"
这里的
<div class="row ">
<div class="col-md-3"></div>
<div class="col-md-6">
{% block form %}
<form method="post" action="{% url 'application:pattern_name' %}">
{% endblock form %}
{% csrf_token %}
{{ form.as_p }}
<input class="form-control btn-primary" type="submit" name="save"
value="send your demand" />
</form>
</div>
</div>
一切正常,表格显示了,我可以提交数据并将其保存到数据库中,然后我自动将其重定向到我保存的对象的详细信息页面,所有详细信息 更正我什至检查了另一个对象的传递ID,以查看其是否更改并显示每个对象的详细信息,并且也可以工作。
现在,当我将表单保存到数据库时,我只想同时保存模型的其余属性。
根据要求 forms.py:urls.py
from .models import My_Model
class MyModelForm(ModelForm):
class Meta:
model=My_Model
exclude=("attr_1", "attr_2")
widgets={
# i listed all the attributes that I need the user to
# fill and they all are being saved correctly
}
urlpatterns=[
path('demand', views.MyModelCreateView.as_view(), name='patern_name'),
path('detils', views.MyModelDetailView.as_view(), name='redirectin_pattern_name'),
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决的
感谢我解决的互动,但我无法解释代码,因此我只会发布它。
我对Views.py进行了更改
Solved
thanks for the interactions I solved it but I can't explain the code so I will just post it.
I made changes to views.py