I'm trying to create a button on the framework django that let me delete my own article on my blog. I tried to create a code for this functionality, but it doesn't work.
views.py
if(request.GET.get('delete')): #if the button is clicked
delete_article = get_object_or_404(Article, id=id)
if request.POST:
form = DeleteNewForm(request.POST, request.FILES)
if form.is_valid():
delete_article.delete()
return HttpResponseRedirect("/")
template.html
<form enctype='multipart/form-data' action="." method="post" class="form" autocomplete="off" autocorrect="off">
{% csrf_token %}
<div class="form-group">TITRE
{{ form.title.errors }}
{{ form.title }}
</div>
<div class="form-group">CONTENU
{{ form.media }}
{{ form.contenu.errors }}
{{ form.contenu }}
</div>
<div class="form-group">
{{ form.image.errors }}
{{ form.image }}
</div>
<input type="submit" class="btn btn-default" value="Edit Article"/>
<input type="submit" class="btn btn-default" value="Delete Article" name="delete">
</form>
Here is what happen when I submit the form : I am not redirected on the index as it should redirect me and the article has not been deleted.
Is there a problem which don't let me delete my article in these lines?
I have no idea what you're doing in your views or in your template. But if I want to delete something, I just define a separate view for that.
# views.py
from django.views.generic.base import View
class DeleteView(View):
def post(self, request *args, **kwargs):
article = get_object_or_404(id=request.POST['article_id'])
# perform some validation,
# like can this user delete this article or not, etc.
# if validation is successful, delete the article
article.delete()
return HttpResponseRedirect('/')
Your template should be like this:
<form action="/url/to/delete/view/" method="POST">
{% csrf_token %}
<input type="hidden" value="{{ article.id }}">
<input type="submit" value="Delete">
</form>
Related
Im on investigation Django framework and now trying to create custom procedure of resetting password.
I use this URL path
path('password_reset_confirm/<uidb64>/<token>',
PasswordResetConfirmView.as_view(
template_name='user_account/reset_password/password_reset_confirm.html',
success_url='/account/password_reset_complete/'),
name="password_reset_confirm"),
In template i use crispy form
<form class="login-form p-4 rounded" method="post">
{% csrf_token %}
<h1 class="h4 mb-4 font-weight-bold">Change your password</h1>
<p>Use the form below to change your password.</p>
{{ form|crispy }}
<button type="submit" value="Change">
Submit
</button>
</form>
So now this form do not showing in template, and if if type {{ form }} instead of {{ form.as_p }} or crispy form, that showing me None in form place.
How do you customize the default login form in Django?
# demo_project/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('', include('pages.urls')),
path('users/', include('users.urls')), # new
path('users/', include('django.contrib.auth.urls')), # new
path('admin/', admin.site.urls),
]
<!-- templates/registration/login.html -->
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
Above code works but I need to customize that {{form.as_p}} Where is that form or can it be override? Thanks for the help.
you can overide default Authentication form
like this
from django.contrib.auth.forms import AuthenticationForm, UsernameField
from django import forms
class UserLoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super(UserLoginForm, self).__init__(*args, **kwargs)
username = UsernameField(widget=forms.TextInput(
attrs={'class': 'form-control', 'placeholder': '', 'id': 'hello'}))
password = forms.CharField(widget=forms.PasswordInput(
attrs={
'class': 'form-control',
'placeholder': '',
'id': 'hi',
}
))
in url.py you can pass this custom authentication form like this
from django.contrib.auth import views
from myapp.forms import UserLoginForm
urlpatterns = [
path(
'login/',
views.LoginView.as_view(
template_name="login.html",
authentication_form=UserLoginForm
),
name='login'
)
]
also, you can override the login template
and customize the template as per you requirement
<form method="post">
{{ form.non_field_errors }}
<div class="form-group">
<label for="{{ form.username.id_for_label }}">Username:</label>
{{ form.username }}
{{ form.username.errors }}
</div>
<div class="form-group">
<label for="{{ form.password.id_for_label }}">Password:</label>
{{ form.password }}
{{ form.password.errors }}
</div>
<button type="submit">Login</button>
</form>
You can customise your form rendering by overriding/editing templates/registration/login.html as below.
This is for example only you can change css styles and formatting as you want.
<h2>Login</h2>
<form method="post">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.username.errors }}
<label for="{{ form.username.id_for_label }}">Username:</label>
{{ form.username }}
</div>
<div class="fieldWrapper">
{{ form.password.errors }}
<label for="{{ form.password.id_for_label }}">Password:</label>
{{ form.password }}
</div>
<button type="submit">Login</button>
</form>
You may also loop over form's fields
<h2>Login</h2>
<form method="post">
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
<button type="submit">Login</button>
</form>
You could also check more form rendering options from here
From question, I assume you want to change the html template's look and feel instead of python forms class. In this case all you need to do is include input type fields with the matching names and ids attributes what default django-auth form expects. You can achieve this using following steps.
Render the template as you are rendering right now (using {{form.as_p}}).
Inspect elements and check user name, password and submit button's name and ids generated by default auth form.
Recreate same tags using your own custom style.
It comes something similar to below:
<form method="POST">
{% csrf_token %}
<input type="input" class="form-control" name="username" id="inputEmail" placeholder="Username" required >
<input type="password" class="form-control" name="password" id="inputPass" placeholder="Password" required>
<button type="submit" style="opacity: 1 !important;">Login</button>
Reset Password
</form>
After this you can use your imagination and design the login form as per your requirement.
Hope this helps.
How can I add attribute autocomplete="off" to the input login template form for an admin?
I'm find this in the login.html template but can't find where is the form template
<div class="form-row">
{{ form.username.errors }}
{{ form.username.label_tag }} {{ form.username }}
</div>
If you need to change behavior based on whether or not the user is admin/staff:
{% if request.user.is_staff %}
<form autocomplete="off" method="post" action="action_name">
<input autocomplete="off" name="hidden" type="text" style="display:none;">
{% else %}
<form method="post" action="action_name">
{% endif %}
<div class="form-row">
And complete the rest of the form as you would.
Reference for the form and input tags to turn autocomplete off (note autocomplete is "off" in the input tag as per testing in comments):
https://gist.github.com/niksumeiko/360164708c3b326bd1c8
I am developing an application with django for uploading a file on the server. I have defined a form and a model in forms.py and models.py files separately as below(respectively):
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
label=''
)
and in models.py:
from django.db import models
# Create your models here.
class Document(models.Model):
docfile = models.FileField(upload_to='targetdir')
in my HTML file and my form is:
<form class="myclass" action="submit" method="post">
{% csrf_token %}
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<br />
<input font-size="50px" style="zoom:1.5" class="myclass" dir="rtl" type="submit" value="upload" id="button" class="top-menu" onclick="pythonhandler()" />
now, whenever I submit my form and I wanna to receive my uploaded file on the server via below codes, I got "
raise MultiValueDictKeyError(repr(key))
MultiValueDictKeyError: "'docfile'""
error. my views.py file:
def pythonhandler(request):
if request.method == 'POST':
try:
data = request.FILES.get('docfile')
with open(os.getcwd()+'/mydirectory/'+request.FILES['docfile'].name, 'wb+') as destination:
for chunk in request.FILES['docfile'].chunks():
destination.write(chunk)
I did the mentioned steps in this , this and this question, but I receive this error again!
in your view function
def pythonhandler(request):
data = DocumentForm(request.POST, request.FILES)
and in your html file
<form class="myclass" action="submit" enctype="multipart/form-data" method="post">
{% csrf_token %}
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<input type="submit" value="upload" id="button" class="top-menu" onclick="pythonhandler()" />
I have missed enctype="multipart/form-data" command in my form tag in my HTML file. So, my form in the HTML file must be such as bellow:
<form class="myclass" action="submit" enctype="multipart/form-data" method="post">
{% csrf_token %}
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<input type="submit" value="upload" id="button" class="top-menu" onclick="pythonhandler()" />
I'm Using Django-ckeditor as a model form widget.I have been able to able to save data using the model-form.
Now that I want to edit any saved data the form does not load the data onto the CKeditor.
Django 1.10 Python 3.5 Windows 7 64bit
forms.py
class templateform(forms.ModelForm):
class Meta:
model = presciptiontemplates
fields = ['template', 'templateid', ]
widgets = {
'template': CKEditorWidget(),
}
labels = {
"templateid": _("Patient ID"),
}
views.py
def get_template(request, tid):
template = presciptiontemplates.objects.get(templateid=tid)
form = templateform(request.POST, instance=template)
if form.is_valid():
form = form.save(commit=False)
form.patientid = tid
form.save()
else:
form = templateform(request.POST, instance=template)
return render(request, 'presapp/viewtemplate.html',{'form': form})
HTML
<div id="preview-content">
<form method="post" style="margin-top:20px;">
{% csrf_token %}
{{ form.media }}
{{ form|safe }}
<div class="" style="margin-top:20px ;">
<button class="btn waves-effect waves-light left" type="submit">Submit
<i class="material-icons right">add_circle</i
</button>
</form>
</div>
</div>
Change {{ form|safe }} to {{ form.as_p }}
<div id="preview-content">
<form method="post" style="margin-top:20px;">
{% csrf_token %}
{{ form.media }}
{{ form.as_p }}
<div class="" style="margin-top:20px ;">
<button class="btn waves-effect waves-light left" type="submit">Submit
<i class="material-icons right">add_circle</i
</button>
</form>
</div>
</div>