Django:如何将数据插入字段,其中pk =?

时间:2015-08-11 18:02:26

标签: python django database django-models django-orm

假设我将事件加载到数据库中,file:///description字段中有信息,但status保留为NULL。

action_taken

如何使用此表单和视图将信息加载到class Incident(models.Model): description = models.TextField() status = models.ForeignKey(Status, default="open") action_taken = models.TextField() 字段?

forms.py

action_taken

views.py

class ResolveForm(forms.Form):
    action_taken = forms.CharField(widget=forms.Textarea)

错误

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)

错误:名称'action_taken'未定义

1 个答案:

答案 0 :(得分:1)

  

如何使用此表单和视图将信息加载到action_taken字段?

我看到你已经有了你的模型实例incident,所以这应该这样做

incident = get_object_or_404(Incident, pk=incident_id)
incident.action_taken = action_taken
incident.save()

如果在您的更新中,您不想触及其他字段:

incident = get_object_or_404(Incident, pk=incident_id)
incident.action_taken = action_taken
incident.save(update_fields=['action_taken'])

批评你的尝试:

q = Incident(action_taken=action_taken)
q.save()

这不会获得您想要更新的对象,而是创建一个新对象并保存它(不是您想要的)