yung peso
yung peso

Reputation: 1766

how to use my base.html template in a view for another app in Django?

I'm trying to implement a newsletter in my footer. My footer is stored in my base.html file, the problem is I need to render this template for a view in another app.

Here is my code:

@csrf_exempt
def new(request):
    if request.method == 'POST':
        sub = Subscriber(email=request.POST['email'], conf_num=random_digits())
        sub.save()
        message = Mail(
            from_email=settings.FROM_EMAIL,
            to_emails=sub.email,
            subject='Newsletter Confirmation',
            html_content='Thank you for signing up for the StockBuckets email newsletter! \
                Please complete the process by \
                <a href="{}/confirm/?email={}&conf_num={}"> clicking here to \
                confirm your registration</a>.'.format(request.build_absolute_uri('/confirm/'),
                                                    sub.email,
                                                    sub.conf_num))
        sg = SendGridAPIClient(settings.SENDGRID_API_KEY)
        response = sg.send(message)
        return render(request, 'index.html', {'email': sub.email, 'action': 'added', 'form': SubscriberForm()})
    else:
        return render(request, 'index.html', {'form': SubscriberForm()})

I want to replace both instance of index.html in the return statements from this view, to base.html. How would I go about doing that?

Upvotes: 1

Views: 717

Answers (1)

NavaneethaKrishnan
NavaneethaKrishnan

Reputation: 1318

In Django all the templates files will be collected in single templates folder. so we have to create something like this.

Django_project/
    app_1/
        ..
    app_2/
        ..
    app_3/
        ..
    Django_project/
        settings.py
        manage.py
    templates/
        app_1/
            base.html
            other.html
        app_2/
            base.html
            other.html
        app_3/
            base.html
            other.html
        other_common.html

or use can add the templates inside the app itself,

Django_project/
    app_1/
        templates/
            app_1/
                base.html
                other.html
    app_2/
        templates/
            app_1/
                base.html
                other.html

Now if you want to use the base template from another app, you add app_1/base.html in your render function.

Upvotes: 1

Related Questions