无法在Django中使用另一个应用程序的数据

时间:2018-04-15 19:52:34

标签: python django django-templates django-views modelform

我的django项目中有三个应用程序(实习,UserProfile和基础设施)。我在UserProfile模型中创建了模型Profile和StudentProject。 StudentProject模型包含两个外键 - > user和Lab(此模型在Infrastructure模型中定义)。在基础架构应用程序中的模板(details.html文件)中,我想要检索所有将其外键作为实验室的StudentProjects,其实际显示详细信息。我无法带来在这里创建的学生项目。请帮助别人。我已经尝试使用过滤器,但它不起作用!

userprofile / models.py文件

from django.conf import settings
from django.db import models
from django.core.urlresolvers import reverse
from infrastructure.models import Lab


class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    type = models.CharField(max_length=100)
    profile_picture = models.FileField()
    skills = models.CharField(max_length=1000)

    def get_absolute_url(self):
        return reverse('userprofile:index')

    def __str__(self):
        return self.name


class StudentProject(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    project_picture = models.FileField()
    lab = models.ForeignKey(Lab)
    mentor = models.CharField(max_length=100)
    domain = models.CharField(max_length=100)
    description = models.CharField(max_length=1000)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('userprofile:index')

infrastructure / models.py文件

from django.db import models
from django.core.urlresolvers import reverse


class Lab(models.Model):
    name = models.CharField(max_length=100)
    department = models.CharField(max_length=100)
    description = models.CharField(max_length=1000)
    lab_logo = models.FileField()

    def get_absolute_url(self):
        return reverse('infrastructure:details', kwargs={'pk': self.pk})

    def __str__(self):
        return self.name

基础设施/模板/ details.html - >这是我想要展示实验室所有学生项目的地方

{% extends 'infrastructure/base.html' %}
{% block body %}
    <h1>This is details page</h1>
    <img src="{{ lab.lab_logo.url }}" style="width: 300px;">
    <h1>{{ lab.name }}</h1>
    <h2>{{lab.projects}}</h2>
{% endblock %}

基础架构/ views.py文件

from django.core.urlresolvers import reverse_lazy
from django.views import generic
from infrastructure.models import Lab
from django.views.generic.edit import CreateView, UpdateView, DeleteView


class IndexView(generic.ListView):
    template_name = 'infrastructure/index.html'
    context_object_name = 'all_labs'

    def get_queryset(self):
        return Lab.objects.all()


class DetailView(generic.DetailView):
    model = Lab
    template_name = 'infrastructure/details.html'


class LabCreate(generic.CreateView):
    model = Lab
    fields = ['name', 'department', 'description', 'lab_logo']


class LabUpdate(generic.UpdateView):
    model = Lab
    fields = ['name', 'department', 'description', 'lab_logo']


class LabDelete(DeleteView):
    model = Lab
    success_url = reverse_lazy('infrastructure:index')

infrastructure / urls.py文件

from django.conf.urls import url

from . import views

app_name = 'infrastructure'

urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='details'),

    url(r'^lab/add/$', views.LabCreate.as_view(), name='lab-add'),
    url(r'^lab/(?P<pk>[0-9]+)/$', views.LabUpdate.as_view(), name='lab-update'),

    url(r'^lab/(?P<pk>[0-9]+)/delete/$', views.LabDelete.as_view(), name='lab-delete'),
]

userprofile / views.py文件

from django.contrib.auth import login, authenticate, logout
from django.http import request
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse_lazy

from .models import Profile, StudentProject
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .forms import UserForm
from django.views import generic
from django.views.generic import View


class IndexView(generic.TemplateView):
    template_name = 'userprofile/index.html'
    context_object_name = 'user_profile'

    def get_queryset(self):
        return request.user.get_profile()


class ProfileCreate(CreateView):
    model = Profile
    fields = ['user', 'name', 'type', 'profile_picture', 'skills']


class ProfileUpdate(UpdateView):
    model = Profile
    fields = ['user', 'name', 'type', 'profile_picture', 'skills']


class StudentProjectCreate(CreateView):
    model = StudentProject
    fields = ['user', 'title', 'project_picture', 'lab', 'mentor', 'domain', 'description']


class StudentProjectUpdate(UpdateView):
    model = StudentProject
    fields = ['user', 'title', 'project_picture', 'lab', 'mentor', 'domain', 'description']


class StudentProjectDelete(DeleteView):
    model = StudentProject
    success_url = reverse_lazy('userprofile:index')


def logout_view(request):
    logout(request)
    return render(request, 'userprofile/logout.html')


# for new user
class UserFormView(View):
    form_class = UserForm
    template_name= 'internship/registration_form.html'

    # display blank form
    def get(self, request):
        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})

    # process from data
    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():
            user = form.save(commit=False)

            # cleaned (normalized) data
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user.set_password(password)
            user.save()

            # return User object if credentials are correct
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect('userprofile:profile-add')

        return render(request, self.template_name, {'form': form})

userprofile / urls.py文件

from django.conf.urls import url, include
from django.contrib.auth import views as auth_views

from userprofile import views

app_name = 'userprofile'


urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^profile/add/$', views.ProfileCreate.as_view(), name='profile-add'),
    url(r'^profile/(?P<pk>[0-9]+)/$', views.ProfileUpdate.as_view(), name='profile-update'),
    url(r'^logout$', views.logout_view, name='logout_view'),
    url(r'^login/$', auth_views.login, {'template_name': 'userprofile/login.html'}),
    url(r'^register/$', views.UserFormView.as_view(), name='register'),
    url(r'^studentproject/add/$', views.StudentProjectCreate.as_view(), name='student-project-add'),
    url(r'^studentproject/(?P<pk>[0-9]+)/$', views.StudentProjectUpdate.as_view(), name='student-project-update'),
    url(r'^studentproject/(?P<pk>[0-9]+)/delete/$', views.StudentProjectDelete.as_view(), name='student-project-delete'),
]

1 个答案:

答案 0 :(得分:0)

基本上,您需要在StudentProject Model中的Lab Field声明中添加 related_name 参数。这将使儿童可以从父模型进一步访问:

class StudentProject(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    project_picture = models.FileField()
    lab = models.ForeignKey(Lab, related_name=projects)
    ...

现在,在您的模板中,您可以轻松地迭代当前实验室的项目:

{% extends 'infrastructure/base.html' %}
{% block body %}
    <h1>This is details page</h1>
    <img src="{{ lab.lab_logo.url }}" style="width: 300px;">
    <h1>{{ lab.name }}</h1>
    {% for project in lab.projects_set.all %}
    <h2>{{project.title}}</h2>
    {% endfor %}
{% endblock %}