如何返回用户id而不是first_name和last_name - Django 1.6

时间:2015-08-06 01:20:49

标签: python django django-models django-forms django-templates

我修改的代码只需要显示实际的user.id而不是Django 1.6中模型的first_name和last_name字段。

我修改的代码是views.py

if not form.cleaned_data['amount']:
            amount = project.amount

        project_application = ProjectApplication.objects.create(
            project=project,
            contractor=UserProfile.objects.get(id=request.user.id),
            completion_time=form.cleaned_data['completion_time'],
            # todo: lazy!
            amount=int(round(amount))
        )

        # debit contratalos credits
        credit.debit_credits(user_profile)

        # Send msgs
        request.session['message'] = _(
            u'<strong>You have applied to this project. </strong> '
            u'We will contact you '
            u'if your proposal was chosen or turned down')

        send_mail(
            _(u'Your have a new project proposal'),
            _(u'Tu proyecto %s ha recibido una propuesta de %s. '
              u'Por favor logueate para ver más detalles' % (
              project.name, project_application.contractor)),
            'contratalos@contratalos.com',
            [project.user.email])

如果您查看project_application方法,我实际上将contractor定义为UserProfile.objects.get(id=request.user.id),因此应该使用该承包商类型用户的id

问题是,这来自一个名为UserProfile的模型,它的外观如下:

class UserProfile(User):
    """Basic User profiles

    Includes basic i18n capabilities

    """

    # Razon Social | Doing business as...
    dba = models.CharField(_('doing business as'), max_length=64,
                           null=True, default=None, blank=True)
    birthdate = models.DateField(_('date of birth'),
                                 help_text=_('please use MM/DD/YYYY format'),
                                 validators=[validate_adult],
                                 null=True, default=None, blank=True)

    is_vat = models.BooleanField(_('is vat?'), default=False)
    government_id = models.CharField(_('government identification'),
                                     max_length=64, validators=[validate_id],
                                     help_text=_("RIF: J0000000 / "
                                                 "CI: V00000000 or E00000000"))

    is_company = models.BooleanField(_('is company?'), default=False)
    description = models.TextField(_('description'), null=True, blank=True)
    hourly_cost = models.PositiveIntegerField(_('hourly cost'), default=0)
    least_cost_contract = models.PositiveIntegerField(_('least amount per contract'),
                                              default=0, null=True)
    active_plan = models.BooleanField(_('has active plan'),
                                      default=False)

    contracting = models.BooleanField(_('contracting?'), default=False)
    membership = models.ForeignKey(MembershipType, null=True)

    skills = models.ForeignKey(SkillCategory, null=True, blank=True)
    main_skills = models.ManyToManyField(Skill, null=True, blank=True,
                                         default=None)

    # System interaction
    skills_search_result = models.BooleanField(_('Appear in search results '
                                                 'matching my skills?'),
                                               default=True)
    jobs_search_result = models.BooleanField(_(
        'I wish to receive e-mail notifications about new jobs '
        'available within my skills'),
        default=True)

    address = models.CharField(_('address'), max_length=255, null=True,
                               blank=True, default=None)
    city = models.ForeignKey(City, null=True, blank=True, default=None)
    state = models.ForeignKey(State, null=True, blank=True, default=None)
    # TODO: Ranking must be a function

    contratalos_credits = models.PositiveIntegerField(default=0)

    objects = UserManager()

    def save(self, *args, **kwargs):
        # Just to keep logic in model for APIs
        if self.birthdate and isinstance(self.birthdate, str):
            import datetime
            bdate = [int(x) for x in self.birthdate.split('-')]
            validate_adult(datetime.date(*bdate))
        super(UserProfile, self).save()

    def __unicode__(self):
        return u'{} {}'.format`(self.first_name, self.last_name)`  ...

正如您所看到的那样,return __unicode__ (self.first_name, self.last_name) views.py对我的应用来说是可以的,并且工作得非常好,但我的问题是,当我发送您在id上看到的电子邮件应该只显示实际的first_name而不是last_nameMBCB

有没有办法克服这个问题?

1 个答案:

答案 0 :(得分:2)

send_mail调用中,传递project_application.contractor.id而不仅仅是project_application.contractor,它会为您提供UserProfile模型实例的unicode表示。