Django - ImageField blank=True does not work - django

I've seen similar problems on stackoverflow, but cannot seem to get mine to work. When I have a user upload photos if a input is left blank Django will throw a MultiValueDictKeyError. I have blank=True in my imageField, but it does not seem to work.
I have the following class article in my app:
def content_file_name(instance, filename):
return '/'.join(['content', instance.user.username, filename])
class Content(models.Model):
user = models.OneToOneField(User, unique=True)
image1 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image2 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image3 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image4 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image5 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image6 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image7 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image8 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
terms = models.ImageField(upload_to=content_file_name, null=True, blank=True)
This is what my views.py looks like:
def register(request):
if request.POST:
content = Content()
content.user = request.user
content.image1 = request.FILES['image1_upload']
content.image3 = request.FILES['image3_upload']
content.image4 = request.FILES['image4_upload']
content.image5 = request.FILES['image5_upload']
content.image6 = request.FILES['image6_upload']
content.image7 = request.FILES['image7_upload']
content.image8 = request.FILES['image8_upload']
content.terms = request.POST.get('terms')
content.save()
return redirect('/portal/register')
try:
gallery = Content.objects.get(user=request.user)
return render(request, 'portal/register.html', {'gallery': gallery})
except ObjectDoesNotExist:
print 'Does Not Exist!'
return render(request, 'portal/register.html')
This is the error Django throws:
Request Method: POST
Request URL: http://127.0.0.1:8000/portal/register/
Django Version: 1.8.2
Exception Type: MultiValueDictKeyError
Exception Value: "'image1_upload'"
Exception Location: /Library/Python/2.7/site-packages/django/utils/datastructures.py in __getitem__, line 322
Python Executable: /usr/bin/python
html where the images are uplaoded:
<div class="container">
<form role="form" method="post" action="." id="js-upload-form" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">{{ user.username }}</h1>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image1" src="/media/{{ gallery.image1 }}" alt="">
</a>
<input type="file" name="image1_upload" id="image1_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image2" src="/media/{{ gallery.image2 }}" alt="">
</a>
<input type="file" name="image2_upload" id="image2_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image3" src="/media/{{ gallery.image3 }}" alt="">
</a>
<input type="file" name="image3_upload" id="image3_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image4" src="/media/{{ gallery.image4 }}" alt="">
</a>
<input type="file" name="image4_upload" id="image4_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image5" src="/media/{{ gallery.image5 }}" alt="">
</a>
<input type="file" name="image5_upload" id="image5_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image6" src="/media/{{ gallery.image6 }}" alt="">
</a>
<input type="file" name="image6_upload" id="image6_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image7" src="/media/{{ gallery.image7 }}" alt="">
</a>
<input type="file" name="image7_upload" id="image7_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image8" src="/media/{{ gallery.image8 }}" alt="">
</a>
<input type="file" name="image8_upload" id="image8_upload" multiple>
</div>
</div>

If the form field is left blank then request.FILES['form_field'] wont exist.
You should instead use something more like:
content.image1 = request.FILES.get('image1_upload', None)
That way if the form field doesn't exist the model field will get set to None.
You can also just check if the file field exists in files, but it ends up being slightly more verbose:
if 'image1_upload' in request.FILES:
content.image1 = request.FILES.image1_upload

Related

Image not getting uploaded in Django

