在django中保存和更新自定义html表单中的数据



我已经为我的模型创建了一个自定义HTML表单,就像我想从前端添加一个帖子一样。我已经创建了一个名为的页面add-post.html

<form method="POST" action="">
{% csrf_token %}
<input name="title" type="text">
<textarea spellcheck="false" name="description"></textarea>
<input type="file" name="image" @change="fileName" multiple />
<select required name="priority">
<option value="Low" selected>Low</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
</select>
<input type="checkbox" name="on_hold">
<button type="submit">Add ToDo</button>
</form>

这是我的模型。py

class Todo(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(null=True, blank=True, upload_to='todo/images/')
description = RichTextField()
Low, Medium, High = 'Low', 'Medium', 'High'
priorities = [
(Low, 'Low'),
(Medium, 'Medium'),
(High, 'High'),
]
priority = models.CharField(
max_length=50,
choices=priorities,
default=Low,
)
on_hold = models.BooleanField(default=False)

不,我想使用上面的自定义HTML表单来发布数据并将其保存到这个模型数据库。而不是使用{% form.as_p %}

我还创建了一个特定的页面来从前端更新这篇文章,但不知道如何使它工作。

你能告诉我如何从自定义表单中保存数据并从自定义表单中更新数据吗?感谢您的回复:)

@Mubasher Rehman -你就快成功了

forms.py

class TodoCreationForm(forms.ModelForm):
class Meta:
model = Todo
fields = ('title','image','description','priorities','priority','on_hold',)

views.py

from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic import CreateView
class CreatProduct(SuccessMessageMixin,CreateView):
model = Todo
form_class = TodoCreationForm
template_name = "add_post.html"
success_message = "Todo was created successfully"
error_message = "Error saving the Todo, check fields below."

add_post.html

<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<button type="submit" class="btn btn-primary">Submit</button>
</form>

@Mubasher Rehman -我自己与这个问题斗争了一段时间,最终找到了一个解决方案。我的情况和你的情况大不相同,但是试试这个:

在你的视图。py覆盖form_valid方法如下:

def form_valid(self, form):
if self.request.POST:
if form.is_valid():
t= Todo.objects.create(title='title', image='image', description='description', priority='priority', on_hold='on_hold')
t.save()
return super(ModelView, self).form_valid(form)

最新更新