[英]Django: How to insert data into field, where pk =?
Lets say I have an incident loaded into the database, where there is information in the description
and status
fields, but action_taken
is left NULL. 可以说我有一个事件加载到数据库中,在
description
和status
字段中有信息,但是action_taken
保留为NULL。
class Incident(models.Model):
description = models.TextField()
status = models.ForeignKey(Status, default="open")
action_taken = models.TextField()
How can I load information into the action_taken
field using this form and view? 如何使用此表单和视图将信息加载到
action_taken
字段中?
forms.py 表格
class ResolveForm(forms.Form):
action_taken = forms.CharField(widget=forms.Textarea)
views.py views.py
def detail(request, incident_id):
incident = get_object_or_404(Incident, pk=incident_id)
template = "incidents/detail.html"
if request.method == 'POST':
form = ResolveForm(request.POST or None)
if form.is_valid():
action_taken = (form.cleaned_data['action_taken'])
######### MY EFFORTS #########################
q = Incident(action_taken=action_taken)
q.save()
print(incident.id)
#new_incident, created = Incident.objects.get_or_create(action_taken)
##############################################
return render(request, template, {'form': form})
else:
form = ResolveForm()
context = { 'incident': incident,
'form': form}
return render(request, template, context)
errors 错误
incident.action_taken = action_taken
error: name 'action_taken' is not defined 错误:未定义名称“ action_taken”
How can I load information into the
action_taken
field using this form and view?如何使用此表单和视图将信息加载到
action_taken
字段中?
I see you already have your model instance incident
, so this should do it 我看到您已经发生了模型实例
incident
,所以应该这样做
incident = get_object_or_404(Incident, pk=incident_id)
incident.action_taken = action_taken
incident.save()
If in your update you don't want to touch the other fields: 如果在更新中,您不想触摸其他字段:
incident = get_object_or_404(Incident, pk=incident_id)
incident.action_taken = action_taken
incident.save(update_fields=['action_taken'])
To critique what you tried: 批评您尝试了什么:
q = Incident(action_taken=action_taken)
q.save()
This doesn't get the object you want to update, but instead it creates a new one and saves it (not what you want) 这不会获取您要更新的对象,而是创建一个新对象并保存(而不是您想要的对象)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.