Home > OS >  question about forms, how do i get instant user in a form field pyhton django
question about forms, how do i get instant user in a form field pyhton django

Time:06-14

i have build some user to user message function. i have sender, receiver and text see below. The user now must choose his email and then the email where the message should go. But what i want is that the user dont need tho choose it self i need a form function that query instantly request.user. but i dont know how to implement that on form. And that the user is not shown in the receiver list. Srry for my bad english hope you understand me.

views.py

def mailEMployee(request):
    mail = Mailsysthem.objects.filter(ontvanger=request.user)
    receiver = Mailsysthem.objects.filter(ontvanger=request.user)
    sender = Mailsysthem.objects.filter(zender=request.user)
    user = CustomUser.objects.filter(email=request.user)
    form = Mailsythemform()
    if request.method == 'POST':
       form = Mailsythemform(request.POST, request.FILES)
    if form.is_valid():
       form.save()
       return redirect('mail')
   context={
   'form':form,
   'receiver':receiver,
   'sender':sender.all,
   'mail':mail,
   'user':user
    }
   return render(request,'emp/mail.html', context)

Forms.py

class Mailsythemform(forms.ModelForm):

class Meta:
    model= Mailsysthem
    fields= ['zender','ontvanger','subject','text']

models.py

class Mailsysthem(models.Model):
zender = models.ForeignKey(to=CustomUser, null=True, on_delete=models.SET_NULL,related_name='Zender')
ontvanger = models.ForeignKey(to=CustomUser, null=True, on_delete=models.SET_NULL,related_name='Ontvanger')
subject = models.CharField(null=True, max_length=200)
text = models.TextField(max_length=300, null=True, blank=True, verbose_name='Bericht')
date = models.DateTimeField(auto_now_add=True, blank=True)
solftdelete = models.BooleanField(default=False)
mail_opened = models.BooleanField(default=False)

url.py

   path('mailemployee/', views.mailEMployee, name='mail'),

CodePudding user response:

You need to provide initial value to your ModelForm (docs) as following:

form = JournalForm(initial={'sender': user.id})
  • Related