Adding edit photo page to django image gallery app using Python - python

I have an image gallery app in Django that has an upload image page and sends that photo to a gallery page. Also, there's an edit photo page where I want to display the uploaded image and edit it, then submit the edited photo to the gallery page. How can I have the currently uploaded image show up on both the upload image and edit pages?
views.py #uploads form for add image page(named addartifact)
def addartifact(request):
if request.method == 'GET':
form = EditorForm()
return render(request=request,template_name='addartifact.html', context={'form': form})
if request.method == 'POST':
form = EditorForm(request.POST)
if form.is_valid():
imgtitle = form.cleaned_data['imgtitle']
imgdesc = form.cleaned_data['imgdesc']
image = form.cleaned_data['image']
artifact = Artifact.objects.create(imgtitle=imgtitle, imgdesc=imgdesc, image=image)
return HttpResponseRedirect(reverse('landingpage'))
views.py #uploads image to page
def image_upload_view(request):
"""Process images uploaded by users"""
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
# Get the current instance object to display in the template
img_obj = form.instance
return render(request, 'addartifact.html', {'form': form, 'img_obj': img_obj})
else:
form = ImageForm()
return render(request, 'addartifact.html', {'form': form})
forms.py
class ImageForm(forms.ModelForm):
"""Form for the image model"""
class Meta:
model = Artifact
fields = ('artifact_id', 'imgtitle', 'imgdesc', 'image')
class EditorForm(forms.Form):
imgtitle = forms.CharField(max_length=13, required=True, label=False, widget=forms.TextInput(attrs={'style': 'text-transform:lowercase;', 'placeholder': 'enter title'}))
imgdesc = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'add description'}), label=False, required=True)
image = forms.URLField(required=True, label=False, widget=forms.TextInput(attrs={'placeholder': 'add image'}))
models.py
class Artifact(models.Model):
artifact_id = models.AutoField(primary_key=True)
imgtitle = models.CharField(max_length=11)
imgdesc = models.CharField(max_length=24)
image=models.ImageField(upload_to='images/')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']

Related

Django formset factory getting error object has no attribute save

Info: I want to upload multiple files while creating new customer. I want to use formset_factory for file update. when i try to submit the form i am getting this error CustomerFileFormFormSet object has no attribute save. can anybody tell me how tell me how can i update multiple files while adding new customer in database?
models.py
class FileData(models.Model):
"""Files Model"""
customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, blank=True)
title = models.CharField(max_length=100)
file = models.FileField(upload_to='data', blank=True)
def __str__(self):
return self.title
views.py
def CustomerCreate(request):
"""Customer Create View"""
customer_form = CustomerForm()
customer_file = formset_factory(CustomerFileForm, extra=1)
if request.method == 'POST':
customer_form = CustomerForm(request.POST)
formset = customer_file(request.POST, request.FILES)
if customer_form.is_valid() and formset.is_valid():
customer = customer_form.save(commit=False)
customer.dealer = request.user
customer.save()
file = formset.save(commit=False)
file.customer = customer
file.save()
return redirect('/')
context = {
'customer_form': customer_form,
'formset': customer_file,
}
return render(request, "customer/customer-create.html", context)
This is the code which is work for me maybe it's good or not but it's working to save the formset_factory instance. i can use forloop for each formset and save...!
views.py
if customer_form.is_valid() and formset.is_valid():
customer = customer_form.save(commit=False)
customer.dealer = request.user
customer.save()
for form in formset:
# extract name from each form and save
title = form.cleaned_data.get('title')
docs = form.cleaned_data['doc']
file_data = FileData(title=title, doc=docs, customer=customer)
# save file data instance
file_data.save()

How do i upload an image into database as base64 in django?

This is my Code. Model Form And View........
class Home(models.Model):
title = models.CharField(max_length=250)
image = models.FileField()
content = models.CharField(max_length=5000000)
date_created = models.DateTimeField(auto_now_add=True)
is_deleted = models.BooleanField()
class Meta:
db_table = 'home' #model
class HomeForm(forms.ModelForm):
class Meta:
model = Home
fields = '__all__'
title = forms.CharField(label="title")
image = forms.FileField(label="image")
content = forms.CharField(label="content") #form
def HomePage(request):
home = Home.objects.order_by('-id')
form = HomeForm()
if request.method == 'POST':
# print(request.POST)
form = HomeForm(request.POST, request.FILES or None)
if form.is_valid():
image = form.cleaned_data['image']
b64_img = base64.b64encode(image.file.read())
form.save() #model
Please What am i doing wrong?
How do i upload an image into database as base64 in django ??

Form is not being saved in Django admin page

