Repository
What Will I Learn?
- URL Behavior
- Update View and Edit Menu
Requirements
- Basic Python
- Install Python 3
- Install Django
Resources
- Python - https://www.python.org/
- Django- https://www.djangoproject.com/
- Bootstrap 4 - https://getbootstrap.com/docs/4.0/getting-started/introduction/
Difficulty
Basic
Tutorial Content
We will continue with the application tutorial forums that we have created so far. a lot has been done in this tutorial. there are some important things that you should not miss it. I suggest you follow the previous tutorial in the curriculum section. In the previous tutorial, we learned how to make detailed views and also learn how to pass parameters to a class view by using the get_context_data ()
method. Now in this tutorial I will update view and edit view. but before that, I will give you tricks and suggestions regarding the importance of the order of URLs on views.py
URL Behavior
There are some problems when we want to create a URL with dynamic parameters. as happened in the previous tutorial we used Slug on our URL. For more details, we can see forums/views.py:
We can see in the example image above, the URL with the slug parameter is in the first path position. Of course, this slug value will be dynamic. On the other hand, we also have a URL with the first path being 'add/'
.
Of course, this will be ambiguous. Because the URL system will recognize that the 'add /'
path is also part of the slug parameter in the path <slug: slug>/
and when this application is run we will see an error like the picture below:
This error message appears because the Django URL system recognizes 'add/'
as a Slug parameter. to solve this problem we need to recognize the behavior of the system URL in Django. In Django, the URL order is very important. URL order can be a priority on the system to read the URL. For more details we can see the code:
from django.urls import path
from .views import ForumCreate, ForumListView, ForumUserListView, ForumDetailView
urlpatterns = [
path('', ForumListView.as_view(), name='forum-list'),
path('add/', ForumCreate.as_view(), name='forum-add')
path('<slug:slug>/', ForumDetailView.as_view(), name='forum-detail'),
path('by/<username>/', ForumUserListView.as_view(), name='forum-by'),
]
I will move the path path('', ForumListView.as_view(), name='forum-list')
above path('<slug:slug>/', ForumDetailView.as_view(), name='forum-detail'),
. Now you can eliminate the error message that appears earlier:
And the problem has been resolved, now you have understood the behavior of the URL system in Django.
Update View
Now we go to Update view. Of course, data updates are common in an application. in Django, we have our own way to update our data. for more details, just go ahead and create the URL and create a class view that we will use in this update system:
forums/urls.py
from django.urls import path
from .views import ForumCreate, ForumListView, ForumUserListView, ForumDetailView, ForumUpdateView // import class ForumUpdateView
urlpatterns = [
path('', ForumListView.as_view(), name='forum-list'),
path('add/', ForumCreate.as_view(), name='forum-add'),
path('edit/<int:pk>', ForumUpdateView.as_view(), name='forum-edit'), //Define URL edit/update
path('<slug:slug>/', ForumDetailView.as_view(), name='forum-detail'),
path('by/<username>/', ForumUserListView.as_view(), name='forum-by'),
]
The first step we have to do is import the class view that we will use. here I will give the name ForumUpdateView, make sure the name you give is relevant to the usefulness of the class.
then you can use the class that you imported to use in the path
path('edit/<int:pk>', ForumUpdateView.as_view(), name='forum-edit')
. In this path we will pass one additional parameter after editing, the parameter is type integer and primary keyedit/<int:pk>
. Later on, we will pass the ID from each forum id and don't forget to give an alias so that we can more easily call latername='forum-edit'
.
Now we switch to forums/views.py, We imported the ForumUpdateView class. But we haven't defined it in views.py class for that we will define it as follows:
from django.shortcuts import render, get_object_or_404
from django.views.generic import CreateView, ListView, DetailView, UpdateView
from .models import Forum
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
class ForumUpdateView(UpdateView):
model = Forum
fields = ['title','desc']
The code above is a code snippet because what we will discuss is only in the ForumUpdateView class.
In the ForumUpdateView class, we will use UpdateView as a parameter class
ForumUpdateView(UpdateView)
. UpdateView is a generic class that has been provided by Django. We have discussed the generic class in the previous tutorial,In this class we will use the Forum model
model = Forum
, that we imported abovefrom .models import Forum
. Then we can define any fields that we will update. Here I will only update two fields, namely title and descfields = ['title','desc']
.
Restrict access to edit view
Of course, not just anyone will be allowed to edit data. there are different conditions for each application. well in this forum application we don't allow other users to edit other user forums. So the user can only edit the contents of their own forum. We need a button as an interface to go to the edit URL. I will appear on the interface at forum_detail.html.
forums/forum_detail.html
{% extends "base.html" %}
{% load humanize %}
{% block title %} {{object.title}} {% endblock %}
{% block content %}
<div class="jumbotron">
<h1>{{object.title}}</h1>
{% if request.user == object.user %} // only the user who created the forum
<a href="{% url 'forum-edit' object.id %}">Edit</a>
{% endif %}
<p style="font-size: 20px;">{{ object.desc }}</p>
- <span><i>{{object.created_at | naturaltime}}</i></span>
<p>{{additional}}</p>
</div>
{% endblock%}
to limit it we can compare the value of
request.user
withobject.user
. If the result is the same or true. then<a>
tag will appear and we can click it to go to the edit menu. We can access the user who is logged on the request object and for data from forums we can take from object values.Then in the
<a>
tag, we will render the URL for the forum edit menu<a href="{% url 'forum-edit' object.id %}">Edit</a>
. to render it we can call the alias if you still remember the alias name of the edit URL is 'forum-edit' and for the parameters, we can take it from object.id.
If there is no error, then we can see the results as shown below, I will log in with an admin account as milleaduski.
In accordance with the expectations that we have expected. We cannot edit forums that are not ours. Here I can't edit the forums owned by user milleaduski1994. because I logged in as milleaduski.
Edit Menu
now we will enter the edit section of the forum. In this section we will learn how to edit forum data and not only that, we will also learn new things, set templates that we will render in the ForumUpdateView class. For more details, we can see the code below:
forums/views.py
class ForumUpdateView(UpdateView):
model = Forum
fields = ['title','desc']
template_name = 'forums/forum_update_form.html' // set template
- To set up templates is very easy. we only need key
template_name
and then the name of the template directory that will be rendered'forums/forum_update_form.html'
.
Keep in mind we have set our template directory in the previous tutorial. the following picture will explain it briefly:
- Create view forum_update_form.html
Now we will create a view for the forum edit menu. This is not much different from the menu add forums. For more details, we can see in the example below:
forums/forum_update_form.html
{% extends "base.html" %}
{% block title %} Edit Forum {% endblock %}
{% block content %}
<h2>Edit Forum</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" name="button">Update</button>
</form>
{% endblock%}
{{ form.as_p }}
will render the form that we define automatically, this is a function that has been provided by Django. If there is no error then we can see the results like the demonstration below:
Now we can see in the picture above, we have successfully updated the forum data and the update menu can only be accessed by the user who created the forum.
Curriculum
- Forum app
Create a forum application using django #1 : Init projects and dependencies and Database schema
Create a forum application using django #2: Template system and Class-based view implementation
Create a forum application using django #3: Base template, Login and Register system
Create a forum application using django #4: Admin dashboard ang setting redirect
Create a forum application using django #6: CRUD system and URL protection,redirect system
Create a forum application using django #7: Unique slug and Manage Modules in admin dashboard
Thank you for your contribution @duski.harahap.
After reviewing your contribution, we suggest you following points:
Again a good tutorial about django. Good job!
Please don't forget to put comments in your code. As you know, the brief comments greatly help less experienced users understand your code.
The section of your curriculum begins to get big in the contribution, could put for example:
Curriculum: django#1, django#2...
Thank you for your work in developing this tutorial.
Looking forward to your upcoming tutorials.
Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.
To view those questions and the relevant answers related to your post, click here.
Need help? Chat with us on Discord.
[utopian-moderator]
Thank you for your review, @portugalcoin! Keep up the good work!
Hi @duski.harahap!
Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server
Hey, @duski.harahap!
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!
Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!