0

how can i change url in django with javascript without refreshing

this is my code and it doesn't work

// script js
$(document).ready(function() {

    // initial   
     $("#contenu").load("{% url home %}");

    // au clic
    $('#lien li a').click(function() {
        var page = $(this).attr("href");
        $("#contenu").load("html/" + page + ".html");
        return false;
     });
});

// urls.py

urlpatterns = [
path('admin/', admin.site.urls),
path('index', views.index, name='index'),
path('index/home',views.home name="home"),
path('contact',views.contact),
path('about',views.about),]
2
  • Do you mean changing the page address without going to that page? Commented Nov 20, 2019 at 7:16
  • in reality I want to change the content of the page without refreshing when I click on a link on my menu Commented Nov 20, 2019 at 7:29

2 Answers 2

1

I am pretty sure you should just change {% url home %} to /index/home

Sign up to request clarification or add additional context in comments.

Comments

0

Are you referring to Single Page Application? You can use Django to serve the API endpoints and use a different router for front end.

I chose React and react-router-dom in this case.

import React, { Component } from "react";
import ReactDOM from "react-dom";
import {
  Route,
  NavLink,
  HashRouter
} from "react-router-dom";
import Home from "./Home";
import About from "./About";
import Contact from "./Contact";


class App extends Component {
    render() {
        return (
            <HashRouter>
                <div>
                    <h1>My App</h1>
                    <ul className="header">
                        <li><NavLink to="/home">Home</NavLink></li>
                        <li><NavLink to="/about">About</NavLink></li>
                        <li><NavLink to="/contact">Contact</NavLink></li>
                    </ul>
                    <div className="content">
                        <Route path="/home" component={Home}/>
                        <Route path="/about" component={About}/>
                        <Route path="/contact" component={Contact}/>
                    </div>
                </div>
            </HashRouter>
        )
    }
}

mysite/urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('app1.urls')),
]

app1/urls.py -- Your frontend will use ajax or axios to call these endpoints to login or register a user, for example.

urlpatterns = [
    path('login' views.login, name='home'),
    path('register', views.register),
]

I find this tutorial really helpful when setting up webpacker for React.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.