我正在尝试在Django中创建一个表单,其中包含一个表单字段,其中包含从User
对象中提取的默认值。
forms.py
class EvangelizedForm(forms.ModelForm):
#full_name = forms.CharField(help_text="Full Name")
email = forms.CharField(help_text="Email ID")
mobile_no = forms.CharField(help_text="Mobile number")
twitter_url = forms.CharField(help_text="Twitter URL")
models.py
class Evangelized(models.Model):
full_name = models.CharField(max_length=128)
email = models.EmailField()
mobile_no = models.CharField(unique=True, max_length = 10, validators=[RegexValidator(regex='^\w{10}$', message='Mobile number should be strictly of 10 digits.')])
twitter_url = models.CharField(unique=True, max_length=128)
views.py
def fillform(request):
if request.method == 'POST':
form = EvangelizedForm(request.POST)
if form.is_valid():
form.save(commit=True)
return index(request)
else:
form.errors
else:
#form = EvangelizedForm()
form = EvangelizedForm(initial={'full_name': request.get_full_name()})
context = RequestContext(request,
{'request': request,
'user': request.user, 'form':form})
#return render(request, 'rango/fillform.html', {'form': form, 'context_instance':context})
return render_to_response('rango/fillform.html',
context_instance=context)
但是,我遇到以下错误:
'AnonymousUser' object has no attribute 'get_full_name'
此错误表示什么,以及如何解决此错误?
答案 0 :(得分:5)
你最想要的是:
request.user.get_full_name() if request.user.is_authenticated() else ""