Can't upload multiple images with formset - javascript

I have django app and problem with multiple images upload.
Everything was OK till add to Familymember model field image.
Now I can not create any item for FamilyMember.
Please for help.
Here is my model:
class Profile(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
created_date = models.DateTimeField(default=timezone.now)
def get_absolute_url(self):
return reverse('profile-update', kwargs={'pk': self.pk})
def __unicode__(self):
return "%s %s" % (self.first_name, self.last_name)
class FamilyMember(models.Model):
profile = models.ForeignKey(Profile)
name = models.CharField(max_length=100)
file = models.FileField(upload_to="localefile/")
relationship = models.CharField(max_length=100)
Here are forms:
class ProfileForm(ModelForm):
class Meta:
model = Profile
exclude = ()
class FamilyMemberForm(ModelForm):
file = forms.FileField(widget=forms.FileInput(attrs={'multiple': True}))
class Meta:
model = FamilyMember
exclude = ()
FamilyMemberFormSet = inlineformset_factory(Profile, FamilyMember,
form=FamilyMemberForm, extra=1)
Here are my views, to create.
class ProfileCreate(CreateView):
model = Profile
fields = ['first_name', 'last_name']
class ProfileFamilyMemberCreate(CreateView):
model = Profile
fields = ['first_name', 'last_name']
success_url = reverse_lazy('profile-list')
def get_context_data(self, **kwargs):
data = super(ProfileFamilyMemberCreate, self).get_context_data(**kwargs)
if self.request.POST:
data['familymembers'] = FamilyMemberFormSet(self.request.POST)
else:
data['familymembers'] = FamilyMemberFormSet()
return data
def form_valid(self, form):
context = self.get_context_data()
familymembers = context['familymembers']
with transaction.atomic():
self.object = form.save()
if familymembers.is_valid():
familymembers.instance = self.object
familymembers.save()
return super(ProfileFamilyMemberCreate, self).form_valid(form)
I also use a JavaScript code, from here:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'formset/jquery.formset.js' %}"></script>
<script type="text/javascript">
$('.formset_row').formset({
addText: 'add family member',
deleteText: 'remove',
prefix: 'familymember_set'
});
</script>

When you upload a file it's passed through request.FILES, so you must also pass it to you FormSet, e.g:
def get_context_data(self, **kwargs):
data = super(ProfileFamilyMemberCreate, self).get_context_data(**kwargs)
if self.request.POST:
data['familymembers'] = FamilyMemberFormSet(
data=self.request.POST,
files=self.request.FILES
)
else:
data['familymembers'] = FamilyMemberFormSet()
return data
Don't forget to add the enctype in your form:
<form enctype="multipart/form-data" ...>

Related

How to show Django form in template?

