You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django技术问题:HTTP请求创建类实例及交互式控制台报错排查

1. How to Create a Class Instance via HTTP Request in Django

There are two common scenarios here—creating an instance of a custom Python class or a Django Model class from an HTTP request. Here's how to handle both:

Custom Class Instance

Suppose you have a custom class (like one to represent SMS responses) and want to spin up an instance using data from an incoming request:

# utils.py (or any file where you define your class)
class SmsResponse:
    def __init__(self, phone_number, message):
        self.phone_number = phone_number
        self.message = message

# views.py
from django.http import HttpResponse
from .utils import SmsResponse

def create_sms_instance(request):
    if request.method == 'POST':
        # Pull data from the request (works for form data or JSON)
        phone_number = request.POST.get('phone_number')
        message = request.POST.get('message')
        
        # Create the class instance with the extracted data
        sms_response = SmsResponse(phone_number, message)
        
        # Do whatever you need with the instance (store it, process it, etc.)
        # ...
        
        return HttpResponse(f"Instance created for {sms_response.phone_number}")
    return HttpResponse("Please use POST method to submit data")

Django Model Instance

If you're creating an instance to save to your database (using Django's ORM):

# models.py
from django.db import models

class SmsSubscriber(models.Model):
    phone_number = models.CharField(max_length=20)
    message = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

# views.py
from django.http import HttpResponse
from .models import SmsSubscriber

def save_sms_subscriber(request):
    if request.method == 'POST':
        phone_number = request.POST.get('phone_number')
        message = request.POST.get('message')
        
        # Create and save the model instance in one step
        subscriber = SmsSubscriber.objects.create(
            phone_number=phone_number,
            message=message
        )
        
        return HttpResponse(f"Subscriber saved with ID: {subscriber.id}")
    return HttpResponse("Please use POST method")

2. Fixing AttributeError: 'tuple' object has no attribute 'get'

This error happens when you try to use the .get() method (typically for dictionaries or querysets) on a tuple instead. Let's walk through the most likely fixes for your Django-Twilio setup:

Issue 1: Incorrect Request Import

Looking at your code snippet, you have:

from django.http import request  # This is a mistake!

request here refers to the module, not the actual request object Django passes to your view. Fix this by using the request parameter that's automatically injected into your view function:

# Correct code
from django_twilio.decorators import twilio_view
from django_twilio.request import decompose
from twilio.twiml.messaging_response import MessagingResponse

@twilio_view
def handle_sms(request):  # Use the request parameter here
    # Decompose the Twilio request into a dictionary-like object
    twilio_data = decompose(request)
    
    # Now you can safely use .get() to pull data
    phone_number = twilio_data.get('From')
    message_body = twilio_data.get('Body')
    
    # Save to your model (example)
    # SmsSubscriber.objects.create(phone_number=phone_number, message=message_body)
    
    # Return the required TwiML response
    resp = MessagingResponse()
    resp.message("Got your reply!")
    return resp

Issue 2: Unpacking Tuples Wrong When Fetching Data

If you're using values_list() to pull phone numbers from your model, it returns tuples by default. For example:

# This returns a list of tuples: [('+1234567890',), ('+0987654321',)]
phone_numbers = SmsSubscriber.objects.values_list('phone_number')

# Trying to call .get() on a tuple here will throw the error
for num in phone_numbers:
    print(num.get('phone_number'))  # Wrong! num is a tuple

Fix this by adding flat=True to get a list of strings instead:

phone_numbers = SmsSubscriber.objects.values_list('phone_number', flat=True)
# Now phone_numbers is ['+1234567890', '+0987654321']
for num in phone_numbers:
    print(num)

Issue 3: Returning a Tuple Instead of a Valid Response

The twilio_view decorator expects a TwiML response object, not a tuple. If your view returns something like (resp, 200) instead of just resp, that could cause unexpected tuple handling in the console. Stick to returning the MessagingResponse directly as shown above.


内容的提问来源于stack exchange,提问作者Ach1916

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:15:53