I tried to save a record using two different methods but both are not working.
Django Form
Models (create method)
1 I have created a ModelForm
class ProductForm(ModelForm):
class Meta:
model= ProductDetails
fields= ("name","category","subcategory","price","mrp","product_details","main_img","img1","img2","img3")
labels={
"name":"Product Name",
"product_details":"Description",
"category":"Category",
"subcategory":"Sub-Category",
"price":"Price",
"mrp":"MRP",
"main_img":"Main Image",
"img1":"Image 1",
"img2":"Image 2",
"img3":"Image 3",
}
widgets = {
'name':forms.TextInput(attrs={'class':'form-control validate',}),
'product_details':forms.TextInput(attrs={'class':'form-control validate',}),
'category':forms.TextInput(attrs={'class':'custom-select tm-select-accounts',}),
'subcategory':forms.TextInput(attrs={'class':'custom-select tm-select-accounts',}),
'price':forms.TextInput(attrs={'class':'form-control validate',}),
'mrp':forms.TextInput(attrs={'class':'form-control validate',}),
'main_img':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}),
'img1':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}),
'img2':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}),
'img3':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}),
}
Models File
# For Product details
class ProductDetails(models.Model):
name= models.CharField(max_length=100)
price= models.FloatField()
mrp= models.FloatField()
main_img = models.ImageField(upload_to='product_img')
img1 = models.ImageField(upload_to='product_img')
img2 = models.ImageField(upload_to='product_img')
img3 = models.ImageField(upload_to='product_img')
category = models.ForeignKey(Category, related_name='produits', on_delete=models.CASCADE)
subcategory = models.ForeignKey(SubCategory, related_name='produits', on_delete=models.CASCADE)
product_details = RichTextField(blank=True, null=True)
trending = models.BooleanField(default=False)
def __str__(self):
return self.name
Method 1
Save record using form.save()
getting Form validation error
I have tried by removing main_img,img1,img2,img3 from all place (Forms.py, template, views,py). Then there is not validation error and record is getting saved successfully.
The validation error is just because of some issue with the image uploading
print(form.errors)= <ul class="errorlist"><li>main_img<ul class="errorlist"><li>This field is required.</li></ul></li><li>img1<ul class="errorlist"><li>This field is required.</li></ul></li><li>img2<ul class="errorlist"><li>This field is required.</li></ul></li><li>img3<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
def add_product(request):
if request.method == "POST":
form = ProductForm(request.POST or None, request.FILES or None)
print(form.errors )
if form.is_valid():
category_id = request.POST.get('category')
subcategory_id = request.POST.get('subcategory')
category= Category.objects.get(id=int(category_id))
subcategory= SubCategory.objects.get(id=int(subcategory_id))
form.category = category
form.subcategory = subcategory
form.save()
return redirect("/dashboard/products")
form = ProductForm()
categories=Category.objects.all()
subcategories=SubCategory.objects.all()
return render(request, "01-add-product.html", "form":form,"categories":categories,"subcategories":subcategories})
Method 2
Tried Saving records using models.save()
The record is getting saved but image is not getting uploaded to the media folder
On saving record from Django-admin the image is getting uploaded to proper place i.e. /media.product_img/...
But From this outside HTML its showing the file name in Django-admin but the file is not available in media folder
I already added urlpattern + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in my project/urls.py.
Also tried adding the same in urls.py of this app
Note = I have mentioned upload_to=product_img in my model (this may be important to know)
def add_product(request):
if request.method == "POST":
name = request.POST['name']
product_details = request.POST['product_details']
category_id = request.POST.get('category')
subcategory_id = request.POST.get('subcategory')
category= Category.objects.get(id=int(category_id))
subcategory= SubCategory.objects.get(id=int(subcategory_id))
price = request.POST['price']
mrp = request.POST['mrp']
main_img = request.POST['main_img']
img1 = request.POST['img1']
img2 = request.POST['img2']
img3 = request.POST['img3']
product = ProductDetails.objects.create(name=name,product_details=product_details,category=category,subcategory=subcategory,price=price,mrp=mrp,main_img=main_img,img1=img1,img2=img2,img3=img3)
product.save()
Here is my template
{% extends '01-admin-base.html' %}
{% load static %}
{% block content %}
<div class="container tm-mt-big tm-mb-big">
<div class="row">
<div class="col-xl-9 col-lg-10 col-md-12 col-sm-12 mx-auto">
<div class="tm-bg-primary-dark tm-block tm-block-h-auto">
<div class="row">
<div class="col-12">
<h2 class="tm-block-title d-inline-block">Add Product</h2>
</div>
</div>
<div class="row tm-edit-product-row">
<div class="col-xl-6 col-lg-6 col-md-12">
<form action="" method="post" class="tm-edit-product-form">
{% csrf_token %}
{{form.media}}
<div class="form-group mb-3">
<label
for="name"
>Product Name
</label>
{{form.name}}
</div>
<div class="form-group mb-3">
<label
for="category"
>Category</label
>
<select
class="custom-select tm-select-accounts"
id="category" name="category"
>
<option selected>Select category</option>
{% for category in categories %}
<option value="{{category.id}}">{{category.name}}</option>
{% endfor %}
</select>
</div>
<div class="form-group mb-3">
<label
for="subcategory"
>Sub Category</label
>
<select
class="custom-select tm-select-accounts"
id="subcategory" name="subcategory"
>
<option selected>Select sub-category</option>
{% for subcategory in subcategories %}
<option value="{{subcategory.id}}">{{subcategory.name}}</option>
{% endfor %}
</select>
</div>
<div class="row">
<div class="form-group mb-3 col-xs-12 col-sm-6">
<label
for="price"
>Price
</label>
{{form.price}}
</div>
<div class="form-group mb-3 col-xs-12 col-sm-6">
<label
for="mrp"
>MRP
</label>
{{form.mrp}}
</div>
</div>
<div class="form-group mb-3">
<label
for="description"
>Description</label
>
{{form.product_details}}
</div>
</div>
<div class="col-xl-6 col-lg-6 col-md-12 mx-auto mb-4">
<div class="custom-file mt-3 mb-3">
<label>Main Image</label>
{{form.main_img}}
</div>
<br><br>
<label>Images</label>
<div class="custom-file mt-3 mb-3">
{{form.img1}}
</div>
<div class="custom-file mt-3 mb-3">
{{form.img2}}
</div>
<div class="custom-file mt-3 mb-3">
{{form.img3}}
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary btn-block text-uppercase">Add Product Now</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock content %}
Please help me to get solution for this.
You need to add enctype="multipart/form-data"> in Html form so:
<form action="/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
</form>

