I'm trying to display pie and bar chart using Flask API on html page using chart.js. I am able to display pie chart but bar chart is getting below error.
"cannot read property of undefined (reading 'offsetWidth')" under "/nutrition_analysis" route.
Please find below Python main.py code,
# importing the necessary dependencies
from flask import Flask, render_template, request,jsonify
from flask_cors import CORS, cross_origin
import pandas as pd
from flask import send_file
#import matplotlib.pyplot as plt
#%matplotlib inline
import logging
from datetime import datetime
app = Flask(__name__) # initializing a flask app
#app.route('/', methods=['GET', 'POST']) # route to display the home page
#cross_origin()
def homePage():
return render_template("home.html")
#app.route('/form_fill',methods=['GET','POST']) # route to display the home page
#cross_origin()
def form_fill():
return render_template("form_fill.html")
#app.route('/download_file',methods=['GET','POST']) # route to display the home page
#cross_origin()
def download_file():
path = 'Daily Nutrition Requirement.xlsx'
return send_file(path, as_attachment=True)
#app.route('/nutrition_analysis',methods=['POST','GET']) # route to show the predictions in a web UI
#cross_origin()
def nutrition_analysis():
if request.method == 'POST':
try:
# reading the inputs given by the user
name = (request.form['name'])
age = float(request.form['age'])
weight = float(request.form['weight'])
reference = (request.form['reference'])
phone = float(request.form['phone'])
emailid = (request.form['emailid'])
file = request.form['customer_data']
customer_data = pd.read_excel(file)
RDA = pd.read_excel('Recommended_Nutrition.xlsx')
df = pd.concat([RDA, customer_data], ignore_index=True)
df_Carbs = df[df["Nutrients"] == "Carbohydrate"]
df_Fat = df[df["Nutrients"] == "Fats"]
df_Prot = df[df["Nutrients"] == "Proteins"]
df_Fbr = df[df["Nutrients"] == "Fiber"]
df_Macros = pd.concat([df_Carbs, df_Fat, df_Prot, df_Fbr])
df_Macros_Exp = df_Macros[df_Macros["Category"] == "Exp"]
# df_Macros_Obs = df_Macros[df_Macros["Category"] == "Obs"]
# plt.pie(df_Macros_Exp["Value"], labels=df_Macros_Exp["Nutrients"], autopct='%1.1f%%')
# plt.title("Expected Macros as per RDA", fontweight='bold')
# plt.savefig('chart.png')
values = df_Macros_Exp["Value"].tolist()
labels = df_Macros_Exp["Nutrients"].tolist()
colors = ["#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA"]
# Bar Chart
df_stack = pd.merge(RDA,customer_data[['Nutrients','Value']],on='Nutrients', how='left')
df_stack1=df_stack[['Nutrients','Value_x','Value_y']].copy()
df_stack1["RDA"]=100
df_stack1["Intake"]=((df_stack1["Value_y"] - df_stack1["Value_x"])/df_stack1["Value_x"])*100
df_stack1.drop(["Value_x", "Value_y"], axis = 1, inplace = True)
def color(x):
if x < 0 or x > 50 :
return '#F7464A'
else:
return '#46BFBD'
df_stack1["Color"]=df_stack1["Intake"].apply(color)
values_bar = df_stack1["Intake"].tolist()
labels_bar = df_stack1["Nutrients"].tolist()
colors_bar = df_stack1["Color"].tolist()
#dt=datetime.now()
# showing the prediction results in a UI
return render_template('nutrition_analysis.html',s1=name,s2=age,s3=weight,s4=reference,s5=phone,s6=emailid,set=zip(values, labels, colors),set2=zip(values_bar,labels_bar,colors_bar))
except Exception as e:
print('The Exception message is: ',e)
logging.debug(e)
return 'something is wrong'
# return render_template('results.html')
else:
return render_template('home.html')
if __name__ == "__main__":
logging.basicConfig(filename='Nutrition_Analysis.log', level=logging.DEBUG)
app.run(host='127.0.0.1', port=8001, debug=True)
#app.run(debug=True) # running the app
Please find html page which need to be rendered below,
<head>
<meta charset="utf-8" />
<title>Macro Analysis</title>
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js'></script>
</head>
<body>
<div class="item active" style="display: flex; height: 100px;">
<div style=" width: 30%;">
<h1><p>Liv365 Nutrition Analysis Report :</p></h1>
<br>name : {{s1}}</br>
<br>age : {{s2}}</br>
<br>weight : {{s3}}</br>
<br>reference : {{s4}}</br>
<br>phone : {{s5}}</br>
<br>emailid : {{s6}}</br>
</div>
<div style=" width: 30%;">
<h1>Macro Analysis</h1>
<canvas id="chart" width="400" height="200"></canvas>
<script>
var pieData = [
{% for values, labels, colors in set %}
{
value: {{values}},
label: "{{labels}}",
color : "{{colors}}"
},
{% endfor %}
];
// draw pie chart
new Chart(document.getElementById("chart").getContext("2d")).Pie(pieData);
</script>
</div>
<div style=" width: 40%;">
<h1>Micro Analysis</h1>
<canvas id="bar" width="400" height="200"></canvas>
<script>
var barData = [
{% for values_bar, labels_bar, colors_bar in set2 %}
{
value: {{values_bar}},
label: "{{labels_bar}}",
color : "{{colors_bar}}"
},
{% endfor %}
];
new Chart(document.getElementById("bar"), {
type: 'bar',
data: {
labels: barData["label"],
datasets: [
{
label: "Population (millions)",
backgroundColor: barData["color"],
data: barData["value"]
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Total Confirmed Cases of COVID in May'
}
}
});
</script>
</div>
</div>
</body>
</html>
Please help me resolve this issue.
Thanks in advance!!!
Regards,
Rohan
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"
}
i am struggling with getting my User ID after i log in. The token is and already stored in localstorage
working on Django as backend and Vue.js as frontend
so a user is able to login and out but I can't seem to find the userId of the logged in user
in able to retrieve more data linked to the user.
Therefore i cannot post an product properly related to a user. besides that, if i manage to post and check via console on chrome, it says my category section null/empty
Whenever I try to link my category foreignfield in the product model
i keep getting this error below
{category: ["Invalid hyperlink - No URL match."]}
category: ["Invalid hyperlink - No URL match."]
0: "Invalid hyperlink - No URL match.
Thanks in advance
my model.py
from django.db import models
from django.contrib.auth.models import User
# class User(models.Model):
# id_user = models.DecimalField(max_digits=10, decimal_places=2, null=True)
# def __str__(self):
# return self.id_user
class Category(models.Model):
name = models.CharField(max_length = 200, null = True,)
def __str__(self):
return self.name
class State(models.Model):
STATE_CHOICES = [('Ordered', 'Ordered'), ('Pending', 'Pending'),
('Placed', 'Placed'), ('Reserved', 'Reserved')
]
state = models.CharField(max_length = 200, null = True,
choices = STATE_CHOICES)
def __str__(self):
return self.state
class Product(models.Model):
user = models.ForeignKey(User,null=True, on_delete=models.SET_NULL)
state = models.ForeignKey(State, null=True, on_delete=models.SET_NULL)
category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL)
title = models.CharField(max_length=200)
description = models.TextField(max_length=800, null=True)
price = models.DecimalField(max_digits=10, decimal_places=2, null=True)
#image = models.ImageField(upload_to='post_image', blank=True, width_field=None, height_field=None, max_length=100,)
date_created = models.DateTimeField(auto_now_add=True, null=True)
class Meta:
unique_together = (('user','title'),)
index_together = (('user','title'),)
# CATEGORY_CHOICES = (
# ('Books', 'Books'),
# ('eBooks','eBooks'),
# ('Writing material','Writing material'),
# )
# category = models.CharField(max_length=200, null=True, choices=CATEGORY_CHOICES)
SCHOOL_CHOICES = (
('Erasmushogeschool | EHB',(
('Campus Kaai', 'Campus Kaai'),
('Campus Bloemberg', 'Campus Bloemberg'),
)),
('Vrije Universiteit Brussel | VUB',(
('Campus Jette', 'Campus Jette'),
('Campus Schaarbeek', 'Campus Schaarbeek'),
)),
('Katholieke universiteit leuven | KUL',(
('KUL Gent', 'KUL Gent'),
('Campus Antwerpen', 'Campus Antwerpen'),
)),
)
school = models.CharField(max_length=50, choices=SCHOOL_CHOICES, null=True)
MAJOR_CHOICES = (
('IT','IT'),
('Marketing','Marketing'),
('DIFF','DIFF'),
)
major = models.CharField(max_length=200,choices=MAJOR_CHOICES, null=True)
SUBJECT_CHOICES = [
('Mathematics','Mathematics'),
('Algoritmes','Algoritmes'),
('Analyses','Analyses'),
]
subject = models.CharField(max_length=200,choices=SUBJECT_CHOICES, null=True)
CONDITION_CHOICES = [
('New','New'),
('Used','Used'),
]
condition = models.CharField(max_length=200,choices=CONDITION_CHOICES, null=True)
LOCATION_CHOICES = [
('Brussel','Brussel'),
('Leuven','Leuven'),
('Gent','Gent'),
('Antwerpen','Antwerpen'),
]
location = models.CharField(max_length=200,choices=LOCATION_CHOICES, null=True)
def __str__(self):
return self.title
serializer.py
from rest_framework import serializers
from .models import Product, State, Category
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'password')
extra_kwargs = {'password':{'write_only':True,'required':True}}
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
print(user)
Token.objects.create(user=user)
return user
class ProductSerializer(serializers.HyperlinkedModelSerializer):
category_name = serializers.CharField(source='category.name', read_only=True)
class Meta:
model = Product
fields = '__all__'
class CategorySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Category
fields = ('id', 'url', 'name')
class StateSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = State
fields = '__all__'
urls.py
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
from django.urls import path
from restapi.views import ProductViewSet, StateViewSet, UserViewSet, CategoryViewSet
# class UserSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# model = User
# fields = ['id', 'url', 'username', 'email', 'is_staff']
# # ViewSets define the view behavior.
# class UserViewSet(viewsets.ModelViewSet):
# queryset = User.objects.all()
# serializer_class = UserSerializer
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register('users', UserViewSet)
router.register('product', ProductViewSet)
router.register('category', CategoryViewSet)
router.register('state', StateViewSet)
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
views.py
from django.shortcuts import render
from rest_framework import viewsets, status
from .models import Product, State, Category
from django.contrib.auth.models import User
from .serializer import ProductSerializer, UserSerializer, StateSerializer, CategorySerializer
from rest_framework.permissions import IsAuthenticated,AllowAny
from rest_framework.authentication import TokenAuthentication
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.response import Response
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
authentication_classes = (TokenAuthentication,)
permission_calsses = (IsAuthenticated,)
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
search_fields = ('title', 'price', 'category__name')
# def delete(self,request,*args,**kwargs):
# response = {'message':'product cannot be updated like this'}
# return Response(response, status = statu.HTTP_400_BAD_REQUEST)
# def create(self,request,*args,**kwargs):
# response = {'message':'product cannot be created like this'}
# return Response(response, status = status.HTTP_400_BAD_REQUEST)
class CategoryViewSet(viewsets.ModelViewSet):
queryset = Category.objects.all()
serializer_class = CategorySerializer
permission_calsses = (IsAuthenticated,)
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
search_fields = ('name', 'id')
class StateViewSet(viewsets.ModelViewSet):
queryset = State.objects.all()
serializer_class = StateSerializer
permission_calsses = (IsAuthenticated,)
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = (AllowAny, )
# class CustomObtainAuthToken(ObtainAuthToken):
# def post(self, request, args, *kwargs):
# response = super(CustomObtainAuthToken, self).post(request, args, *kwargs)
# token = Token.objects.get(key=response.data['token'])
# return Response({'token': token.key, 'id': token.user_id})
my front end Vue.js login
<template>
<div class="login-form">
<b-form #submit.prevent="login" v-if="token==null">
<div class="sign-in-htm">
<div class="group">
<label for="user" class="label">Username</label>
<input id="user" type="text" class="input" required v-model="username">
</div>
<div class="group">
<label for="pass" class="label">Password</label>
<input
id="pass"
type="password"
class="input"
data-type="password"
v-model="password"
required>
</div>
some more code...
</template>
<script>
export default {
name: "login",
data() {
return {
username: '',
user_id : 0,
password: '',
repeat: '',
submitted: false,
token: null,
log_status: ''
}
},
methods: {
login() {
axios
.post("http://127.0.0.1:8000/auth/", {
username: this.username,
password: this.password
})
.then(res => {
this.token = res.data.token;
this.log_status = "Log out";
this.$root.$emit("logAndToken", this.log_status, this.token);
console.log(
"Login data:",
res,
this.username,
this.password,
this.token
);
localStorage.setItem("logAndToken", this.token);
localStorage.setItem("user_id", this.user_id);
});
this.$router.push({ name: "homepage" }).catch(err => {
localStorage.removeItem("logAndToken");
localStorage.removeItem("user_id");
console.log("error loginn", err);
});
},
register() {
console.log(this.username);
axios
.post("http://127.0.0.1:8000/auth/", {
username: this.username,
password: this.password
})
.then(res => console.log(res))
.catch(err => console.log(err));
this.submitted = true;
this.$validate()
.then(function(success) {
if (success) {
alert('Validation succeeded!');
}
});
this.$router.push({ name: "useradmin" });
},
submit: function () {
this.submitted = true;
this.$validate()
.then(function(success) {
if (success) {
alert('Validation succeeded!');
}
});
}
</script>
my navbar at the top | in this component i check whether i have an token or not with the v-for
<template>
<li class="nav-item dash">
<a class="nav-link pr-2 h5 font-weight-bold" type="button" #click.prevent="$router.push({ name: 'useradmin' }).catch(err => {})" v-if="this.token!=null">Dasboard</a>
</li>
<li class="nav-item">
<a class="nav-link pr-2 h5" type="button" #click.prevent="$router.push({ name: 'sdf' }).catch(err => {})" v-if="this.token!=null" v-on:click="logout()" >{{this.log_status}}</a>
</li>
<li class="nav-item">
<a class="nav-link pr-2 h5" type="button" #click.prevent="$router.push({ name: 'sdf' }).catch(err => {})" v-if="this.token==null">{{this.log_status}}</a>
</li>
// more code
</template>
<script>
var url_category = 'http://127.0.0.1:8000/category/'
export default {
name: "Menu",
components: {},
props: [],
data() {
return {
categories:[],
title: '',
token: null,
log_status: this.token?'log out':'log in',
};
},
mounted() {
this.$root.$on('logAndToken', (log_status, token) => {
this.token = token
this.log_status = log_status
console.log('message received from login + token' ,log_status, token);
})
},
methods: {
sendCategoryName(category_name){
this.$root.$emit('message', category_name)
},
logout(){
localStorage.removeItem('logAndToken');
this.token = null;
this.log_status = "Log in"
this.$root.$emit('logAndToken', this.log_status, this.token)
}
},
created() {
axios.get(url_category).then(res => (this.categories = res.data))
.catch(err => console.log("error", err));
/* To check if anything is coming trough, i console log the result:
.then(res => console.log(res))
My records were in the array 'results'
*/
// get the Records form the API use Vue detected tool extention via chrome.
}
};
</script>
You can fetch user_id from request object. request.user.id
If you want to store additional information, it's a good idea to utilize JWT tokens. When you send the token from the server you can encode additional information into the response payload.
For example your payload might look like this when its encoded.
{
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
}
When you decode it from your frontend app
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
Take a look at https://jwt.io/
Right now, it seems like you don't encode any other additional information into your response.
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" ...>
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')