I have faced a problem in my Django project where my form is not being saved as a new listing in my model(listing) and is not even showing on Django's admin page.
my models.py :
class listing(models.Model):
title = models.CharField(max_length=64)
describtion = models.CharField(max_length=300)
bid = models.FloatField()
category = models.ForeignKey(categories, default=1, verbose_name="Category",
on_delete=models.SET_DEFAULT)
user = models.ForeignKey(User,default='', verbose_name="User", on_delete=models.SET_DEFAULT)
image = models.CharField(max_length=400)
def __str__(self):
return f"{self.title} "
create a new listing form :
class create(ModelForm):
class Meta:
model = listing
fields = [ 'title', 'describtion','bid','category','image']
views.py :
def CreateListing(request):
user = request.user
if request.method == "POST":
form = create(request.POST, instance=user)
if form.is_valid():
new_listing = form.save()
new_listing.user = request.user
new_listing.save()
return render(request, "auctions/listing.html")
else:
return render(request, "auctions/Create.html",{
"form": create
})
Ps: I have no problem with my urls.py
You need to set the user before you can save this to the database:
def CreateListing(request):
user = request.user
if request.method == "POST":
form = create(request.POST, instance=user)
if form.is_valid():
form.instance.user = user
form.save()
return redirect('%name-of-some-view')
else:
form = create(instance=user)
return render(request, "auctions/Create.html",{
'form': form
})
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.

Not getting fields prefilled with previous values while editing a form in django

I have a form(EditProfileForm) which I created to edit the profile details. My issue is that whenever I go to the EditProfileForm page in the browser the fields are not filled with previous values which I gave while making the profile for the first time, I have to fill the entire form however if I make some change in the value then the change is being made successfully.
my Profile model:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='profile_pic.jpg', upload_to='profile_pictures')
location = models.CharField(max_length=100, blank=True, null=True)
bio = models.CharField(max_length=500, blank=True, null=True)
def __str__(self):
return self.user.username
my EditProfileForm in forms.py:
class EditProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image', 'location', 'bio']
my two views regarding profile and edit profile:
#login_required
def profile_page(request):
user = request.user
posts = Post.objects.filter(author=user)
posts_count = posts.count()
profile = Profile.objects.get(user=user)
return render(request, 'blog_app/profile.html', {'user': user, 'posts_count': posts_count, 'profile': profile})
def edit_profile(request, id):
profile = Profile.objects.get(id=id)
if request.method == 'GET':
form = EditProfileForm(request.FILES, instance=profile)
else:
form = EditProfileForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
# deleting old uploaded image.
image_path = profile.image.path
if os.path.exists(image_path):
os.remove(image_path)
# the `form.save` will also update the newest image & path.
form.save()
return redirect('profile')
return render(request, 'blog_app/edit_profile.html', {'profile': profile, 'form': form})
my two urls about profile and edit profile:
path('profile', user_views.profile_page, name='profile'),
path('edit_profile/<int:id>', user_views.edit_profile, name='edit_profile')
By the way I used django signals to automatically create profile for the first time.
The way I work with ModelForm is:
form = EditProfileForm(request.POST or None, request.FILES or None, instance=profile)
I don't know what is actually the difference between these two statements:
form = EditProfileForm(request.POST or None, request.FILES or None, instance=profile)
and
form = EditProfileForm(request.FILES, instance=profile)
But, You can try with this.
You can replace the edit_profile(request, id) function with this:
def edit_profile(request, id):
profile = Profile.objects.get(id=id)
form = EditProfileForm(request.POST or None, request.FILES or None, instance=profile)
if request.method =='POST':
if form.is_valid():
# deleting old uploaded image.
image_path = profile.image.path
if os.path.exists(image_path):
os.remove(image_path)
# the `form.save` will also update the newest image & path.
form.save()
return redirect('profile')
return render(request, 'blog_app/edit_profile.html', {'profile': profile, 'form': form})

Issue with Django 1.6 Registration Form, submitting data

Having a problem with my user registration form in django, the form wont submit the data and register the information, the registration form just clears out and loads the page again, with an empty form. Any ideas as too what I am doing wrong?
Forms.py
class RegisterForm(forms.Form):
real_name=forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': 'Real Name','required':True}))
birthday=forms.DateField(label=_(u"birthdate(mm/dd/yy)"),widget=extras.SelectDateWidget(years=range(1900, now[0]+1)),required=False)
city=forms.CharField(max_length=30, widget=forms.TextInput(attrs={'placeholder': 'City','required':True}))
state=forms.CharField(max_length=2, widget=forms.TextInput(attrs={'placeholder': 'State','required':True}))
image = forms.ImageField(required=False)
class Meta:
""" To Specify the fields from User model and the extension of the user model from django, and to prevent abstraction"""
fields = ['real_name', 'birthday','city','state','image']
def clean_real_name(self):
last_name = self.cleaned_data['real_name']
return real_name
def clean_birthday_name(self):
birthday = self.cleaned_data['birthday']
return birthday
def clean_city(self):
city = self.cleaned_data['city']
return city
def clean_state(self):
state = self.cleaned_data['state']
return state
def clean_image(self):
image = self.cleaned_data['image']
return image
Views.py
def register(request):
template_var={}
form = RegisterForm()
if request.user.is_authenticated():
if request.method=="POST":
form=RegisterForm(request.POST.copy(),request.FILES)
if form.is_valid():
user=request.user
real_name=form.cleaned_data["real_name"]
birthday=form.cleaned_data["birthday"]
city = form.cleaned_data["city"]
state = form.cleaned_data["state"]
reqfile = request.FILES["image"]
resgisteruser=ProfileUser.objects.create( birthday=birthday, user_title='Fashionista', user_points=0,
city=city, state=state, image=reqfile)
resgisteruser.save()
return HttpResponseRedirect(reverse("dashboard"))
template_var["form"]=form
return render_to_response("registration/register.html",template_var,context_instance=RequestContext(request))

Categories

Resources