无法在后端 django 的反应中显示图像

时间:2021-04-17 19:22:21

标签: reactjs django django-rest-framework

我想显示一个图像,我从数据库中获取 src 链接到 localhost 8000 上的 django,作为反应(本地主机 3000)。

这是我的观点:

class NextQuestion(APIView):    
    permission_classes = [IsAuthenticated]
    lookup_url_kwarg = 'old_questions'

    def post(self, request, format=None):
        old_questions = request.data.get(self.lookup_url_kwarg)

        if len(old_questions):
            old_questions_q = [Q(id=x) for x in old_questions]        
            questions_valides = Question.objects.exclude(reduce(operator.or_, old_questions_q))
            if len(questions_valides) == 0 :
                return Response("Il n'y a plus de questions disponibles!")
        else:
            questions_valides = Question.objects.all()
        
        index = randint(0, len(questions_valides) -1)
        new_question = QuestionSerializer(questions_valides[index]).data

        return Response(new_question)

我的序列化器:

class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Question
        fields = '__all__'

我的网址:

from django.contrib import admin
from django.urls import path, include, re_path
from django.views.generic import TemplateView

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    ######
    path('quiz/', include('quiz.urls')),
]

urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

在我的设置中:

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'build/static')
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

MEDIA_URL = '/media/'

在我的 .js 中:

<Fade in={!toggle} {...(!toggle ? { timeout: 2000 } : {})}>
    <Paper elevation={0} className={classes.paper}>
        <img className={classes.image} src={image} alt="La réponse." />
    </Paper>
</Fade >

我的应用组件:

const App = () => (
    <Provider store={store}>
        <SnackbarProvider maxSnack={5} >
            <Router>
                <Switch>                
                    <NavLayout>
                        <Route exact path='/' component={Home} />
                        <Route exact path='/login' component={Login} />
                        <Route exact path='/signup' component={Signup} />
                        <Route exact path='/reset-password' component={ResetPassword} />
                        <Route exact path='/password/reset/confirm/:uid/:token' component={ResetPasswordConfirm} />
                        <Route exact path='/activate/:uid/:token' component={Activate} />
                    </NavLayout>                
                </Switch> 
            </Router>
        </SnackbarProvider>        
    </Provider>    
);

export default App;

请求返回状态 200,但响应为空:

GET
    
scheme
    http
host
    127.0.0.1:8000
filename
    /media/images/quiz/cochon.png
Adresse
    127.0.0.1:8000
État200
OK
VersionHTTP/1.1
Transfert2,42 Ko (taille 2,17 Ko)
Politique de référentsame-origin

    
Content-Length
    2227
Content-Type
    text/html; charset=utf-8
Date
    Sun, 18 Apr 2021 08:18:28 GMT
Referrer-Policy
    same-origin
Server
    WSGIServer/0.2 CPython/3.9.2
Vary
    Origin
X-Content-Type-Options
    nosniff
X-Frame-Options
    DENY
    
Accept
    image/webp,*/*
Accept-Encoding
    gzip, deflate
Accept-Language
    fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3
Cache-Control
    max-age=0
Connection
    keep-alive
Cookie
    csrftoken=8e5HTXPQRNuesBbAC389HePJYYebgcKNS7Km60kP6uqURbIpNyA3khuuJPQK4V7M; djdt=hide; sessionid=ffneb7uu8ia5ly8f7w45a2ynbemz6886; PGADMIN_INT_KEY=7bde6f56-0a71-41e0-9953-f719d7135568; PGADMIN_LANGUAGE=en; tabstyle=html-tab
Host
    127.0.0.1:8000
Referer
    http://127.0.0.1:8000/
User-Agent
    Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:87.0) Gecko/20100101 Firefox/87.0

我的变量图像具有以下值:/media/images/quiz/animal-2029280_1280.png

它应该匹配与图像对应的路径,但它没有加载。我忘记操作了吗?还是参数错误?我只有图片有问题,其他都很好。

如果我在 localhost 8000 或 3000 上运行我的应用程序,我会得到相同的结果。

谢谢!

1 个答案:

答案 0 :(得分:1)

问题出在这两行代码中:

urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

第一个网址路径正则表达式模式匹配所有网址。因此,第二个无效。

要解决它,只需将顺序更改为这两行(或修改正则表达式以不匹配媒体网址)