I'm new to Django and i try my best to resolve this problem.
So i try to create a delete button on my template. I create my view and i create my url but it doesn't work.
So here my views :
def book_delete(request, pk):
book = get_object_or_404(Book, pk=pk)
if request.method == 'POST':
book.delete()
return redirect('/')
return render(request, "livre/newbook_form.html", {'form': book})
My urls
from . import views
from django.conf.urls import url
urlpatterns = [
url(r'^livre/(?P<pk>[0-9]+)/$', views.book_delete, name='book_delete')
]
My template
<form action="liste" method="POST">{% csrf_token %}
<table>
<th>Titre</th><th>Auteur</th><th>Nombre de pages</th><th>Supprimer</th>
{% for Book in Book %}
<tr>
<td>{{ Book.title }}</td>
<td>{{ Book.author }}</td>
<td>{{ Book.num_pages }}</td>
<td>
<form action="{% url 'book_delete' Book.id %}" method="POST">
{% csrf_token %}
<input type="button" value="{{Book.id}}"/>
</form>
</td>
</tr>
{% endfor %}
</table>
</form>
I don't know why it doesn't work. Can you help me ?
You need to submit the form, so with type="submit" [dev-mozilla]:
<form action="{% url 'book_delete' Book.id %}" method="POST">
{% csrf_token %}
<input type="submit" value="delete"/>
</form>
Related
here is my project code .
I after posting data by form nothing happens.
#model.py
from django.db import models
from projectapp.models import Project
class Productbacklog(models.Model):
project=models.ForeignKey(Project,on_delete=models.CASCADE,default=None)
pbId=models.IntegerField(primary_key=True)
pbTitle=models.CharField(max_length=100)
pbPriority=models.IntegerField(blank=True, null=True)
class Meta:
unique_together=('project','pbId')
def __str__(self):
return self.pbTitle
#forms.py
from django import forms
from productbacklogapp.models import Productbacklog
from projectapp.models import Project
class ProductbacklogForm(forms.ModelForm):
class Meta:
model = Productbacklog
exclude=('pbId','project')
fields=['pbTitle']
#views.py
def productbacklogall(request):
if request.method == 'POST':
form = ProductbacklogForm(request.POST)
if form.is_valid():
form.instance.manage = Project.objects.get_or_create(cname=form.cleaned_data['manage_id'])
form.save()
messages.success(request, ('new productbacklog added'))
return redirect('productbacklogall')
else:
pb_all=Productbacklog.objects.all()
return render(request, 'productbacklogall.html', {'pb_all':pb_all})
I think that issue is on forms.py or views.py but I can't find it.
I'm so greatful if anyone can help me.
here is also my html code,when I submit something the method is post but I don't know why it doesn't go to data basse.
#productbacklogall.html
{%extends 'base.html'%}
{%block title%}
<title>backlog all</title>
{%endblock title%}
{%block content%}
</br>
{% if messages %}
{% for message in messages %}
<div class="alert alert-primary" role="alert">
{{ message }}
×
</div>
{% endfor %}
{% endif %}
<div class="container">
<form method="POST" class="row">
{% csrf_token %}
<label class="col-lg-4"></label>
<input type="text" class="form-control" name="Project" placeholder="project title?"/>
<input type="number" class="form-control" name="pbId" placeholder="backlog id?"/>
<input type="text" class="form-control" name="pbTitle" placeholder="pb title?"/>
<button type="submit" class="btn btn-primary col-lg-2">add project</button>
</form>
</div>
</br>
</br>
<table class="table table-bordered text-center">
<thead class="thead-dark">
<tr>
<th scope="col"> backlog-title</th>
<th scope="col">Edit</th>
<th scope="col">delivarable_task</th>
<th scope="col">related project</th>
</tr>
</thead>
<tbody>
{% load static %}
{% if pb_all %}
{% for obj in pb_all %}
<tr>
<td>{{ obj.pbTitle }}</td>
<td><a href='{% url "delete_productbacklog" obj.pbId %}'>delete</a></td>
<td> <a href=#> delivarabletask </a></td>
<td>{{ obj.project.pbTitle }}</td>
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
</div>
{%endblock content%}
Your form data are not valid, to see them, add this code to your views :
else:
messages.error(request, "Error")
like this :
def productbacklogall(request):
if request.method == 'POST':
form = ProductbacklogForm(request.POST)
if form.is_valid():
form.instance.manage = Project.objects.get_or_create(cname=form.cleaned_data['manage_id'])
form.save()
messages.success(request, ('new productbacklog added'))
else:
messages.error(request, "Error")
return redirect('productbacklogall')
else:
pb_all=Productbacklog.objects.all()
return render(request, 'productbacklogall.html', {'pb_all':pb_all})
I am listing all our plans with a subscribe button as follows (django template syntax):
{% for plan in plans %}
<tr>
<td>{{ plan.name }}</td>
<td>£{{ plan.price_human }}</td>
<td>
<form method="POST" action=".">
{% csrf_token %}
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ public_key }}"
data-image="/static/images/logo-n.png"
data-name="Product Name"
data-description="{{ plan.name }}"
data-currency="{{ plan.currency }}"
data-amount="{{ plan.price }}"
data-locale="{{ request.LANGUAGE_CODE }}"
data-email="{{ user.email }}"
data-label="{% trans 'Subscribe' %}"
data-panel-label="{% trans 'Subscribe' %}"
data-allow-remember-me="false"
>
</script>
</form>
</td>
</tr>
{% endfor %}
Then I am creating the customer/subscription in response to this form being POSTed:
class SubscribePageView(generic.TemplateView):
def post(self, request, *args, **kwargs):
stripe.api_key = settings.STRIPE_SECRET_KEY
user = self.request.user
token = request.POST.get('stripeToken')
customer = stripe.Customer.create(
source=token,
plan=[[WHERE DOES THIS COME FROM??]],
email=user.email,
)
user.customer_id = customer.id
user.save()
But at that point I don't have the plan ID to pass back to Stripe. :/.
Am I doing this all kinds of wrong?
All the Stripe checkout script does is insert the token into a hidden field in your form, and then submit the whole form to your server. If you need any other information such as the plan, you should include that in your form too:
<form method="POST" action=".">
{% csrf_token %}
<input type="hidden" name="plan" value="{{ plan.id }}">
<script....>
</form>
Now you can access the plan via request.POST['plan'].
In a Django project, my homepage view is as follows:
#login_required
def home(request):
return render(request, 'home.html')
So that when someone tries to access the homepage, they're automatically taken to a login form if no one is logged in. Here's that form, straight from the Django docs:
{% extends "base.html" %}
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="{% url django.contrib.auth.views.login %}">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
{% endblock %}
Once someone logs into the form, they get taken to the homepage which looks like this:
{% extends "base.html" %}
{% block content %}
<form method="post" action="{% url django.contrib.auth.views.logout_then_login %}">
{% csrf_token %}
<input type="submit" value="logout" />
</form>
<h1>Home Page</h1>
{% endblock %}
As you can see, I've attempted to create a logout button that will take the user right back to the login page. However, I noticed that when first arriving at the login page, the URL ends in ?next=/, whereas once I "logout", the "login" page I'm taken to has a URL lacking ?next=/. And when I try to login using that page, I'm sent to the URL /accounts/profile/ (instead of the proper homepage URL), which doesn't exist. I'm guessing I've done something wrong in urls.py, but I'm not sure what:
(r'^accounts/login/$', 'django.contrib.auth.views.login'),
(r'^accounts/logout/$', 'django.contrib.auth.views.logout_then_login'),
What am I missing here?
You should tell Django where it should redirect visitors when it doesn't receive a next parameter. This is done with a LOGIN_REDIRECT_URL settings, as explained in the Django documentation.
In my django App on the login page i want to have a request password button which functions like, when this button is clicked I get a request from the user per email to provide that user a password for the site.At the template login.html I made this change :
{% extends "base.html" %}
{% load url from future %}
{% block site_contents %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" name="request_password" value="Request Password" />
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
{% endblock %}
Where in views can I write code to capture the event request_password and write my code to email to the amdin about user's request?
Thanks in advance
I think this would be easier to do by creating a new form and pointing it to your own view. Or, if you want to have it in one form, you can probably create a view along the lines of:
from django.contrib.auth.views login as original_login
def my_login(request):
if request.method == 'POST' and 'request_password' in request.POST:
# process password request somehow
else:
return original_login(request)
Modifying Django-supplied view would probably just complicate things for you in the long run.
I am New beginner in python and django...
i want to know how can i create a login form by using django forms(forms.py)
In your urls.py file link to the built in Django login view, and pass in the path to a template you wish to use as the login page:
(r'^login/$', 'django.contrib.auth.views.login', {
'template_name': 'myapp/login.html'
}),
And here is an example of what the template my look like (from the Django docs):
{% extends "mybase.html" %}
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
{% endblock %}
Yes, you can. Actually, you don't need to create your own form. Simply use auth module and create your own login template. Read this: http://docs.djangoproject.com/en/dev/topics/auth/