How to filter out Friends of user in search users function Django

I'm trying to filter out the friends of a user and also the current logged in user from a "search_users" function, I've tried using exclude() but keep getting an error I'm not sure whats wrong. I also wanted to add a "add friend" button next to the users, which I think I've done correctly on 'search_users.html.
Error
views.py
#login_required
def search_users(request):
query = request.GET.get('q')
object_list = User.objects.filter(username__icontains=query).exclude(friends=request.user.profile.friends.all())
context ={
'users': object_list
}
return render(request, "users/search_users.html", context)
search_users.html
{% extends "feed/layout.html" %} {% load static %}
{% block searchform %}
<form
class="form-inline my-2 my-lg-0 ml-5"
action="{% url 'search_users' %}"
method="get"
>
<input name="q" type="text" placeholder="Search users.." />
<button class="btn btn-success my-2 my-sm-0 ml-10" type="submit">
Search
</button>
</form>
{% endblock searchform %} {% block content %}
<div class="container">
<div class="row">
<div class="col-md-8">
{% if not users %}
<br /><br />
<h2><i>No such users found!</i></h2>
{% else %}
<div class="card card-signin my-5">
<div class="card-body">
{% for user_p in users %}
<a href="{{ user_p.profile.get_absolute_url }}"
><img
src="{{ user_p.profile.image.url }}"
class="rounded mr-2"
width="40"
height="40"
alt=""
/></a>
<a class="text-dark" href="{{ user_p.profile.get_absolute_url }}"
><b>{{ user_p }}</b></a
>
<small class="float-right">
<a
class="btn btn-primary mr-2"
href="/users/friend-request/send/{{ user_p.username }}"
>Add Friend</a>
</small>
<br/><br />
{% endfor %}
</div>
</div>
{% endif %}
</div>
<div class="col-md-4">
<div class="card card-signin my-5">
<a href="{{ request.user.profile.get_absolute_url }}"
><img
class="card-img-top"
src="{{ request.user.profile.image.url }}"
alt=""
/></a>
<div class="card-body">
<h5 class="card-title text-center">{{ request.user }}</h5>
<h6 class="text-center">
{{ request.user.profile.friends.count }}
<p class="text-muted">Friends</p>
</h6>
<p class="card-text text-center">{{ request.user.profile.bio }}</p>
</div>
</div>
</div>
</div>
{% endblock content %}
</div>
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.png', upload_to='profile_pics')
slug = AutoSlugField(populate_from='user')
bio = models.CharField(max_length=255, blank=True)
friends = models.ManyToManyField('Profile', blank=True)
I would have done like this :
object_list = User.objects\
.filter(username__icontains=query)\
.exclude(profile__friends__in=request.user.profile.friends.all())\
.exclude(id=request.user.id)
It should be
User.profile.objects.filter(username__icontains=query).exclude(friends=request.user.profile.friends.all())
You were getting an error earlier because you referred to the user object earlier and not the profile itself. User.profile gives the one to one related model profile instead.
You can read more about one to one relationships here. https://docs.djangoproject.com/en/3.1/topics/db/examples/one_to_one/

