简体   繁体   中英

Get username in Django Forms

I want to get username in my form. For example: username of current user is admin then in my form, the name part should fill with ' admin ' automatically. What should I do? Here is my codes...

views.py

def attendanceView(request):
    if request.method=='POST':
        form = AttendanceForm(request.POST)
        if form.is_valid():
            attendance = AttendanceModel()
            attendance.name = form.cleaned_data['name']
            attendance.date = form.cleaned_data['date']
            attendance.save()
            return redirect('home')
    else:
        form = AttendanceForm()
    return render(request, 'attendance.html', {'form': form})

models.py

class AttendanceModel(models.Model):
    name = models.CharField(max_length=100)
    date = models.DateTimeField(default=datetime.now)

    class Meta:
        unique_together = ('name', 'date',)

forms.py

class AttendanceForm(ModelForm):
    class Meta:
        model = AttendanceModel
        fields=('name', 'date')

You can prepopulate specific fields of the form in your view.

views.py

   def attendanceView(request):
      if request.method=='POST':
          form = AttendanceForm(request.POST)
          if form.is_valid():
              attendance = AttendanceModel()
              attendance.name = form.cleaned_data['name']
              attendance.date = form.cleaned_data['date']
              attendance.save()
              return redirect('home')
          else:
              initial = {'name':request.user.username}
              form = AttendanceForm(initial=intial)
      return render(request, 'attendance.html', {'form': form})

You can prepopulate parts of the form with the initial keyword argument: https://docs.djangoproject.com/en/2.1/ref/forms/api/#django.forms.Form.initial .

In your case, this would be something like this in the else clause: form = AttendanceForm(initial={"username": request.user.username})

You need to call the the user from init method in the forms.py. First instantiate the user in the view.

    if request.method=='POST':
        form = AttendanceForm(request.POST, name=request.name)
        if form.is_valid():
            attendance = AttendanceModel()
            attendance.name = form.cleaned_data['name']
            attendance.date = form.cleaned_data['date']
            attendance.save()
            return redirect('home')
    else:
        form = AttendanceForm(name=request.name)
    return render(request, 'attendance.html', {'form': form})

Then in the forms you need to add an __init_ method.

    def __init__(self, *args, **kwargs):
        self.name = kwargs.pop('name')
        super(AttendanceForm, self).__init__(*args, **kwargs)

        name = forms.CharField()

        if name is not None:
            self.fields['name'] = forms.CharField(initial=self.name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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