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

Xamarin Forms调用Django Web服务及ListView数据展示问题咨询

解决Xamarin Forms从Django网站获取数据并展示的问题

首先明确:你绝对应该用REST API!你现在的代码请求的是Django返回的HTML网页内容,不是结构化的JSON数据,所以JsonConvert.DeserializeObject肯定会失败——这就是代码无法运行的核心原因。下面一步步帮你搞定:

第一步:在Django端搭建REST API

推荐用Django REST Framework(DRF)来快速生成API,这是Django生态里做API的标准方案:

  1. 安装DRF
pip install djangorestframework
  1. 在settings.py里添加rest_framework到INSTALLED_APPS:
INSTALLED_APPS = [
    # ... 其他已有的app
    'rest_framework',
]
  1. 为你的Post模型创建序列化器(在app的serializers.py里):
from rest_framework import serializers
from .models import Post

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ['id', 'description', 'image', 'published']
  1. 写API视图(在app的views.py里):
from rest_framework import generics
from .models import Post
from .serializers import PostSerializer

class PostList(generics.ListAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
  1. 配置URL路由(在项目的urls.py里):
from django.urls import path
from your_app_name.views import PostList

urlpatterns = [
    # ... 其他已有路由
    path('api/posts/', PostList.as_view(), name='post-list'),
]

现在启动Django服务,访问https://mysite.ru/project/api/posts/就能看到返回的JSON数据了。

第二步:修改Xamarin Forms代码适配API

你的现有ViewModel逻辑框架没问题,但要调整几个关键地方:

1. 修正API请求地址

把client.GetAsync的地址改成刚才创建的API地址:https://mysite.ru/project/api/posts/

2. 优化HttpClient的使用(避免资源泄漏)

不要每次请求都新建HttpClient,建议复用单例:

private static readonly HttpClient _httpClient = new HttpClient();

3. 添加异常处理(方便调试)

加入try-catch块,能快速定位错误:

private async void GetDataAsync() {
    try {
        var response = await _httpClient.GetAsync("https://mysite.ru/project/api/posts/");
        response.EnsureSuccessStatusCode(); // 非200状态会抛出异常
        var content = await response.Content.ReadAsStringAsync();
        var menu = JsonConvert.DeserializeObject<List<Dishes>>(content);
        // 注意:Django返回的image是相对路径,要拼接成完整URL
        foreach(var dish in menu) {
            dish.image = $"https://mysite.ru/project{ dish.image }";
        }
        MenuList = menu;
    }
    catch(Exception ex) {
        // 这里可以打印日志或者给用户提示
        Console.WriteLine($"获取数据失败:{ex.Message}");
    }
}

4. 确保ListView的XAML绑定正确

你的XAML里要正确绑定ViewModel和ListView:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:vm="clr-namespace:YourAppNamespace.ViewModels"
             x:Class="YourAppNamespace.Views.LandingPage">
    <ContentPage.BindingContext>
        <vm:LandingViewModel />
    </ContentPage.BindingContext>
    <ListView ItemsSource="{Binding MenuList}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout>
                        <Label Text="{Binding description}" />
                        <Image Source="{Binding image}" />
                        <Label Text="{Binding published, StringFormat='发布于:{0:yyyy-MM-dd}'}" />
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

额外注意点

  • 如果你Django网站开启了CSRF保护,API请求可能需要处理,但DRF的ListAPIView默认是允许匿名GET请求的,暂时不用管;如果后续有POST请求再配置。
  • 确保Django的媒体文件(图片)能被外部访问,需要在settings.py里配置MEDIA_URL和MEDIA_ROOT,并且在开发环境中配置媒体文件的路由。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 11:52:37