简体   繁体   中英

Django queryset by username in user model

I've models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User) #from contrib.auth,...
    titulo = models.CharField(max_length=50, blank=True, default="")
    descripcion = models.TextField(default="")

    # Valor por defecto, "Pagina de +nombre usuario"
    def save(self, *args, **kwargs):
        if not self.titulo:
            self.titulo = "Pagina de " + self.user.get_username()
        super(UserProfile, self).save(*args, **kwargs)

views.py

 def ShowUserPage(request):
    UsuarioElegido = request.path.split('/')[1]
    UsuarioModel = UserProfile.user.get_user(UsuarioElegido)
    return HttpResponse(UsuarioElegido)

I wanna get "titulo" and "descripcion" of UsuarioElegido. UsuarioElegido is the request.path for example /"root". But I can't get it Help?

getting this error: ReverseSingleRelatedObjectDescriptor' object has no attribute 'get_user' UsuarioModel = UserProfile.objects.filter(user.username=UsuarioElegido)

but I don't know how to get it. Tried this before

         UsuarioModel = UserProfile.objects.filter(user.username=UsuarioElegido)

EDIT: I've just tried this, but Django can't finde my ShowUserPage in views :/?

def ShowUserPage(request):
    UsuarioElegido = request.path.split('/')[1]
    UsuarioModel = User.objects.get(username=UsuarioElegido)
    UsuarioModel = UserProfile.objects.filter(user=UsuarioModel)
    return HttpResponse(UsuarioElegido)

Assuming username is unique:

UsuarioModel = UserProfile.objects.get(user__username=UsuarioElegido)

Use __ (double underscore) to follow relations in lookups .

First of all, you don't have to analyze request.path on your own and extract all necessary parts of the URL. You can map this using urls.py file. For example like this:

urlpatterns = [
    url(r'^user/(?P<username>\w+)$', views.ShowUserPage),
]

And your ShowUserPage view method that handles this request has following signature:

def ShowUserPage(request, username)

Second, if you want to look for the user by its name, you can use following query:

UserProfile.objects.get( user__username=UsuarioElegido )

It will search by username attribute of the native Django class for User.

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