【问题标题】:Converting from a Model Type to string in python django在 python django 中从模型类型转换为字符串
【发布时间】:2019-01-21 07:20:27
【问题描述】:

以下是我在 django 应用程序中的一个模型的快照:

class Request(models.Model):
    device_type                     = models.ForeignKey(DeviceType,to_field='device_type')
    requested_by                    = models.ForeignKey(User,to_field='username')
    urgency                         = models.ForeignKey(RequestUrgency,to_field='request_urgency')
    request_must_be_satisfied_by    = models.DateField(null=True)
    reason                          = models.TextField()
    status                          = models.ForeignKey(ResuestStatus,to_field='request_status',default="PENDING")
    request_date                    = models.DateField(default=datetime.now)

def __unicode__(self):
    return self.device_type

def __str__(self):
    return self.device_type

views.py 文件中的代码:

def request_form(request):
    if request.method == "POST":
        print("Inside out if")
        form = RequestForm(request.POST)
        print("request form: ", form)
        print("request fields ", form.fields)
        print("errors: ",form.errors.as_data())
        if form.is_valid():
        print("errors: ",form.errors.as_data())
        if form.is_valid():
            cleaned_data = form.cleaned_data

            post = form.save(commit = False)
            post.requested_by_id = request.user
            post.save()

            userdata = User.objects.get(username = request.user.username)
            useremail = userdata.email
            email_body_text = "Hi "+request.user.username+","+"\n"+"Your requested a repair for the following:"+"\n"\
                        +"Device Type: "+cleaned_data["device_type"]+"\n"\
                        +"Urgency: "+cleaned_data["urgency"]+"\n"\
                        +"Request must be satisfied by: "+cleaned_data["request_must_be_satisfied_by"]+"\n"\
                        +"Reason for new device: "+cleaned_data["reason"]+"\n"\
                        +"We will try to complete your request at the earliest. In case of any concerns contact the controller of operations."

            send_mail(email_subject,email_body_text,config.sender_email_id,[useremail],fail_silently=False)


        return redirect("NewRequest")

    else:
        print("Inside else")
        form = RequestForm(initial={'requested_by':request.user})
        Tp = DeviceType.objects.all()
        Tp = Tp.annotate(text=F('device_type')).values_list('text', flat=True)
        print("Tp request form: ", Tp)
        Ur = RequestUrgency.objects.all()
        Ur = Ur.annotate(text=F('request_urgency')).values_list('text', flat=True)
        form.fields["device_type"] = forms.ModelChoiceField(queryset=Tp, empty_label=None)
        form.fields["urgency"] = forms.ModelChoiceField(queryset=Ur, empty_label=None)
        return render(request, "Form_template.html", {"form": form, \
                                                  "name": "Device Request Form"})

现在,我的 views.py 中有一个函数可以验证通过 django 呈现的表单提交的数据。现在,我有一种情况,我想通过将其与特定字符串连接来打印通过表单发送的数据。每当我不得不这样做。我收到以下错误:

TypeError: coercing to Unicode: need string or buffer, DeviceType found 

我应该如何克服这个问题?

【问题讨论】:

  • 您至少需要显示您使用的代码。
  • 您是在询问views.py 中的代码吗? @丹尼尔罗斯曼
  • 你的模型中有 str 方法吗??
  • 是的@EsirKings 我更新了它。那么,情况还是一样。
  • @AishwaryShukla:这您当前面临的问题,您将字符串和非字符串添加在一起。那么"foo" + some_device_type 应该做什么呢?

标签: django python-2.7 django-models django-forms django-views


【解决方案1】:

问题是在构造email_body_text 时将字符串和非字符串加在一起。 Python 不理解字符串和 device_type 应该是什么意思。这并不奇怪,加一个字符串和一个数字有同样的问题:

>>> u"abc" + 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, int found

如您所见,消息一模一样,除了这里我们使用int 而不是DeviceType

您最好通过执行字符串格式化来解决这个问题。这不仅更安全(因为它会在窗帘后面调用unicode(..)str(..),而且更优雅。

但视图也存在其他问题:例如,您使用 cleaned_data 而不是您在表单中构造的 Request 对象,这使事情变得更容易、更优雅和可读:

def request_form(request):
    if request.method == "POST":
        form = RequestForm(request.POST)
        if form.is_valid():
            post = form.save(commit = False)
            post.requested_by_id = request.user
            post.save()

            user = request.user
            useremail = user.email
            email_body_text = (
                u"Hi {},"
                "\nYour requested a repair for the following:"
                "\nDevice Type: {}"
                "\nUrgency: {}"
                "\nRequest must be satisfied by: {}"
                "\nReason for new device: {}"
                "\nWe will try to complete your request at the earliest."
                "In case of any concerns contact the controller of operations."
            ).format(
                user.username,
                post.device_type,
                post.urgency,
                post.request_must_be_satisfied_by,
                post.reason,
            )

            send_mail(email_subject,email_body_text,config.sender_email_id,[useremail],fail_silently=False)
            return redirect("NewRequest")
    else:
        form = RequestForm(initial={'requested_by':request.user})
        Tp = DeviceType.objects.all()
        Tp = Tp.annotate(text=F('device_type')).values_list('text', flat=True)
        print("Tp request form: ", Tp)
        Ur = RequestUrgency.objects.all()
        Ur = Ur.annotate(text=F('request_urgency')).values_list('text', flat=True)
        form.fields["device_type"] = forms.ModelChoiceField(queryset=Tp, empty_label=None)
        form.fields["urgency"] = forms.ModelChoiceField(queryset=Ur, empty_label=None)
    return render(request, "Form_template.html", {"form": form, "name": "Device Request Form"})

注意;我建议您迁移到 Python-3.x,因为两年内将不再支持 Python-2.x:https://pythonclock.org/

【讨论】:

    猜你喜欢
    • 2011-06-29
    • 2013-10-16
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    相关资源
    最近更新 更多