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

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 ??

Related

Django save form with foreign key

I am currently trying to create a form where users get to fill in their details after creating an account. The idea is that every user, after registration, gets redirected to this form page to fill it out. To achieve this, i'm using foreign keys.However it doesn't save to database.
models.py
class User(AbstractUser):
pass
def __str__(self):
return self.username
class Detail(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, default="")
first_name = models.CharField(max_length=200, default="")
last_name = models.CharField(max_length=255, default="")
class Meta:
verbose_name_plural = "Detail"
def __str__(self):
return self.first_name+ " "+self.last_name
forms.py
class Details(forms.ModelForm):
class Meta:
model = Detail
fields = "__all__"
widgets={
"user": forms.TextInput()
}
views.py
def details(request):
if request.method =="POST":
form = Details(request.POST)
if form.is_valid():
detail = form.save(commit=False)
detail.user = request.user
detail.first_name = detail.first_name.lower()
detail.last_name = detail.last_name.lower()
detail.save()
return redirect("admin:index")
else:
form = Details(initial={"user":request.user.username})
return render(request, "details.html", {"form":form})
You need to exclue user field from ModelForm like this
form.py
class Details(forms.ModelForm):
class Meta:
model = Detail
fields = "__all__"
exclude =["user"]
views.py
def details(request):
if request.method =="POST":
form = Details(request.POST)
if form.is_valid():
detail = form.save(commit=False)
detail.user = request.user
detail.first_name = detail.first_name.lower()
detail.last_name = detail.last_name.lower()
detail.save()
return redirect("admin:index")
else:
form = Details()
return render(request, "details.html", {"form":form})

Adding edit photo page to django image gallery app using 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']

Refer to current model when submitting forms django