I want to display countries and states in Django form, for that I am trying to get data from json, create form, pass json data to form and get state of the country on ajax request. I managed to write the process as far as I learned, but at last form is not rendered on Django template. How can I render Django form with following code structure?
My Model:
from django.db import models
class Address(models.Model):
country = models.CharField(null=True, blank=True, max_length=100)
state = models.CharField(null=True, blank=True, max_length=100)
def __str__(self):
return '{} {}'.format(self.country, self.state)
My Forms.py:
import json
def readJson(filename):
with open(filename, mode="r", encoding="utf-8") as fp:
return json.load(fp)
def get_country():
""" GET COUNTRY SELECTION """
filepath = './static/data/countries_states_cities.json'
all_data = readJson(filepath)
all_countries = [('-----', '---Select a Country---')]
for x in all_data:
y = (x['name'], x['name'])
all_countries.append(y)
return all_countries
def return_state_by_country(country):
""" GET STATE SELECTION BY COUNTRY INPUT """
filepath = './static/data/countries_states_cities.json'
all_data = readJson(filepath)
all_states = []
for x in all_data:
if x['name'] == country:
if 'states' in x:
for state in x['states']:
y = (state['name'], state['name'])
all_states.append(state['name'])
else:
all_states.append(country)
return all_states
class AddressForm(forms.ModelForm):
country = forms.ChoiceField(
choices = get_country(),
required = False,
label='Country / Region*',
widget=forms.Select(attrs={'class': 'form-control', 'id': 'id_country'}),
)
class Meta:
model = Address
fields = ['country']
My Form.html
<form class="" action="" method="post">
{% csrf_token %}
{% for error in errors %}
<div class="alert alert-danger mb-4" role="alert">
<strong>{{ error }}</strong>
</div>
{% endfor %}
<div class="row">
<div class="col-lg-6">
<div class="mb-4">
{{ form.country}}
</div>
</div>
<div class="col-lg-6">
<div class="mb-4">
<div class="form-group">
<label >Select a Province/State</label>
<select id="id_province" class="form-control" name="state">
<option value="-----">Select Province/State</option>
</select>
</div>
</div>
</div>
</div>
</form>
My Views:
def readJson(filename):
with open(filename, mode="r", encoding="utf-8") as fp:
return json.load(fp)
def return_state_by_country(country):
""" GET STATE SELECTION BY COUNTRY INPUT """
filepath = './static/data/countries_states_cities.json'
all_data = readJson(filepath)
all_states = []
for x in all_data:
if x['name'] == country:
if 'states' in x:
for state in x['states']:
y = (state['name'], state['name'])
all_states.append(state['name'])
else:
all_states.append(country)
return all_states
def getProvince(request):
country = request.POST.get('country')
provinces = return_state_by_country(country)
return JsonResponse({'provinces': provinces})
def processForm(request):
context = {}
if request.method == 'GET':
form = AddressForm()
context['form'] = form
return render(request, './ecommerce/checkout.html', context)
if request.method == 'POST':
form = AddressForm(request.POST)
if form.is_valid():
selected_province = request.POST['state']
obj = form.save(commit=False)
obj.state = selected_province
obj.save()
return render(request, './ecommerce/checkout.html', context)
My Ajax:
<script>
$("#id_country").change(function () {
var countryId = $(this).val();
$.ajax({
type: "POST",
url: "{% url 'ecommerce:get-province' %}",
data: {
'csrfmiddlewaretoken': '{{ csrf_token }}',
'country': country
},
success: function (data) {
console.log(data.provinces);
let html_data = '<option value="-----">Select Province/State</option>';
data.provinces.forEach(function (data) {
html_data += `<option value="${data}">${data}</option>`
});
$("#id_province").html(html_data);
}
});
});
</script>
I am trying to print form.country on template but its not working. What could be the problem?
With ModelForms I find that this type of configuration, in which everything falls under class Meta: works.
However im dubious about that get_country() method. If you share it I can take a deeper look and maybe even test it to make sure that it's not doing anything funky.
If your list of countries is somewhat static and not too long you might wanna consider using a TextChoices enum type in your model attribute to limit the choice selection. Django forms will automatically render a dropdown widget listing the items from your enum.
You can checkout this answer if you want to look into that, which further links to the django docs.
class AddressForm(forms.ModelForm):
class Meta:
model = Address
fields = ['country']
widgets = {
"country": forms.ChoiceField(
choices = get_country(),
attrs={
"class": "form-control",
"id": "id_country"
}
),
}
labels = {
"country" : "Company Country Location"
}

How to implement js to django to run 3 functions?

