I'm trying to add the ability to upload an image to a post but having issues.
The image field is in its own model but uses a foreign key to show which post it relates to.
At the moment the upload button does not post the form but also how would I use the post page url/slug/id as the image foreign key.
Would i need to call it in the html post page?
views.py
def designUpload(request):
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return render(request, 'users/dashboard.html')
else:
form = ImageForm()
return render(request, 'users/dashboard.html', {
'form': form
})
**models.py**
class Designs(models.Model):
forbrief = models.ForeignKey(Brief, on_delete=CASCADE)
postedby = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
design = models.ImageField(null=True, blank=True)
date = models.DateTimeField(auto_now=True, blank=True)
forms.py
class ImageForm(forms.ModelForm):
class Meta:
model = Designs
fields = ["design",]
HTML Form
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="image" name="mydesign">
<button type="submit">Upload</button>
</form>
Related
What I am trying to achieve is to have my "student_id" auto-generated field to be part of the form submission in the sense that the "student_id" field does not have to be manually input in form submission:
The "student_id" field needs to be either pre-generated upon displaying the form or to be generated upon form submission.
I have tried and currently facing error when submitting form as bellow:
KeyError at 'student_id'
Exception Value: 'student_id'
Removing the "student_id = form.cleaned_data['student_id']" syntax in views.py does not help either.
I have the following model, which generates an auto "student_id" field
class Student(models.Model):
student_id = models.AutoField(primary_key=True,unique=True, max_length=10, blank=False)
name = models.CharField(max_length=200, blank=False)
first_name = models.CharField(max_length=100, blank=True)
last_name = models.CharField(max_length=100, blank=True)
def __str__(self):
return self.name
my forms.py:
Class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = [
'student_id','name', 'first_name', 'last_name'
]
my views.py:
def index(request):
if request.method == 'POST':
form = StudentForm(request.POST, or None)
if form.is_valid():
student_id = form.cleaned_data['student_id']
form.save()
else:
FormError = StudentForm.errors
return redirect(f'/card/{student_id}')
else:
form = StudentForm()
template_name = 'index.html'
context = {
'form' : form,
}
return render(request, template_name, context)
my html:
<form method="POST" action="{% url 'student:index' %}" enctype="multipart/form-data">{% csrf_token %}
<div class="form-group">
{{ form | crispy }}
</div>
<input type="submit" value="Envoyer" class="btn btn-primary btn-lg btn-block">
</form>
Will appreciate any help
I'm having a little problem with the .save() method in Django. For 1 form it works, for the other it doesn't. And I can't find the problem.
views.py
#login_required
def stock_add(request, portfolio_id):
if request.method == 'POST':
print('request.method is ok')
form = StockForm(request.POST)
print('form is ok')
if form.is_valid():
print('form is valid')
stock = form.save(commit=False)
stock.created_by = request.user
stock.portfolio_id = portfolio_id
stock.save()
return redirect('portfolio-overview')
else:
print("nope")
else:
print('else form statement')
form = StockForm()
context = {
'form':form
}
return render(request, 'portfolios/stock-add.html', context)
forms.py
class StockForm(ModelForm):
class Meta:
model = Stock
fields = ['quote', 'amount']
html
{% extends 'core/base.html' %}
{% block content %}
<div class="container">
<h1 class="title">Add Stock</h1>
<form method="POST" action=".">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="button is-primary">Submit</button>
</form>
</div>
{% endblock %}
models
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Portfolio(models.Model):
title = models.CharField(max_length=56)
description = models.TextField(blank=True, null=True, max_length=112)
created_by = models.ForeignKey(User, related_name='portfolios', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'Portfolio'
def __str__(self):
return self.title
class Stock(models.Model):
Portfolio = models.ForeignKey(Portfolio, related_name='stocks', on_delete=models.CASCADE)
quote = models.CharField(max_length=10)
amount = models.IntegerField()
created_by = models.ForeignKey(User, related_name='stocks', on_delete=models.CASCADE)
created_at = models.DateField(auto_now_add=True)
def __str__(self):
return self.quote
If you look at the views.py file, when I submit the form, it won't even do print('request.method is ok')
I can add the stock via the admin page.
So I have no clew where to look anymore...
Cheers
When you post a form and need a special url (like your' with an attribute), i like to set action="{% url myview.views.stock_add portfolio_id %}"
action="." will save to the same page without taking care of extra parameters (if needed)
Just pass portfolio_id in the context and that will work
I found the answer, an InteregerField (from models.py) needs a default value.
Either default=None (or another value).
Cheers
There has a file upload page for upload file to a object by id in model. However, it shown MultiValueDictKeyError after submitted. I would appreciate if any help.
models.py:
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
items = models.ManyToManyField(OrderItem)
img_upload = models.FileField(upload_to='payment', null=True)
forms.py:
class Upload_File(forms.Form):
class Meta:
model = Order
fields = ('img_upload')
views.py:
def upload_page(request, id):
order = get_object_or_404(Order, id=id)
form = Upload_File(request.POST or None, request.FILES or None)
if request.method == 'POST':
order.img_upload = request.FILES['file']
if form.is_valid():
form.save()
messages.success(request, 'Succeed')
return redirect('user_info')
else:
form = Upload_File()
context = {
'form': form,
}
return render(request, 'upload.html', context)
html:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input class="form-group" type="file" name="file">
<button class="form-group" type="submit">Submit</button>
</form>
I am working on a Django project with crispy forms.
I want to use images instead of the the default Models title/label to select a instance in a Many to Many relation form.
Content models.py:
class Cloth(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL)
title = models.CharField(max_length=200)
picture = ImageCropField(upload_to='cloth_pics/%Y-%m-%d/',
blank=True)
def __str__(self):
return self.title
class Outfit(models.Model):
owner = models.ForeignKey('profiles.Profile')
title = models.CharField(max_length=200)
cloths=models.ManyToManyField(Cloth)
Content forms.py
class ClothForm(forms.ModelForm):
class Meta:
model = Cloth
fields = ('title','type','picture')
class OutfitForm(forms.ModelForm):
class Meta:
model = Outfit
exclude= ["owner"]
Content views.py
def outfits_new(request):
if request.method == "POST":
form = OutfitForm(request.POST)
if form.is_valid():
outfit = form.save(commit=False)
outfit.owner = get_user(request)
outfit.created_date = timezone.now()
outfit.save()
pk=outfit.id
return HttpResponseRedirect(reverse('outfit_edit_delete', args=[pk]))
else:
cloths = Cloth.objects.filter(owner=request.user.id)
form = OutfitForm()
return render(request, '../templates/outfits_new.html', {'form': form, "cloths":cloths})
Content outfits_new.html
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
{{ form|crispy }}
<div class="btn-group" role="group" aria-label="Basic example">
<input type="submit" value="Submit" name="edit" class="btn btn-success">
</div>
This code produces a Outfit form where I can select different cloths( displaying the cloths title). I want to select different cloths using a image from the cloths.picture field.
Thank you very much,
Patrick
Have a look at select2 at https://select2.github.io/examples.html. It allows you to do images in comboboxes
There is a Django package at https://github.com/applegrew/django-select2
I have a modelform set up for a user to enter his contact info. The validation and form.is_valid() method is working, however the request.POST data is not being stored to the db, and I'm having trouble figuring out what the problem is. Here is what I currently have --
# model
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
contact_email = models.EmailField(max_length=100, blank=True)
contact_phone = models.IntegerField(max_length=11, blank=True)
website = models.CharField(max_length=256, blank=True)
class ContactInfoForm(ModelForm):
class Meta:
model = UserProfile
fields = ('contact_email', 'contact_phone', 'website',)
# view
#login_required
def edit_contact(request):
contact_email = request.user.get_profile().contact_email
form = ContactInfoForm(initial={'contact_email':contact_email,})
if request.method == 'POST':
form = ContactInfoForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return render_to_response(...)
# template
<form action="." method="post"> {% csrf_token %}
<table>
{{form}}
</table>
<p><input type="submit" name="save_changes" value="Save Changes" ></p>
</form>
I think the error might be the instance you're calling in your ModelForm. You need to use a UserProfile instance, but you're using a User instance. The following might work (untested):
#login_required
def edit_contact(request):
contact_email = request.user.get_profile().contact_email
form = ContactInfoForm(initial={'contact_email':contact_email,})
user_profile = UserProfile.objects.get(contact_email=contact_email)
if request.method == 'POST':
form = ContactInfoForm(request.POST, instance=user_profile)
if form.is_valid():
form.save()
return render_to_response(...)