views.py
form = StudentTaskForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.instance.user = User.objects.get(id=request.user.id)
obj = form.save(commit=False)
obj.student = request.user
obj.todo = qs
obj.level = instance
obj.save()
ImageFormSet = modelformset_factory(Images,
form=ImageForm,min_num=0,
max_num=3, validate_min=True,extra=3)
if request.method == 'POST':
formset = ImageFormSet(request.POST, request.FILES,
queryset=Images.objects.none())
if formset.is_valid():
for form in formset.cleaned_data:
try:
image = form['image']
Images.objects.create(post=todo[0],image=image)
except KeyError:
pass
return redirect('student:dashboard')
else:
formset = ImageFormSet(queryset=Images.objects.none())
forms.py:
class StudentTaskForm(forms.ModelForm):
title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-
control',' type': "text",'placeholder':'Enter Title'}))
content = forms.CharField(widget=SummernoteWidget())
class Meta:
model = Task
fields = [
'title',
'content',
]
widgets = {
'content': SummernoteWidget(),
}
def clean_object(self):
instance = self.instance
class ImageForm(forms.ModelForm):
image = forms.ImageField(label='Image')
class Meta:
model = Images
fields = ('image', )
Im using formsets for saving images.A task may contain a maximum of three images.
In models.py i have :
class Task(models.Model):
level = models.ForeignKey(Level, on_delete=models.CASCADE)
todo = models.ForeignKey(ToDo,
on_delete=models.CASCADE,related_name='todo')
student = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=150)
content = models.TextField()
timestamp = models.TimeField(auto_now=True)
datestamp = models.DateField( auto_now=True)
like =
models.ManyToManyField(User,related_name='user_likes',blank=True)
is_verified=models.BooleanField(default=False,blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('student:dashboard')
objects = PostManager()
#property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
#property
def get_content_type(self):
instance = self
content_type =
ContentType.objects.get_for_model(instance.__class__)
return content_type
class Images(models.Model):
post = models.ForeignKey(Task,
default=None,on_delete=models.CASCADE)
image = models.ImageField(verbose_name='Image',blank=True)
def __str__(self):
return self.post.title
Im creating another model to save the images that belong to a particular task
How do i target the post when submitting the form.?
Images.objects.create(post=todo[0],image=image)
Im confused what to put in post=? .By the definition of the model the post is a foreign key to a task object .i want this task object to be the model for currently submitting form model from the StudentTaskForm
You should be using an inline formset, which will handle this for you.
ImageFormSet = inlineformset_factory(Task, Images,
form=ImageForm, min_num=0,
max_num=3, validate_min=True, extra=3)
formset = ImageFormSet(request.POST, request.FILES, instance=obj)
if formset.is_valid():
formset.save()
Here there's no need to iterate at all.

Django how to change forms or views.py?

i create simple page where i can add article (title, text and category). When i do it on 'site administration everything is ok', but when i add it on page i can't choose category.
http://i.stack.imgur.com/4Nxzb.jpg
I choose category, for example like on this screen but my article do not have this category after i save it (article is uncategorized).
I created forms.py file and i done it like this:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'text', 'categories')
How must i change 'categories' here to make it usable?
models.py:
from django.db import models
from django.utils import timezone
class Category(models.Model):
name = models.CharField('Nazwa Kategorii', max_length=100)
slug = models.SlugField('Odnośnik', max_length=100)
icon = models.ImageField('Ikonka Kategorii', upload_to='icons',
blank=True)
class Meta:
verbose_name = "Kategoria"
verbose_name_plural = "Kategorie"
def __unicode__(self):
return self.name
class Post(models.Model):
author = models.CharField(max_length=25, blank=True, null=True)
title = models.CharField(max_length=200)
slug = models.SlugField('Odnośnik', max_length=255)
text = models.TextField()
published_date = models.DateTimeField(
default=timezone.now)
categories = models.ManyToManyField(Category, verbose_name='Kategorie')
def publish(self):
self.published_date = timezone.now()
self.save()
def __unicode__(self):
return self.title
And from views.py my view
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('blog.views.post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
When you save a form using commit=False you should call the save_m2m() method of the form:
post = form.save(commit=False)
post.author = request.user
post.save()
form.save_m2m()
Another, more elegant, solution is to pass the instance with preset field to the form's constructor. Is this case you don't need to use the commit=False argument:
form = PostForm(request.POST, instance=Post(author=request.user))
if form.is_valid():
post = form.save()
return redirect('blog.views.post_detail', pk=post.pk)

Django Forms Updating Record Issues

I am getting an error when I try to update a record in Django using a form. I get an error that a record with that number already exists. Below is my model and view. This is really driving me nuts. I though that Django would just update the record instead of trying to write a new record.
class Report(models.Model):
report_number = models.CharField(max_length=4, unique=True)
detected = models.CharField(max_length=40)
computer_name = models.CharField(max_length=40)
username = models.CharField(max_length=15)
cab_date_time = models.CharField(max_length=40)
collector = models.CharField(max_length=40)
addresses = models.TextField()
fault = models.CharField(max_length=40)
known_malware = models.TextField(default='No')
collected_files = models.TextField(default='None')
registry_keys = models.TextField()
service_number = models.CharField(max_length=15, blank=True)
notes = models.TextField(blank=True)
sample_requested = models.CharField(max_length=4, blank=True)
action = models.CharField(max_length=35, blank=True)
And View
def reports(request, report_number):
instance = get_object_or_404(Report, report_number=report_number)
form = ReportForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
return render(request, 'reports/report.html', {'form': form})
Here is the Form defination
from django.forms import ModelForm
from reports.models import Report
class ReportForm(ModelForm):
class Meta:
model = Report
exclude = ('moderator',)
def reports(request, report_number):
instance = get_object_or_404(Report, report_number=report_number)
if request.method == 'POST':
form = ReportForm(request.POST, instance=instance)
if form.is_valid():
form.save(force_update=True)
return HttpResponseRedirect('/')
else:
form = ReportForm(instance=instance)
return render(request, 'reports/report.html', {'form': form})

Categories

Resources