I have found this question which could work for me, but I don't know javascript. I want to run 3 functions like you see in my views.py, but I'm unable to do that because I use (forms.Form) one document that is uploaded to run 3 functions. Can you help me implement this js code to my django site.
This is forms.py
class DocumentForm(forms.Form):
docfile = forms.FileField(label='Select a file')
This is views.py
def save_exls(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'])
newdoc.save()
return redirect('html_exls')
else:
form = DocumentForm()
documents = Document.objects.all()
context = {'documents': documents, 'form': form,}
return render(request, 'list.html', context)
def pandas_exls(request):
if request.method == "POST":
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
output = io.BytesIO()
newdoc = request.FILES['docfile']
dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0])
writer = pd.ExcelWriter(output)
for name, df in dfs.items():
#pandas stuff
done.to_excel(writer, sheet_name=name)
output.seek(0)
response = HttpResponse(
output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
else:
form = DocumentForm()
return render(request, 'list.html', {'form': form})
def html_exls(request):
if request.method == "POST":
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
output = io.BytesIO()
newdoc = request.FILES['docfile']
dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0])
writer = pd.ExcelWriter(output)
for name, df in dfs.items():
#pandas stuff for html
done.to_excel(writer, sheet_name=name)
html = done.to_html()
print(html)
output.seek(0)
response = HttpResponse(
output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
else:
form = DocumentForm()
return render(request, 'list.html', {'form': form})
This is html file, list.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Django site</title>
</head>
<body>
<!-- Upload form. Note enctype attribute! -->
<form action="{% url "pandas_exls" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload"/></p>
</form>
<br/>
{{html|safe}}
</body>
</html>
Thanks in advance!
EDIT
See comments to make sense of this edit. This is what I tried before, to put everything in one function but it did not work.
def upload_file(request):
if request.method == "POST":
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
output = io.BytesIO()
newdoc = request.FILES['docfile']
#newdoc.save() * if I include this, I got an error, see below
dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0])
writer = pd.ExcelWriter(output)
for name, df in dfs.items():
df.columns = df.columns.str.split('_', expand=True)
new_data = df.stack(0)
#rest of pandas computation everyting until done
done.to_excel(writer, sheet_name=name)
html = done.to_html()
writer.save()
output.seek(0)
# return render(request, 'list.html', {'table': html}) **can't render html and it will not be showed
filename = f"calculated_{newdoc.name}"
response = HttpResponse(
output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
else:
form = DocumentForm()
return render(request, 'list.html', {'form': form})
'*' I got this error, AttributeError at /uploadfile/ 'InMemoryUploadedFile' object has no attribute 'save'
'**' Can't have two returns
forms.py
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(label='Select a file')
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadFileForm
from calculation import handle_uploaded_file
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
html_to_show = handle_uploaded_file(request.FILES['file'])
return HttpResponse(html_to_show)
else:
form = DocumentForm()
return render(request, 'upload.html', {'form': form})
calculation.py
def do_calculation(fname):
df = pd.read_excel(fname)
#Perform df operations here
return df.to_html()
def handle_uploaded_file(f):
fname = 'some/file/name.xlsx'
with open(fname, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
return do_calculation(fname)
EDIT (how to serve uploaded files)
We will render a another view which is expecting 2 variables from response file_url & html_table_to_show
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadFileForm
from calculation import handle_uploaded_file
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
html_to_show, file_url = handle_uploaded_file(request.FILES['file'])
return render(request, '/viewToRender.html', {
'uploaded_file_url': file_url, 'table_view': html_to_show
})
else:
form = DocumentForm()
return render(request, 'upload.html', {'form': form})
calculation.py
def do_calculation(fname):
df = pd.read_excel(fname)
#Perform df operations here
df.to_excel(fname)
return df.to_html()
def handle_uploaded_file(f):
fname = 'some/file/name.xlsx'
with open(fname, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
return do_calculation(fname), fname

Get current logged in user in JSON Format from views.py

I'm trying to build a follow and unfollow button, I want to show the button only For any other user who is signed in, a user should not be able to follow themselves.
How can I return from my views.py the currently logged-in user as a JSON format to my JS file?
I'm building the button in the JavaScript file and not in the template, I tried to return as JSON format but didn't succeed
views.py
def display_profile(request, profile):
try:
profile_to_display = User.objects.get(username=profile)
profile_to_display_id = User.objects.get(pk=profile_to_display.id)
except User.DoesNotExist:
return JsonResponse({"error": "Profile not found."}, status=404)
# Return profile contents
if request.method == "GET":
return JsonResponse(profile_to_display.profile.serialize(), safe=False)
else:
return JsonResponse({
"error": "GET or PUT request required."
}, status=400)
models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class NewPost(models.Model):
poster = models.ForeignKey("User", on_delete=models.PROTECT, related_name="posts_posted")
description = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
likes = models.IntegerField(default=0)
def serialize(self):
return {
"id": self.id,
"poster": self.poster.username,
"description": self.description,
"date_added": self.date_added.strftime("%b %d %Y, %I:%M %p"),
"likes": self.likes
}
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
following = models.ManyToManyField(User, blank=True, related_name="following")
followers = models.ManyToManyField(User, blank=True, related_name="followers")
def serialize(self):
return {
"profileID": self.user.id,
"following": int(self.following.all().count()),
"followers": int(self.followers.all().count()),
}
index.js
function load_user_info(user_clicked_on){
document.querySelector('#page-view').style.display = 'none';
document.querySelector('#posts-view').style.display = 'none';
document.querySelector('#show-posts').style.display = 'none';
document.querySelector('#load-profile').style.display = 'block';
fetch(`/profile/${user_clicked_on}`)
.then(response => response.json())
.then(profile => {
const profile_element = document.createElement('div');
const followers = document.createElement('div');
const following = document.createElement('div');
const follow_button = document.createElement('button');
followers.innerHTML = 'Followers: ' + profile.followers;
following.innerHTML = 'Following: ' + profile.following;
if (profile.profileID == ?? ){
follow_button.innerHTML = 'Sameuser';
}else{
follow_button.innerHTML = 'Not same user';
}
profile_element.appendChild(followers);
profile_element.appendChild(following);
profile_element.appendChild(follow_button);
profile_element.classList.add('profile_element');
document.querySelector('#user-profile').appendChild(profile_element);
});
document.querySelector('#user-profile').innerHTML = `<h3>${user_clicked_on.charAt(0).toUpperCase() + user_clicked_on.slice(1)} Profile</h3>`;
}
I think all you need is the detail of the logged in user right?
may be you can get it from the request object by using
{{request.user}}
this returns the logged user instance
{{request.user.username}} {{request.user.email}}
this returns username and email
I dont know if you can directly use it in javascript , but you can kind of save this in template using a hidden field lik
<input type="hidden" value="{{request.user.username}}" id='user_detail'>
and grab it using id selector (getElementById, or jquery)
$('#user_detail').val()

Passing Django model properties to JavaScript with the Fetch API

I'm working on an assignment to use the fetch API to do some of the normal things we would have Python do in our views with JavaScript such as adding records or querying the database. One issue I'm running across is passing the normal properties we would see in Django, say a user or username, where it just shows up as a literal user id when I pull it from the sql database with the fetch API. With the views, html and JavaScript I have written now, how would I go about pulling the username with fetch in JavaScript that I can normally grab with a variable or view with a print statement in the Django console, instead of just viewing the user id from the database. I feel like I'm missing a step and I'm just not seeing it.
urls
app_name = "network"
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
# API Routes
path("addpost", views.post, name="post"),
path("<str:navbar_item>", views.viewposts, name="viewposts"),
]
models.py
class User(AbstractUser):
pass
class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
bio = models.TextField(null=True, blank=True)
# pics
website = models.CharField(max_length=225, null=True, blank=True)
follower = models.ManyToManyField(
User, blank=True, related_name="followed_user") # user following this profile
# profile user that follows this profile
following = models.ManyToManyField(
User, blank=True, related_name="following_user")
def __str__(self):
return f"{self.user}'s' profile id is {self.id}"
def following_users(self):
for username in self.following:
return username
def get_absolute_url(self):
return reverse("network:profile-detail", args=[str(self.id)])
class Post(models.Model):
created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="post_user")
body = models.TextField(max_length=1000)
timestamp = models.DateTimeField(auto_now_add=True)
likes = models.ManyToManyField(User, blank=True, related_name="post_likes")
def __str__(self):
return f"{self.created_by} posted {self.body}"
def get_absolute_url(self):
return reverse("network:post-detail", args=[str(self.id)])
def total_likes(self):
return self.likes.count()
class Meta:
ordering = ["-timestamp"]
views.py
def index(request):
if request.user.is_authenticated:
return render(request, "network/index.html", {})
else:
return HttpResponseRedirect(reverse("network:login"))
#login_required
def post(request):
# Composing a new post must be done via POST
if request.method != "POST":
return JsonResponse({"error": "You must POST your request."}, status=404)
try:
data = json.loads(request.body)
body = data.get("body", "")
user = request.user
print(user)
post = Post(created_by=user, body=body)
# post = Post(created_by=Profile.objects.get(user=user), body=body)
post.save()
except AttributeError:
return JsonResponse({"error": "AttributeError thrown."}, status=500)
return JsonResponse({"message": "Post created."}, status=201)
#login_required
def viewposts(request, navbar_item):
if navbar_item == "viewposts":
posts = Post.objects.all()
posts = posts.order_by("-timestamp")
json_post = serialize("json", posts)
print(posts)
return HttpResponse(json_post, content_type="application/json")
else:
return JsonResponse({"error": "Invalid page."}, status=400)
index.html
{% extends "network/layout.html" %}
{% load static %}
{% block body %}
<div class="container p-5">
{% if error %}
{{ error }}
{% endif %}
<h1 class="display-4">All Posts</h1>
<div class="form-group border rounded p-4">
<h2 class="diplay-3">New Post</h2>
<form id="addpost" class="form-group pt-5">
{% csrf_token %}
<div class="form-group">
<textarea class="form-control" id="body" placeholder="Add post here..."></textarea>
</div>
<input type="submit" class="btn btn-primary"/>
</form>
</div>
<div id="all-posts" class="all-posts">
</div>
</div>
{% endblock %}
{% block script %}
<script src="{% static 'network/main.js' %}"></script>
{% endblock %}
JavaScript
// Post on index page # API Routes /addpost
const addPost = () => {
const addPostUrl = '/addpost';
const csrftoken = getCookie('csrftoken');
const body = document.querySelector('#body').value;
// body needs to be passed into an object before using the stringify method
const bodyObject = { body };
fetch(addPostUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken,
},
body: JSON.stringify(bodyObject)
})
.then(response => response.json())
.then(result => {
console.log(result);
})
.catch(error => {
console.log(error);
});
return false;
};
// Load posts in index page # API Routes /navbar_item
function loadPosts(navItem, event) {
preventPageLoad(event);
const postUrl = `/${navItem}`;
// Send a GET request to the URL to retrieve all posts
fetch(postUrl)
.then(response => response.json())
.then(data => {
data.forEach(post => {
const { fields } = post;
const allPostsContainer = document.querySelector("#all-posts");
const element = document.createElement('div');
const postId = `#post-${fields.id}`;
element.style.textDecoration = 'none';
element.classList.add('HoverClass1');
element.setAttribute('id', `post-${fields.id}`);
element.classList.add('d-flex', 'flex-column' ,'justify-content-between', 'p-4', 'm-3', 'lead', 'border', 'rounded');
element.style.color = '#000000';
element.innerHTML =
// This is returning an id
`<div class="bd-highlight font-weight-bolder mr-5">${fields.created_by}</div>
<div class="bd-highlight">${fields.timestamp}</div>
<div class="flex-fill bd-highlight">${fields.body}</div>`;
console.log(fields);
allPostsContainer.append(element);
const linePost = document.querySelector(postId);
linePost.addEventListener('click', (event) => {
console.log(event);
});
});
})
.catch(error => {
console.log(error);
});
return false;
}
Images showing my admin console in Django versus the browser console and what fetch is pulling in JavaScript. You'll see in the admin console we can view the username, but in the browser console all I'm getting is the user id with fetch.
I figured out how to do this. I added a serialize method to the Post model to convert these properties to JSON.
def serialize(self):
return {
'id': self.id,
'created_by': self.created_by.username,
'body': self.body,
'timestamp': self.timestamp.strftime('%b %-d %Y, %-I:%M %p'),
'likes': self.total_likes()
}
Then in views.py, in my viewposts function, instead of my the HttpResponse, I used JsonResponse and passed the model's serialize method as an argument.
#login_required
def viewposts(request, navbar_item):
if navbar_item == "viewposts":
posts = Post.objects.all()
posts = posts.order_by("-timestamp")
return JsonResponse([post.serialize() for post in posts], safe=False)
else:
return JsonResponse({"error": "Invalid page."}, status=400)
This allowed me to not have to deconstruct anything in my JavaScript file. So I could pull any attributes from my query using dot notation directly off of the data model in fetch.