how to make the divs at the same size

how can i make all the divs at the same size
i am using django ??
<div class="row text-left">
{% for meg in objj %}
<div class="col-lg-6 col-md-12">
<!--Image-->
<div class="view overlay rounded z-depth-1-half mb-3">
<img src="{{ meg.img.url }}" class="img-fluid" alt="Sample post image" height="100%"
width="150%">
<a>
<div class="mask rgba-white-slight"></div>
</a>
{% endfor %}
models:
class News(models.Model):
title = models.CharField(max_length=250)
body = models.TextField()
img = models.ImageField(upload_to='media/')
def __str__(self):
return self.title
enter image description here
The way you are doing, it is going to generate the divs of the same size only.
But then you are forgetting the </div> inside the for loop.
Fixing that will work for you.
{% for meg in objj %}
<div class="col-lg-6 col-md-12">
<!--Image-->
<div class="view overlay rounded z-depth-1-half mb-3">
<img src="{{ meg.img.url }}" class="img-fluid" alt="Sample post image" height="100%"
width="150%">
<a>
<div class="mask rgba-white-slight"></div>
</a>
<!---- !!!!!!!! you are missing the below 2 closing divs --->
</div>
</div>
{% endfor %}

Django forms using html elements with different name from moels field

In my django project i have this model:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,)
u_fullname = models.CharField(max_length=200)
u_email = models.EmailField()
u_profile = models.CharField(max_length=1)
u_job = models.CharField(max_length=100, null=True, blank=True, default='D')
u_country = models.CharField(max_length=20, null=True, blank=True, default='Italy')
u_regdata = models.DateTimeField(auto_now=True)
stripe_id = models.CharField(max_length=100, null=True, blank=True)
activation_code = models.CharField(max_length=10)
u_picture = models.ImageField(upload_to='profile_images', blank=True)
u_active = models.BooleanField(default=False)
u_terms = models.BooleanField(default=False)
def __unicode__(self):
return self.u_profile
and a forms.py like this one:
from a_profile.models import UserProfile
class ProfileModelForm(ModelForm):
class Meta:
model = UserProfile
fields = ['u_fullname',
'u_job',
'u_country',
'u_email',
'u_terms',
]
def clean(self):
cleaned_data = super(ProfileModelForm, self).clean()
u_fullname = cleaned_data.get('u_fullname')
u_job = cleaned_data.get('u_job')
u_country = cleaned_data.get('u_country')
u_email = cleaned_data.get('u_email')
u_terms = cleaned_data.get('u_terms')
if not u_terms:
raise forms.ValidationError("Please read and accept our Terms of Service")
if not u_fullname and not u_job and not u_country and not u_terms:
raise forms.ValidationError('You have to write something!')
return cleaned_data
well, now in html i have to use different names for element related to form fields:
<form action="" method="POST">
{% csrf_token %}
{{ form.errors }}
<div class="row">
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<input type="text" name="u_fullname_C" id="u_fullname_c"
placeholder="Company Name">
<i class="la la-building"></i>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<select name="u_country_c" id="u_country_c"
value="{{ form.u_country }}">
<option selected="selected">Italy</option>
<option>Spain</option>
<option>USA</option>
<option>France</option>
</select>
<i class="la la-globe"></i>
<span><i class="fa fa-ellipsis-h"></i></span>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<select name="u_job_c" id="u_job_c" value="{{ form.u_job }}">
<option selected="selected">Technology</option>
<option>Healthcare</option>
<option>Building</option>
<option>Aerospace</option>
</select>
<i class="la la-industry"></i>
<span><i class="fa fa-ellipsis-h"></i></span>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<input type="text" name="u_email_c" id="u_email_c"
placeholder="Enter a valid email"
value="{{ form.u_email }}">
<i class="la la-envelope"></i>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<input type="password" name="u_password_c" id="u_password_c"
placeholder="Password">
<i class="la la-lock"></i>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<input type="password" name="repeat-password_c"
id="repeat-password_c"
placeholder="Repeat Password"
onfocusout="return checkPass('C')">
<i class="la la-lock"></i>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="checky-sec st2">
<div class="fgt-sec">
<input type="checkbox" name="u_terms_c" id="u_terms_c">
<label for="u_terms_c"><span></span></label>
<span></span>
</label>
<small>Yes, I understand and agree to the workwise Terms &
Conditions.</small>
</div><!--fgt-sec end-->
</div>
</div>
<div class="col-lg-12 no-pdd">
<button type="submit" name="company" value="submit"
onclick="return checkUserRegForm('C')">Get Started
</button>
</div>
</div>
</form>
at this point when i run my code and enter data into form, when i Submit i get a form error because forms don't see value into my fields:
ERROR-> {'u_fullname': [ValidationError(['This field is required.'])], 'u_email': [ValidationError(['This field is required.'])], 'all': [ValidationError(['Please read and accept our Terms of Service'])]}
How can i link my form fields name to my html element name value?
So many thanks in advance
Here's a link to docs on the subject rendering fields manually.
I looked for awhile and this is what I came up with. I apologize I left some stuff out. In your view if you are able to get 'country code' options and 'job' options you could look over them in them template.
I added value="{{ form.u_fullname }}", and value="{{ form.u_terms }}".
<form method="" action="">
{% csrf_token %}
{{ form.errors }}
<div class="row">
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<input type='text' name="u_fullname_C" id="u_fullname_c"
value="{{ form.u_fullname }}" placeholder="">
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<select name="u_country_c" id="">
{% for option in options %}
<option value="{{ option.pk }}">{{ option.name }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<select name="u_job_c" id="u_job_c" value="{{ form.u_job }}">
{% for job in jobs %}
<option value="{{ job.pk }}">{{ job.name }}</option>
{% endfor %}
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<input type='text' name='u_email_c' id='u_email_c' placeholder="" value="{{ form.u_email }}">
<i class="la la-envelope"></i>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<input type="password" name="u_password_c" id="u_password_c" placeholder="Password">
<i class=""></i>
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="sn-field">
<input type="password" name="repeat-password_c" id="repeat-password_c" placeholder="" onfocusout="return checkPass('C')">
</div>
</div>
<div class="col-lg-12 no-pdd">
<div class="checky-sec st2">
<div class="fgt-sec">
<input type="checkbox" value="{{ form.u_terms }}" name="u_terms_c" id="u_terms_c">
<label for="u_terms_c"><span></span>
<span></span>
</label>
<small>Yes, I understand and agree to the workwise Terms &
Conditions.
</small>
</div>
</div>
</div>
<div class="col-lg-12 no-pdd">
<button type='submit' name='company' value='submit' onclick="return checkUserRegForm('C')">
Get Started
</button>
</div>
</div>
</form>
If you are using a class view
class ProfileView(CreateView):
form_class = UserProfileForm
success_url = '/'
def form_valid(self, form):
user_profile = form.save(commit=False)
user_profile.updated = datetime.datetime.now()
user_profile.save()
return super().form_valid(form)
Or a function view:
def user_profile_view(request):
if request.method == 'POST':
form = ProfileModelForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
fullname = cd['u_fullname']
UserProfile.objects.create(user=request.user, u_fullname=fullname)
return redirect('')
else:
form = ProfileModelForm()
Would you be able to provide your views.py file? I'm still semi new to Django so let me know if you are still having troubles.

Integrity Error, UNIQUE constraint failed

I am trying to allow users to upload photos and to be able to change them. Whenever the user comes back and changes the photos I get an Integrity error, "UNIQUE constraint failed: portal_content.user_id". I assume it's that I am trying to save the user when there already is one. The problem with this though is that I do not know how work around around it and fix it. I've seen similar problems, but do to my skill level I am not really sure on how to fix it. Here is my code:
Model:
def content_file_name(instance, filename):
return '/'.join(['content', instance.user.username, filename])
class Content(models.Model):
user = models.OneToOneField(User, unique=True)
image1 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image2 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image3 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image4 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image5 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image6 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image7 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
image8 = models.ImageField(upload_to=content_file_name, null=True, blank=True)
terms = models.ImageField(upload_to=content_file_name, null=True, blank=True)
View:
#login_required
def register(request):
if request.POST:
content = Content()
content.user = request.user
content.image1 = request.FILES.get('image1_upload', None)
content.image2 = request.FILES.get('image2_upload', None)
content.image3 = request.FILES.get('image3_upload', None)
content.image4 = request.FILES.get('image4_upload', None)
content.image5 = request.FILES.get('image5_upload', None)
content.image6 = request.FILES.get('image6_upload', None)
content.image7 = request.FILES.get('image7_upload', None)
content.image8 = request.FILES.get('image8_upload', None)
content.terms = request.POST.get('terms')
content.save()
return redirect('/portal/register')
try:
gallery = Content.objects.get(user=request.user)
return render(request, 'portal/register.html', {'gallery': gallery})
except ObjectDoesNotExist:
print 'Does Not Exist!'
return render(request, 'portal/register.html')
Template:
{% extends 'portal/base.html' %}
{% load staticfiles %}
{% block head_block %}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<script language="javascript" type="text/javascript" src="{% static 'js/input.js' %}"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" type="text/javascript"></script>
{% endblock %}
{% block body_block %}
<div class="container">
<form role="form" method="post" action="." id="js-upload-form" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">{{ user.username }}</h1>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image1" src="/media/{{ gallery.image1 }}" alt="">
</a>
<input type="file" name="image1_upload" id="image1_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image2" src="/media/{{ gallery.image2 }}" alt="">
</a>
<input type="file" name="image2_upload" id="image2_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image3" src="/media/{{ gallery.image3 }}" alt="">
</a>
<input type="file" name="image3_upload" id="image3_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image4" src="/media/{{ gallery.image4 }}" alt="">
</a>
<input type="file" name="image4_upload" id="image4_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image5" src="/media/{{ gallery.image5 }}" alt="">
</a>
<input type="file" name="image5_upload" id="image5_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image6" src="/media/{{ gallery.image6 }}" alt="">
</a>
<input type="file" name="image6_upload" id="image6_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image7" src="/media/{{ gallery.image7 }}" alt="">
</a>
<input type="file" name="image7_upload" id="image7_upload" multiple>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" id="image8" src="/media/{{ gallery.image8 }}" alt="">
</a>
<input type="file" name="image8_upload" id="image8_upload" multiple>
</div>
</div>
<br>
<!--<div class="form-group">-->
<!--<textarea name="terms" id="terms" class="form-control input-sm" placeholder="Terms" value="{{ content.terms }}"></textarea>-->
<!--</div>-->
<div class="form-group">
<input type="text" name="terms" id="terms" class="form-control input-sm" placeholder="terms" value="{{ gallery.terms }}">
</div>
<br>
<input type="submit" value="Register" id="js-upload-submit" class="btn btn-info btn-block">
</form>
<br>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
iPad View
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">{{ user.Username }}</h1>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="/media/{{ gallery.image1 }}" alt="">
</a>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="/media/{{ gallery.image2 }}" alt="">
</a>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="/media/{{ gallery.image3 }}" alt="">
</a>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="/media/{{ gallery.image4 }}" alt="">
</a>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="/media/{{ gallery.image5 }}" alt="">
</a>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="/media/{{ gallery.image6 }}" alt="">
</a>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="/media/{{ gallery.image7 }}" alt="">
</a>
</div>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<img class="img-responsive" src="/media/{{ gallery.image8 }}" alt="">
</a>
</div>
</div>
<p>
{{ gallery.terms }}
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<script language="javascript" type="text/javascript" src="{% static 'js/preview.js' %}"></script>
{% endblock %}
<!--http://jsfiddle.net/Mqvgx/-->
Your register() view attempts to create a new Content object each time. Since every user can only be related to a single Content object, when attempting to create a second one, it will fail.
You could replace content = Content() with a content, created = Content.objects.get_or_create(user=request.user). This would take care of multiple Content objects for a user.
P.S. a much better approach would be to use Django's ModelForms.