I know similar kind of question is asked before, but I was not able to get it. This is my first project as a Django beginner.
In my Django blog app, I made a delete button but it is not working and I am finding for answers, trying different methods on the web but it did not help.
I am trying to do is when admin open the post, then on clicking the delete button, it take the post-id and delete that post and redirect to home page, but it is not working as expected. So, lastly I came here. Any help will be appreciated. Thanks!
This is my urls.py file:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('post/<int:pk>', views.post, name='post'),
path('about', views.about, name='about'),
path('contact_us', views.contact_us, name='contact_us'),
path('register', views.register, name='register'),
path('login', views.login, name='login'),
path('logout', views.logout, name='logout'),
path('create_post', views.create_post, name='create_post'),
path('delete_post', views.delete_post, name='delete_post')
]
This is my views.py file:
def delete_post(request, *args, **kwargs):
pk = kwargs.get('pk')
post = get_object_or_404(Post, pk=pk)
if request.method == 'POST':
post.delete()
return redirect('/')
return render(request, 'delete-post.html')
This is delete post html form:
<form action="{% url 'delete_post' post.id %}" method="post">
{% csrf_token %}
<input type="submit" value="Delete post">
</form>
Delete button:
<button type="button" class="btn btn-danger" style="position:relative; right: -1145px;">Delete</button>
for deleting a post
def delete_post(request, id):
post = Post.objects.filter(id=id)
address.delete()
return redirect('/')
and in your html
<a class="btn btn-outline-danger" href="{% url 'appname:delete_post' id=post.id %}">Delete It</a>
and in your urls.py
path('<int:id>/delete-post',views.delete_post,name='delete_post')
Related
I'm new to Django, and I'm trying to submit a form to process the data in a view function, but I can't find why when I press the Send button it doesn't do anything. i read many other questions but were syntax related problems, which I believe is not my case.
Here's my form. It is in the new.html template:
<from action="{% url 'notes:create' %}" method="post">
{% csrf_token %}
<input type='text' name='note_name' id='note_name' placeholder='Title...'>
<input type='date' name='note_date' id='note_date'>
<input type="submit" value="Send">
</form>
Here it is urls.py:
app_name = 'notes'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('new/', views.new_note, name='new'),
path('output/', views.create_note, name='create')
]
And here the views.py file. Currently the create_note view only redirects to the index. I'm going to process the entered data once the form works correctly.
class IndexView(generic.ListView):
template_name = 'notes/index.html'
context_object_name = 'all_notes'
def get_queryset(self):
return Note.objects.all()
def new_note(request):
return render(request, 'notes/new.html')
def create_note(request):
return HttpResponseRedirect(reverse('notes:index'))
While using django 4.0.4 I have encountered the error "Reverse for 'upload' not found. 'upload' is not a valid view function or pattern name". It was working earlier in the day, and I can't figure out the problem for the life of me. I'll include my views.py, urls.py, and the relevant section of my html file, all three of which are in the same folder of the project. If anyone has any advice I would greatly appreciate it.
Views.py
def welcome(request):
return render(request, 'welcome.html')
def contact(request):
return render(request, 'contact-us.html')
def how(request):
return render(request, 'How-to-use.html')
def upload(request):
if request.method == 'POST':
if 'scatter_plot' in request.POST:
form = UploadFileForm(request.POST.get, request.FILES)
file=request.FILES['document']
csv = CSV.objects.create(doc=file)
os.system('python ../scatter_plot.py')
if 'line_plot' in request.POST:
form = UploadFileForm(request.POST.get, request.FILES)
file=request.FILES['document']
csv = CSV.objects.create(doc=file)
os.system('python ../line_plot.py')
return render(request, 'uploaded.html')
else:
form = UploadFileForm
Urls.py
urlpatterns = [
path('', views.welcome),
path('admin/', admin.site.urls),
path('contact-us/', views.contact),
path('upload.html', views.upload),
path('upload/', views.upload),
path('welcome/', views.welcome),
path('How-to-use/', views.how),
path('contact-us.html', views.contact),
path('welcome.html', views.welcome),
path('How-to-use.html', views.how)
]
Welcome.html
<form method="POST" enctype="multipart/form-data" action="{% url 'upload' %}">
{% csrf_token %}
<input type='file' name='document' accept='.csv'>
<button type='submit' name='line_plot'>Graph as a line Graph</button>
<button type='submit' name='scatter_plot'>Graph as a Scatter Plot</button>
</form>
you need to put the name for the URL
path('upload/', views.upload, name='upload'),
Refer this
https://docs.djangoproject.com/en/4.0/topics/http/urls/#reversing-namespaced-urls
https://docs.djangoproject.com/en/4.0/topics/http/urls/
The Form in register.html request for POST method but GET method is working. Submit is calling register method in views.py using GET method, but this shouldn't be happening.
Error :
Request Method: POST
Request URL: http://127.0.0.1:8000/Profile/register/register/
views.py
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.contrib.auth.models import User
from django.contrib import messages
def register(request):
if request.method == 'POST':
return redirect('/')
else:
return render(request, 'register.html')
register.html
<form action="register" method="post">
{% csrf_token %}
<input type="Submit">
</form>
urls.py of Project
from re import template
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')),
path('Profile/', include('Profile.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('login/', auth_views.LoginView.as_view(template_name="login.html"),
name='login'),
path('logout/', auth_views.LogoutView.as_view(),
name='logout'),
path('reset_password/', auth_views.PasswordResetView.as_view(),
name = 'reset_password'),
path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(),
name='password_reset_done'),
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(),
name='password_reset_confirm'),
path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(),
name='password_reset_complete')
]
urls.py of Profile app
from django.urls import path
from Profile import views
urlpatterns = [
path('profile/', views.profile, name='profile'),
path('register/', views.register, name='register'),
]
The URL is register/. Because you do not use a trailing slash, Django will make a redirect with a slash, but that will thus result in a GET request, not a POST request.
You thus should work with:
<form action="/profile/register/" method="post">
{% csrf_token %}
<input type="Submit">
</form>
or better is to work with the {% url … %} template tag [Django-doc]:
<form action="{% url 'register' %}" method="post">
{% csrf_token %}
<input type="Submit">
</form>
I want to save data from HTML template into database Model. I want to override this toplaner_name, toplaner_avatar, toplaner_price everytime I submit the Form. The img and span tags are dynamically changing by JS
template
<form method='POST'>
{% csrf_token %}
<div class="player-on-map toplaner">
<img class='img-on-map' src="{% static 'images/ago/img1.png' %}" alt="portrait-on-map">
<span class="nickname">Szygenda</span>
<span>Price: 1500</span>
</div>
<button type='submit'>SAVE TEAM</button>
</form>
models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return f'{self.user.username} Profile'
class Team(models.Model):
toplaner_name = models.CharField(max_length=30, default='k1ck/Ibo')
toplaner_avatar = models.ImageField(default='avatar.png')
toplaner_price = models.IntegerField()
JS
toplaners.forEach(toplaner => toplaner.querySelector('.btn').addEventListener('click', function(){
toplaner_on_map.innerHTML = toplaner.innerHTML;
toplaner_on_map.querySelectorAll('.btn, .position, .player-price').forEach(item => item.classList.add('hide'))
}))
urlpatterns = [
path('', views.home, name='home'),
path('register/', views.register, name='register'),
path('login/', auth_views.LoginView.as_view(template_name='profilecontent/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='profilecontent/logout.html'), name='logout'),
path('profile/', views.profile, name='profile')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
First of all you have to make one URL in urls.py as below...
urlpatterns = [
path('', views.home, name='home'),
path('register/', views.register, name='register'),
path('login/', auth_views.LoginView.as_view(template_name='profilecontent/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='profilecontent/logout.html'), name='logout'),
path('profile/', views.profile, name='profile'),
# Add new URL
path('toplaner/', views.toplaner, name='toplaner'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Then add toplaner view in views.py as below...
def toplaner(request):
# Here you can get all the form data
if request.method == 'POST':
field_name = request.POST.get('field_name_in_html_form')
# Add all other required field here
Then you have to add action url in form as below...
<form method='POST' action="{% url 'toplaner' %}">
{% csrf_token %}
<div class="player-on-map toplaner">
<img class='img-on-map' src="{% static 'images/ago/img1.png' %}" alt="portrait-on-map">
<span class="nickname">Szygenda</span>
<span>Price: 1500</span>
</div>
<button type='submit'>SAVE TEAM</button>
</form>
Now, when you press submit button you will get your form data in toplaner view and at there you can write your further logic.
After log out user in my django web app, the redirected homepage still displays the "Log Out" button instead of the "Sign in with Facebook". In the following code, I follow the django documentation to logout the user and redirect the page to homepage which is the base.html. It seems that my web app still has user.is_authenticated as True after log out? What am I missing?
I cannot find any useful hint online. Any comment is much appreciated.
Here is part of my template html
<div class="navbar-form navbar-right">
{% if user.is_authenticated %}
<a id="logout" href="/accounts/logout" class="btn btn-success">Logout</a>
{% else %}
<a id="facebook_login" href="/accounts/facebook/login" class="btn btn-success">Sign in with Facebook</a>
{% endif %}
</div>
Here is my urls.py
url(r'^$', 'homepage.views.home', name='home'),
url(r'^accounts/', include('allauth.urls')),
url(r'^accounts/logout/$', 'homepage.views.logout', name='logout'),
Here is my homepage/views.py
# Create your views here.
def home(request):
return render(request, "base.html", {})
# ensure only logged in users can access the view.
#login_required
def logout(request):
logout(request)
# Take the user back to the homepage.
return redirect('home')
There are 2 things here:
You need to reorder the URLs
from:
url(r'^accounts/', include('allauth.urls')),
url(r'^accounts/logout/$', 'homepage.views.logout', name='logout'),
to
url(r'^accounts/logout/$', 'homepage.views.logout', name='logout'),
url(r'^accounts/', include('allauth.urls')),
This way, your logout takes precedence over the allauth's logout URL pattern
You should be aliasing the imported logout, or rename your logout to something different.
Example:
from django.contrib.auth import logout as auth_logout
and then
def logout(request):
auth_logout(request)
....