Why aren't changes saved when editing a Django product? - python

Created a website with products. I need to make a window for editing them on the site in order to change the manufacturer and other characteristics. This must be done in a pop-up window. I have data displayed, I change it, but nothing changes when I save it. How can this problem be solved.
My vievs:
def parts(request):
added = ''
error = ''
PartAllView = Part.objects.order_by('-id')
if request.method == 'POST' and 'parts_add' in request.POST:
form = PartForm(request.POST, request.FILES)
if form.is_valid():
form.save()
added = 'Добавлено'
else:
error = 'Данная запчасть уже добавлена'
if request.method == 'POST' and 'parts_edit' in request.POST:
PartPost = int(request.POST['parts_edit'])
PartID = Part.objects.get(id=PartPost)
if PartID:
PartID.save()
added = 'Запчасть успешно отредактирована'
else:
error = 'Ошибка редактирования'
form = PartForm()
data = {
'added': added,
'error': error,
'form': form,
'PartAllView': PartAllView,
}
return render(request, 'kross/parts.html', data)
My HTML:
{% if PartAllView %}
{% for el in PartAllView %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="modal fade" id="partEdit{{ el.id }}">
<div class="modal-dialog modal-dialog-centered text-center" role="document">
<div class="modal-content modal-content-demo">
<div class="modal-header">
<h6 class="modal-title">Добавление запчасти</h6><button aria-label="Close" class="btn-close"
data-bs-dismiss="modal"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="row row-sm">
<div class="col-lg-6">
<div class="form-group">
<input type="text" class="form-control" name="brand" value="{{ el.brand }}">
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<input type="text" class="form-control" value="{{ el.number }}">
</div>
</div>
<div class="col-lg-12">
<div class="form-group">
<input type="text" class="form-control" value="{{ el.name }}"><br>
<input type="textarea" class="form-control" rows="2" value="{{ el.description }}">
</div>
</div>
</div>
{{ el.analog }}
...

You can use updateView to edit an existing data in your website by simply:
from django.views.generic.edit import UpdateView
From MyApp models import #Model
class editview(UpdateView):
model = #Your Model You want to edit
fields = [#Add the fields you want to edit]
template_name = 'edit.html'
success_url = ('Home')
In your edit Template add:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update">
I hope it help.

Related

How to add comment without refreshing the page itself in django

I was making a blog website, I am new to django and I don't know how to add comment without refreshing the page itself. I was trying to do with the help of tutorial but they are not helping anymore
here is my html file
<div class="row">
<div class="comment-section col-8">
{% for i in data %}
<li>{{i}}</li><br>
{% endfor %}
</div>
<div class="col-4">
<h4 class="m-3">{{comments.count}} Comments...</h4>
{% for j in comments %}
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">{{j.title}}</h5>
<h6 class="card-subtitle mb-2 text-muted">{{j.visitor.name}}</h6>
<p class="card-text">{{j.description}}</p>
</div>
</div>
{% endfor %}
<hr>
<h3>Comment here</h3>
<form method="post" id="comment-form">
{% csrf_token %}
<input type="hidden" id="contentId" name = 'contentId' value="{{ result.id }}">
<div class="form-group">
<input type="hidden" id="name" name="name" class="form-control" value="{{request.session.user.name}}" readonly>
</div>
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" name="title" class="form-control">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" id="description" cols="30" rows="5" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-secondary">Submit</button>
</form>
</div>
here is my views.py file
def addComment(request):
if request.method == 'POST':
post_id = request.POST['contentId']
title = request.POST['title']
description = request.POST['description']
user = request.session['user']['id']
con = Comment(
post_id=post_id,
title=title,
description=description,
visitor_id=user,
)
con.save()
print()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

Django-Vue error "Failed to mount app: mount target selector returned null."

Thanks for looking into my problem, I am a beginner with Django and Vue your assistance with this wil be extremely helpful. I am working on a Job portal and created the job search functionality in Django as backend for the same I have an app called job into my Django project. The browser Js console gives this error Failed to mount app: mount target selector returned null. For this app I have an add job view, through which an employer adds the jobs. For this I'm using Vue for validation and showing any errors if any non-null fields are not entered by the employer account. So this is not how it was supposed to look,Unexpected results snap shot so as you can see it wasn't supposed to give me [[error]] and company_size instead The company size is missing as per the Vue AddJobApp, given below. Also if were to add # within mount-function-createapp within Vue-AddJobApp, the page entirely disappears (blank page). what am I doing wrong here?
adding # in AddJob.mount() function is making the page go blank a
Add job template
{% extends 'core/base.html' %}
{% block content %}
<div id="add-job-app">
<h1 class="title"> Add Job</h1>
<form action="." method="POST" v-on:submit="validateForm">
{% csrf_token %}
{% if form.errors %}
{% for error in form.errors %}
<div class="notification is-danger">
{{ error }}
</div>
{% endfor %}
{% endif %}
<div class="notification is-danger" v-if ="error.length" >
<p v-for="error in errors" >
[[ error ]]
</p>
</div>
<div class="field">
<label for="">Title</label>
<div class="control">
<input class="input" type="text" name="title" id="id_title" v-model= "title">
</div>
</div>
<div class="field">
<label for="">Short description</label>
<div class="control">
<textarea name="short_description" id="id_short_description" class="textarea" v-model= "short_description" ></textarea>
</div>
</div>
<div class="field">
<label for="">Long description</label>
<div class="control">
<textarea name="long_description" id="id_long_description" class="textarea" v-model= "long_description" ></textarea>
</div>
</div>
<div class="field">
<label for="">Company name</label>
<div class="control">
<input class="input" type="text" name="company_name" id="id_company_name" v-model= "company_name" >
</div>
</div>
<div class="field">
<label for="">Company address</label>
<div class="control">
<input class="input" type="text" name="company_address" id="id_company_address" v-model= "company_address">
</div>
</div>
<div class="field">
<label for="">Company zipcode</label>
<div class="control">
<input class="input" type="text" name="company_zipcode" id="id_company_zipcode" v-model= "company_zipcode">
</div>
</div>
<div class="field">
<label for="">Company place</label>
<div class="control">
<input class="input" type="text" name="company_place" id="id_company_place" v-model= "company_place">
</div>
</div>
<div class="field">
<label for="">Company Country</label>
<div class="control">
<input class="input" type="text" name="company_country" id="id_company_country" v-model= "company_country">
</div>
</div>
<div class="field">
<label for="">Company Size</label>
<div class="control">
<div class="select">
<select name="company_size" v-model = "company_size">
<option value="">Choose Size</option>
<option value="size_1_9">1-9</option>
<option value="size_10_49">10-49</option>
<option value="size_50_99">50-99</option>
<option value="size_100">100+</option>
</select>
</div>
</div>
</div>
<div class="field">
<div class="control">
<button class="button is-success">Submit</button>
</div>
</div>
</form>
</div>
{% endblock %}
{% block scripts %}
<script >
const AddJobApp = {
data() {
return {
title:'',
company_name:'',
short_description:'',
company_size:'',
errors:[]
}
},
delimiters:['[[',']]'],
methods :{
validateForm(e){
this.errors = []
if( this.title ===''){
this.errors.push('The title field is missing')
}
if( this.short_description ===''){
this.errors.push('The short description field is missing')
}
if( this.company_name ===''){
this.errors.push('The company name field is missing')
}
if( this.company_size ===''){
this.errors.push('The company size is missing')
}
if(this.errors.length){
e.preventDefault()
return false
}else{
return true
}
}
}
}
Vue.createApp(AddJobApp).mount('add-job-app');
</script>
{% endblock %}
my views.py file inside of job app
from apps.job.forms import AddJobForm, ApplicationForm
from django.shortcuts import redirect, render
from .models import Job
from django.contrib.auth.decorators import login_required
from apps.notification.utilities import create_notification
def job_detail(request,job_id):
job = Job.objects.get(pk=job_id)
return render(request, 'job/job_detail.html',{'job':job})
def search(request):
return render(request,'job/search.html')
#login_required
def apply_for_job(request,job_id):
job = Job.objects.get(pk=job_id)
if request.method=='POST':
form = ApplicationForm(request.POST)
if form.is_valid():
application = form.save(commit=False)
application.job = job
application.created_by = request.user
application.save()
create_notification(request, job.created_by ,'application',extra_id=application.id)
return redirect('dashboard')
else:
form = ApplicationForm()
return render(request,'job/apply_for_job.html',{'form':form,'job':job})
#login_required
def add_job(request):
if request.method=='POST':
form = AddJobForm(request.POST)
if form.is_valid():
job = form.save(commit=False)
job.created_by = request.user
job.save()
return redirect('dashboard')
else:
form = AddJobForm()
return render(request,'job/add_job.html',{'form':form})

CSRF middleware token missing?

I'm novice adapting a simple address book database program using Django from a course I've done on Codemy.
I have a page where I enter the names, surnames etc together with a DELETE and EDIT button next to each address. There's no problem when I click the EDIT button (the form populates automatically and takes me to website/edit1,2,3,4 etc/), but when I click the 'edit' button after editing the addressee info, I get the error as below. The btn1 is the name="btn1" of the button as indicated.
GET /edit/3?csrfmiddlewaretoken=b4IkMxxxxxxxxxxxDHrDIgRnjvEWr53rL&**btn1**=140 HTTP/1.1" 200 5751
Here is my views file
from django.shortcuts import render, redirect
from .models import List
from .forms import ListForm
from django.contrib import messages
from django.http import HttpResponseRedirect
def home(request):
all_items = List.objects.all
return render(request, 'home.html', {'all_items': all_items})
def about(request):
return render(request, 'about.html', {})
def edit(request, item_id):
if request.method =='POST':
item = List.objects.get(pk=item_id)
form = ListForm(request.POST or None, instance=item)
if form.is_valid():
form.save()
messages.success(request, ('Item Had Been Edited'))
return redirect('home')
else:
item = List.objects.get(pk=item_id)
return render(request, 'edit.html', {'item': item})
def delete(request, item_id):
item = List.objects.get(pk=item_id)
item.delete()
return redirect('home')
...And here is the edit.html file
{% extends 'base.html' %}
{% block title %}To-Do-List | Edit {% endblock %}
{% block content %}
{% if item %}
{{ item.item }}
<form class="needs-validation" novalidate>
{% csrf_token %}
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="validationCustom01">First name</label>
<input type="text" class="form-control" id="validationCustom01" value="{{ item.First_name }}" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-6 mb-3">
<label for="validationCustom02">Last name</label>
<input type="text" class="form-control" id="validationCustom02" value="{{ item.Surname }}" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="validationCustom03">Street</label>
<input type="text" class="form-control" value="{{ item.Street }}" id="validationCustom03" required>
<div class="invalid-feedback">
Please provide a valid city.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom03">Town</label>
<input type="text" class="form-control" value="{{ item.Town }}" id="validationCustom03" required>
<div class="invalid-feedback">
Please provide a valid city.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom05">Province</label>
<input type="text" class="form-control" value="{{ item.Province }}" id="validationCustom05" required>
<div class="invalid-feedback">
Please provide a valid zip.
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-3 mb-3">
<label for="validationCustom05">Postal code</label>
<input type="text" class="form-control" value="{{ item.Postal_code }}" id="validationCustom05" required>
<div class="invalid-feedback">
Please provide a valid zip.
</div>
</div>
</div>
<button class="btn btn-primary" type="submit" type="hidden" value="" name='btn1'>Edit</button>
</form>
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
{% endif %}
{% endblock %}
I cannot locate an issue with the CSRF token. it is included just like the tutorial on the edit.html page. Not even sure if the issue is with the token?
I've gone through the tutorial time and again and cannot see an issue.
I'm a noob, so any info would be great!
Normally, when you save information after editing it in a form, you should "post" your data to the server.
It appears your form method is not set which default to get. It should be set to post.
<form method="post">...</form>
This being said, your view should also be configured accordingly. Without more details, it is hard to provide deeper answer.

Form is not responding to submit

I have form, user must fill it and submit but I have no reaction from this form
First I thought there is a problem with action directive of the form, so used redirect method in the views but no help
def organization_info(request):
organization_form = OrganizationInformationForm()
context = {
'organization_form': organization_form
}
if request.method == "POST":
print("POST")
organization_form = OrganizationInformationForm(request.POST, request.FILES)
if organization_form.is_valid():
print("VALID")
new_org = OrganizationInformation.objects.create(**organization_form.cleaned_data)
print("FILLED")
return redirect(organization_list)
return render(request, 'organization_form.html', context)
<form method="POST" enctype="multipart/form-data" class="form-horizontal">
{% csrf_token %}
<div class="form-group">
<label for="name" class="col-sm-4 control-label">Organization Name:</label>
<div class="col-sm-4">
{{ organization_form.name }}
</div>
.
.
<div class="form-group">
<div class="col-sm-4 col-sm-offset-4">
<button type="submit" class="btn btn-pink">Submit</button>
</div>
</div>
</form>
I only have the "POST" printed on the log no any errors
add form handler path in action and try again
<form method="POST" enctype="multipart/form-data" class="form-horizontal" action={'your form handler path'}>
{% csrf_token %}
<div class="form-group">
<label for="name" class="col-sm-4 control-label">Organization Name:</label>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-4">
<button type="submit" class="btn btn-pink">Submit</button>
</div>
</div>
</form>
You need to add an action attribute to your form.
<form method="POST" enctype="multipart/form-data" class="form-horizontal" **action="url-of-handler"**>
</form>
More on this topic: https://www.w3schools.com/tags/att_form_action.asp

Regist form cannot be sent

Regist form cannot be sent.
I wrote in views.py
def login(request):
login_form = LoginForm(request.POST)
regist_form = RegisterForm(request.POST)
if login_form.is_valid():
user = login_form.save()
login(request, user)
context = {
'user': request.user,
'login_form': login_form,
'regist_form': regist_form,
}
return redirect('profile')
context = {
'login_form': login_form,
'regist_form': regist_form,
}
return render(request, 'registration/accounts/login.html', context)
in login.html
<body>
<ul class="top-menu">
<h3 class="login">Login</h3>
<div class="container">
<form action="{% url 'login' %}" method="post" role="form">
{% csrf_token %}
<div class="form-group">
<label class="email_form">Email</label>
<input for="id_email" name="email" type="text" value="" placeholder="Email" class="form-control"/>
</div>
<div class="form-group">
<label class="password_form">Password</label>
<input id="id_password" name="password" type="password" value="" minlength="8" maxlength="12" placeholder="Password" class="form-control"/>
</div>
<button type="submit" class="btn btn-primary btn-lg">Login</button>
<input name="next" type="hidden" value="{{ next }}"/>
</form>
</div>
</ul>
<div class="newaccount">
<h2>New Account registration</h2>
<form class="form-inline" action="{% url 'accounts:detail' %}" method="POST">
<div class="form-group">
<label for="id_username">Username</label>
{{ form.username }}
{{ form.username.errors }}
</div>
<div class="form-group">
<label for="id_email">Email</label>
{{ form.email }}
{{ form.email.errors }}
</div>
<div class="form-group">
<label for="id_password">Password</label>
{{ form.password1 }}
{{ form.password1.errors }}
</div>
<div class="form-group">
<label for="id_password">Password(conformation)</label>
{{ form.password2 }}
{{ form.password2.errors }}
<p class="help-block">{{ form.password2.help_text }}</p>
</div>
<button type="submit" class="btn btn-primary btn-lg">Regist</button>
<input name="next" type="hidden"/>
{% csrf_token %}
</form>
</div>
</body>
in forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm
from .models import User
class RegisterForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email',)
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['email'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.attrs['class'] = 'form-control'
class LoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['password'].widget.attrs['classF'] = 'form-control'
in urls.py
urlpatterns = [
url(r'^login/$', views.login,name='login'),
]
No error happens in login form ,but in registration form all input field is not shown.I think RegisterForm cannot be sent, but I really cannot understand why all input field of LoginForm is ok although I send LoginForm by using same way of RegisterForm.
How should I fix this?What should I write it?
You're render HTML with login_form and register_form in your form HTML.
But you're trying to render with form var instead of register_form, so django doesn't know what to render.
If you try to render not-exist variable in django template engine, it just show Nothing at all. So there will be NO errors!
Change your HTML code like this:
<body>
<ul class="top-menu">
<h3 class="login">Login</h3>
<div class="container">
<form action="{% url 'login' %}" method="post" role="form">
{% csrf_token %}
<div class="form-group">
<label class="email_form">Email</label>
<input for="id_email" name="email" type="text" value="" placeholder="Email" class="form-control"/>
</div>
<div class="form-group">
<label class="password_form">Password</label>
<input id="id_password" name="password" type="password" value="" minlength="8" maxlength="12"
placeholder="Password" class="form-control"/>
</div>
<button type="submit" class="btn btn-primary btn-lg">Login</button>
<input name="next" type="hidden" value="{{ next }}"/>
</form>
</div>
</ul>
<div class="newaccount">
<h2>New Account registration</h2>
<form class="form-inline" action="{% url 'accounts:detail' %}" method="POST">
<div class="form-group">
<label for="id_username">Username</label>
{{ regist_form.username }}
{{ regist_form.username.errors }}
</div>
<div class="form-group">
<label for="id_email">Email</label>
{{ regist_form.email }}
{{ regist_form.email.errors }}
</div>
<div class="form-group">
<label for="id_password">Password</label>
{{ regist_form.password1 }}
{{ regist_form.password1.errors }}
</div>
<div class="form-group">
<label for="id_password">Password(conformation)</label>
{{ regist_form.password2 }}
{{ regist_form.password2.errors }}
<p class="help-block">{{ regist_form.password2.help_text }}</p>
</div>
<button type="submit" class="btn btn-primary btn-lg">Regist</button>
<input name="next" type="hidden"/>
{% csrf_token %}
</form>
</div>
</body>
This code will show your input tags.
And one thing more... Why don't you use login_form in your HTML?

Categories

Resources