简体   繁体   中英

Is it possible to create a unique Django path for each row in a pandas dataframe?

I have a Django project that takes information in each row of a pandas dataframe and displays the contents on the page. I'd like to separate each row of the dataframe into its own page with its own unique path. There are too many rows in the dataframe to hard code each row in the context of the views.py file. How would I go about creating a unique url path for each row? Is this even possible?

You probably want to do something like embed the row as a parameter in the url

like

http://example.com/pandasdata/<row>

In your view your would extract the row from the url and extract only that data from the pandas dataframe and display that.

In your application urls.py File Add Following code

path('pandasdata/< int:rowid >', views.row)

In your application views.py file, add following code:

def row(request, rowid):
  # Add code to extract row and display here

Make sure both place name should be same (rowid)

The answer above is exactly correct and just what I was looking for. I'd just like to elaborate on this for anyone stumbling across this question in the future.

As stated in the answer, in the urls.py file add the path that allows you extract row information. Something like:

path("data/<int:row_id>/", views.app)

Then in your views.py file, you'll be able to access the row information like this:

def func(request, row_id):
    row_id = row_id
    x = row_id
    df1 = df.iloc[x]
    return render(request, "data/app.html", {
        "col1": df1['col1'],
        "col2": df1['col2'],}

Now when you visit a path like http://example.com/data/100/ for example, it will load the row with that index from the dataframe, along with whatever information from the columns that you have set in the context. Or if the number is outside the number of rows in your database it will throw you an error.

Thanks to WombatPM for the original answer!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM