How to use model views in other apps

So I have 2 apps in django, issues and users. Can I use issues's model methods inside my users app? Here’s part of my code to better illustrate what I’m asking to do.

issues/views.py

from django.shortcuts import render, get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.views.generic import (
    ListView,
    DetailView,
    CreateView,
    UpdateView,
    DeleteView
)
from .models import Issue


def home(request):
    context = {
        'issues': Issue.objects.all()
    }
    return render(request, 'issues/home.html', context)

class UserAccesMixin(UserPassesTestMixin):
    def test_func(self):
        user = self.request.user
        return user.groups.filter(name='Manager').exists() or self.get_object().author == user

# def dashboard(request):
#     total_issues = Issue.objects.all().count()
#     open_issues = Issue.objects.filter(mark_as=True).count()
#     closed_issues = Issue.objects.filter(mark_as=False).count()

#     context = {'total_issues': total_issues, 
#             'open_issues': open_issues,
#             'closed_issues': closed_issues}
#     return render(request, 'issues/total_issues.html', context)
    

class IssueListView(ListView):
    model = Issue
    template_name = 'issues/home.html'
    context_object_name = 'issues'
    ordering = ['-date_posted']
    paginate_by = 5
    

    def total():
        open_issues = Issue.objects.filter(mark_as=True).count()
        closed_issues = Issue.objects.filter(mark_as=False).count()
        context = { 
                'open_issues': open_issues,
                'closed_issues': closed_issues}
        return context
    
    
    

class UserIssueListView(ListView):
    model = Issue
    template_name = 'issues/user_issues.html'
    context_object_name = 'issues'
    paginate_by = 5

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Issue.objects.filter(author=user).order_by('-date_posted')
    

class IssueDetailView(DetailView):
    model = Issue


class IssueCreateView(LoginRequiredMixin, CreateView):
    model = Issue
    fields = ['title', 'content', 'mark_as', 'assignee']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

class IssueUpdateView(LoginRequiredMixin, UserAccesMixin, UpdateView):
    model = Issue
    fields = ['title', 'content', 'mark_as', 'assignee']
    

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)
    
class IssueDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Issue
    success_url = '/'

    def test_func(self):
        issue = self.get_object()
        if self.request.user == issue.author:
            return True
        return False


def about(request):
    return render(request, 'issues/about.html', {'title': 'About'})

users/views.py

from django.shortcuts import redirect, render
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm

def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account created for {username}!')
            return redirect('issues-home')
    else:
        form = UserRegisterForm()
    return render(request, 'users/register.html', {'form': form})



@login_required
def profile(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST,
                                    request.FILES,
                                    instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, f'Your account has been updated!')
            return redirect('profile')

    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)
    
    context = {
        'u_form': u_form,
        'p_form': p_form
    }

    return render(request, 'users/profile.html', context)

issues/urls.py

urlpatterns = [
    path('', IssueListView.as_view(), name='issues-home'),
    
    path('user/<str:username>', UserIssueListView.as_view(), name='user-issues'),
    path('issues/<int:pk>/', IssueDetailView.as_view(), name='issue-detail'),
    path('issues/new/', IssueCreateView.as_view(), name='issue-create'),
    path('issues/<int:pk>/update/', IssueUpdateView.as_view(), name='issue-update'),
    path('issues/<int:pk>/delete/', IssueDeleteView.as_view(), name='issue-delete'),
    path('about/', views.about, name='issues-about'),
]

urls.py for users inside the base project

urlpatterns = [
    path('admin/', admin.site.urls),
    path('register/', user_views.register, name='register'),
    path('profile/', user_views.profile, name='profile'),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path('password-reset/',
         auth_views.PasswordResetView.as_view(
             template_name='users/password_reset.html'
         ),
         name='password_reset'),
    path('password-reset/done/',
         auth_views.PasswordResetDoneView.as_view(
             template_name='users/password_reset_done.html'
         ),
         name='password_reset_done'),
    path('password-reset-confirm/<uidb64>/<token>/',
         auth_views.PasswordResetConfirmView.as_view(
             template_name='users/password_reset_confirm.html'
         ),
         name='password_reset_confirm'),
    path('password-reset-complete/',
         auth_views.PasswordResetCompleteView.as_view(
             template_name='users/password_reset_complete.html'
         ),
         name='password_reset_complete'),
    path('', include('issues.urls')),
]

Don’t think of page construction in terms of your templates.

Your views are building your pages. The templates are just some text used by the view for producing those pages. It’s the view that accepts the request from the browser and returns a response.

What your templates look like is almost irrelevant. What matters are the views, and the context that those views create to use when rendering your templates.

Or, another way to say this is that you should be thinking that your “pages” are your views. The views (generally) fetch data from the database, pass that data (the context) to the rendering engine. The rendering engine builds some text from a template and the context, and returns it to the view. The view then sends that data back out to the browser. (That data could be html. It could also be JSON, XML, or even something else.)

All this comes around to saying that we need to see the views here.

1 Like

Wow thanks, that was super informative. I’ve edited the original post to show both my views and urls.py

The direct answer to your question is yes. You can import code from other apps and use it in the same way you would use code from the current app.

What do I do? Are there documentation i can read?

When you’re writing a view, how do you import a model?

from .models import ModelName

Good.

You have:
from .models

The .models is a reference to the current app.
from other_app.models ... would then be a reference to the models in a different app.

Then I would import the views like so from other_app.models import views?

The views aren’t in the models files. The views are in the views files, so it would be other_app.views.

Alright I think I got it now. Thanks!