简体   繁体   English

Django model 表单,在创建新笔记时添加用户 ID

[英]Django model form, adding a user id when creating new note

I'm pretty new to Django, I've been stuck on this view for a little while.我对 Django 很陌生,我已经被这个观点困住了一段时间。 My goal with this form is to be able to create a small note on a "Property" about maintenance or other information.我使用此表单的目标是能够在“财产”上创建有关维护或其他信息的小注释。 The note would log the time, date, note and the user that recorded the note.该便笺将记录时间、日期、便笺和记录该便笺的用户。 Any help would be appreciated.任何帮助,将不胜感激。

View:看法:

@login_required(login_url="login")
def createNote(request, pk):
PropertyNoteFormSet = inlineformset_factory(
    Property, PropertyNote, fields=('note', 'user',))
property_note = Property.objects.get(id=pk)
form = PropertyNoteFormSet(instance=property_note)

# form = OrderForm(initial={'customer': customer})
if request.method == "POST":
    print(request.POST)
    form = PropertyNoteFormSet(
        request.POST, instance=property_note)
    if form.is_valid():
        form.save()
        return redirect("/")

context = {"form": form}
return render(request, "dashboard/create_note.html", context)

Here is the ModelForm:这是模型表单:

 class PropertyNoteForm(ModelForm):
    class Meta:
      model = PropertyNote
      fields = ['note']
      exclude = ['user']

Here is the Model:这是 Model:

 class PropertyNote(models.Model):
        airbnb_name = models.ForeignKey(Property, blank=True, 
        null=True,on_delete=models.CASCADE)
        note = models.TextField(blank=True, null=True)
        user = models.ForeignKey(User, on_delete=models.CASCADE)
        created_on = models.DateTimeField(auto_now_add=True)

        def __str__(self):
            return self.note

The form comes out with around 4 boxes to fill in. Currently it works, but you have to actually select the user that is posting the note, I would like this part to be handled automatically and use the current logged in user.表格出来时有大约 4 个要填写的框。目前它可以工作,但您实际上必须 select 发布注释的用户,我希望这部分能够自动处理并使用当前登录的用户。 I think I still have a whole lot of holes in my knowledge around this stuff, I just can't seem to work it out.我想我对这些东西的知识仍然有很多漏洞,我似乎无法解决。

Thanks in advance.提前致谢。

Edit:编辑:

I've tried this:我试过这个:

def createNote(request, pk):
PropertyNoteFormSet = inlineformset_factory(
    Property, PropertyNote, fields=('note',), extra=1)
property_note = Property.objects.get(id=pk)
form = PropertyNoteFormSet(
    queryset=PropertyNote.objects.none(), instance=property_note)

# form = OrderForm(initial={'customer': customer})
if request.method == "POST":
    print(request.POST)
    form = PropertyNoteFormSet(
        request.POST, instance=property_note)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.user = request.user
        print(instance.user)
        instance.save()
        return redirect("/")

context = {
    "form": form,
    'pk': pk,
}
return render(request, "dashboard/create_note.html", context)

But I get this:但我明白了:

AttributeError at /create_note/75/
'list' object has no attribute 'user'
Request Method: POST
Request URL:    http://127.0.0.1:8000/create_note/75/
Django Version: 3.0.4
Exception Type: AttributeError
Exception Value:    
'list' object has no attribute 'user'

you can use request.user.id to get the logged user id in your view.您可以使用request.user.id在您的视图中获取登录的用户 ID。

See Documentation in Django 请参阅 Django 中的文档

@login_required(login_url="login")
def createNote(request, pk, **kwargs):
    note_form = PropertyNoteForm()
    if request.method == "POST":
        note_form = PropertyNoteForm(request.POST)
        if note_form.is_valid():
            add_note = note_form.save(commit=False)
            add_note.user = request.user
            add_note.airbnb_name = 
      Property.objects.get(id=pk)
            add_note.save()
            return redirect('/property/' + pk + '/')

    context = {
        "form": note_form,
        'pk': pk,
    }
    return render(request, "dashboard/create_note.html", context)

I solved it with the above code.我用上面的代码解决了它。 Using instance was the incorrect thing to do here.在这里使用实例是不正确的。 I didn't need to create an instance and I didn't need the inline form.我不需要创建实例,也不需要内联表单。 I simply needed a new form:我只需要一个新表格:

note_form = PropertyNoteForm()

The user input information, I need to send that information to check if it's valid:用户输入信息,我需要发送该信息以检查它是否有效:

if request.method == "POST":
note_form = PropertyNoteForm(request.POST)
if note_form.is_valid():

Then I needed to populate the form with information that was not already in the form from the user:然后我需要使用用户表单中尚未包含的信息填充表单:

add_note = note_form.save(commit=False)
add_note.user = request.user
add_note.airbnb_name = Property.objects.get(id=pk)
add_note.save()
return redirect('/property/' + pk + '/')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM