Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

171
Vistas
Django: text-input instead selection on foreignkey

I want to create a messaging function in ma django app. User should be able to write other users a 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)

By default, with no forms.py entry I get a selection, which will be unuseful with many users. I want the message sender to type in the user name, or in the first step the user id (which I could resolve with ajax from the name) .

Integer

But with forms.py

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

I get:

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

ChoiceField and NumberInput

with:

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

I get the error message "not valid"

Is it possible to write the foreignkey 'manually' at all?

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Try this:

recipient = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.Select, required=False)
about 4 years ago · Santiago Trujillo Denunciar

0

considering your

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()

in 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

This is not perfect but can give you an idea how to implement. With the details you gave this is the best I can do for now.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda