Django:在foreignkey上选择文本输入

时间:2017-04-01 14:09:05

标签: django django-models django-forms foreign-keys

我想在ma django app中创建一个消息传递功能。用户应该能够为其他用户写一个textmessage。

models.py

from django.contrib.auth.models import User
class Message(models.Model):
    recipient   = models.ForeignKey(User, null=True)
    contentDescription = models.CharField(max_length=1000, null=True)

默认情况下,如果没有forms.py条目,我会得到一个选择,这对许多用户来说都是无用的。我希望邮件发件人输入用户名,或者在第一步中输入用户ID(我可以使用名称中的ajax解析)。

整数

但是使用forms.py

recipient =         forms.IntegerField(    widget=forms.NumberInput , required=False,)

我明白了:

    Cannot assign "11": "Transport.recipient" must be a "User" instance.

ChoiceField和NumberInput

使用:

recipient =          forms.ChoiceField(  widget=forms.NumberInput, required=False,)

我收到错误消息"无效"

是否可以手动编写外键'一点都没有?

2 个答案:

答案 0 :(得分:1)

试试这个:

recipient = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.Select, required=False)

答案 1 :(得分:1)

考虑你的

models.py -

from django.contrib.auth.models import User
class Message(models.Model):
    recipient   = models.ManytoMany(User, null=True)
    contentDescription = models.TextField()

forms.py

from .models import Message
from django import forms
from django.contrib.auth.models import User

class MailForm(forms.ModelForm):
     recipient = forms.Charfield()
     class Meta:
           model = Message
           fields = ('contentDescription',)

     def clean_recipient(self):
         user_list = self.cleaned_data.get('recipient')
         # considering you post user_list of usernames as 'username1,username2,username3'
         if user_list is not None:
            user_list = user_list.split(',')
            user_qs = User.objects.filter(username__in=userlist)
         else:
            raise forms.ValidationError('Error in this field')
         return user_qs

def save(self, user_qs):
    self.instance.user = user_qs
    return super().save()
views.py -

中的

from .forms import MailForm
def your_view(request):
    form = MailForm(request.POST or None)
    if form.is_valid():
       user_qs=form.cleaned_data.get('recipient')
       form.save(user_qs)
       #return render here
    else:
         #create your context here and return render

这不完美,但可以让您了解如何实施。根据你给出的细节,这是我现在能做的最好的事情。