When I make my form ajax it does not save image to model

My model works good when page makes POST request but when it makes it makes ajax request it stops saving an image( I can not change image to another), rest fields works good. What can be the problem?
Here is my model:
class Contact(models.Model):
name = models.CharField(max_length=40, blank=False)
last_name = models.CharField(max_length=40, blank=False)
date_of_birth = models.DateField(blank=True, null=True)
bio = models.TextField(blank=True)
contacts = models.TextField(blank=True)
email = models.EmailField(blank=True)
jabber = models.CharField(max_length=40)
skype = models.CharField(max_length=40)
other_contacts = models.TextField(blank=True)
photo = models.ImageField(upload_to='photo/', null=True)
Ajax function:
$(function(){
var form = $('#contact_form');
form.submit(function(e){
$('#sendbutton').attr('disabled', true)
$('#ajax-progress-indicator').show();
$('#ajaxwrapper').load('/1/edit/' + '#ajaxwrapper',
form.serializeArray(), function(responseText, responseStatus) {
$('sendbutton').attr('disabled', false)
$('#ajax-progress-indicator').hide();
});
e.preventDefault();
});
});
Urls:
urlpatterns = patterns(
'',
# Examples:
url(r'^$', 'apps.hello.views.home', name='home'),
)
from .settings import MEDIA_ROOT, DEBUG
if DEBUG:
# serve files from media folder
urlpatterns += patterns('',
url(r'^uploads/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': MEDIA_ROOT}))
Form:
class ContactForm(forms.ModelForm):
"""
The model for Contact model edit
"""
# other_contacts = forms.CharField(widget=PreformattedTextWidget)
class Meta:
model = Contact
fields = ['name', 'last_name', 'date_of_birth', 'bio', 'contacts',
'email', 'jabber', 'skype', 'other_contacts', 'photo']
widgets = {
'skype': forms.Textarea(attrs={'placeholder': 'Enter your skype ID'}),
# 'other_contacts': PreformattedTextWidget()
}
View class:
class ContactUpdateView(UpdateView):
model = Contact
form_class = ContactForm
template_name = 'edit.html'
def get_success_url(self):
return reverse('home')
def post(self, request, *args, **kwargs):
if request.POST.get('cancel_button'):
return HttpResponseRedirect(
u'%s?status_message=Canceled!'
%reverse('home'))
else:
return super(ContactUpdateView, self).post(request, *args,
**kwargs)
def get_ajax(self, request, *args, **kwargs):
return render(request, 'home.html')

Categories

Resources