I am trying to make an image field using mongoengine in DJango. The form shows up, I upload the image, all other fields are saved except the image but it keeps saying "This field is required" for the thumbnail_new field. Here is my model
class VideoMain(Document):
"""This class represents the Video Meta data model."""
video_id = fields.SequenceField()
ytlink = fields.StringField()
title = fields.StringField()
description =fields.StringField()
show = fields.StringField()
published_at = forms.DateTimeField()
views = fields.IntField()
thumbnail = fields.StringField()
**thumbnail_new = fields.ImageField(size=600,thumbnail_size=None)**
channel_name = fields.StringField()
channel_description = fields.StringField()
guests = fields.ListField(fields.StringField(max_length=30))
anchors = fields.ListField(fields.StringField(max_length=30))
tags = fields.ListField(fields.StringField(max_length=30))
And here is the Django form
from django import forms
from .models import *
class ShowDetailsForm(forms.Form):
shows = Show.objects.all()
title = forms.CharField()
description = forms.CharField()
channel = forms.CharField()
publishingdate = forms.CharField()
views = forms.IntegerField()
thumbnail = forms.CharField()
thumbnail_new = forms.ImageField()
#show = forms.ChoiceField(shows)
class Meta:
model = VideoMain
fields="__all__"
And finally the view function where the form has to be stored
def show_video_data(request):
"""
View function for renewing a specific BookInstance by librarian"""
if request.method == 'POST':
#print("I am post")
form = ShowDetailsForm(request.POST,request.FILES)
if form.is_valid():
newfile=FileUploadHandler(title='anything', file=request.FILES['thumbnail_new'])
newfile.save()
print (form.photo)
# do saving #
form.save()
return HttpResponseRedirect('/fetchvideodata')
I am new to django, so please bear If there is a silly mistake. I couldn't find a solution or tutorial that uses both mongoengine and django forms. Also I got error while specifying collection_name="thumbs",**kwargs in the model thumbnail_new = fields.ImageField(size=600,thumbnail_size=None).
Related
I want to display an image inside a detail view of a model, when browsing through Django Admin. I have seen other posts about displaying images in the list view of all instances of a model in Django Admin. But I'm interested in seeing the image on the page where you can edit the data.
models.py
class Label(models.Model):
label = models.TextField()
fragment = models.ForeignKey('Fragment', models.DO_NOTHING, null=True)
in_english = models.BooleanField(default=True)
validated = models.BooleanField(default=False)
def __str__(self):
return str(self.fragment)
admin.py
#admin.register(Label)
class LabelsAdmin(admin.ModelAdmin):
fields = ("label", "in_english", "validated", )
# What I tried. This is not working even after adding 'image' to the fields. I get an error.
# def image(self, obj):
# return format_html('<img src="{0}" />'.format(f"/static/fragments/{obj}.png"))
you create a method like display_image.
def display_image(self, obj):
# get image url
image_url = '<your_image_url>'
if image_url is not None:
return format_html('<img src="{}">', image_url)
return None
Add 'display_image' in fields list
fields = ("label", "in_english", "validated", 'display_image')
then make this field as a readonly
readonly_fields = ['display_image']
I currently have a Django form that saves data from a questionnaire against a user, where a user is stored as a Foreign Key from the Person model. I can successfully find the person from the Person class using get_object_or_404(), but when I try to save(commit=True), the data is not being saved in the database. See below for my code:
# models.py
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=100)
email = models.EmailField(max_length=254, primary_key=True)
tel_number = models.CharField(max_length=13, blank=True)
referral_code = models.UUIDField()
class Meta:
verbose_name_plural = 'People'
def __str__(self):
return str(self.referral_code)
class Questionnaire(models.Model):
user = models.ForeignKey(Person, related_name='questionnaire_person', on_delete=models.CASCADE)
... and some questionnaire questions here (CharFields and TextFields) ...
# views.py
def index_questionnaire(request):
template = 'questionnaire.html'
# load blank instance of template
questionnaire = UserQuestionnaire()
context = {
"questionnaire": questionnaire
}
# if user has submitted something, check form is valid
if request.method == 'POST':
answers = UserQuestionnaire(data=request.POST)
if answers.is_valid():
# submission is genuine so save as new entry to database
# get user's unique referral ID from URL
user_referral_id = request.GET.get('user')
# check legit person
try:
answers.save(commit=False)
answers.person = get_object_or_404(Person, referral_code=user_referral_id)
print('user found: {}'.format(answers.person))
answers.save(commit=True)
print('Questionnaire saved')
except:
print("user not found")
return render(
request,
template,
context
)
#forms.py
class UserQuestionnaire(forms.ModelForm):
class Meta:
model = Questionnaire
fields = (
'answers_1',
'free_text_1',
'answers_2',
'answers_3',
'answers_4',
'answers_5',
'answers_6'
)
widgets = {
'answers_2' : forms.RadioSelect(),
'answers_3' : forms.RadioSelect(),
'answers_4' : forms.RadioSelect(),
'answers_5' : forms.RadioSelect(),
}
So at the moment I'm drawing the user parameter from the URL, which is uuid.uuid4(). The print statement in the "try: except" bit successfully prints out the user UUID as expected, yet when submitted it doesn't save correctly. For further info, I am using the MultiSelectField() for one of the questionnaire questions.
If anyone has any suggestions as to why this might be, that would be amazing!
That is because asnwers.save(commit=False) creates another new object.
Do something like
f = answer.save(commit=false)
f.person = get_object_or_404(Person, referral_code=user_referral_id)
f.save()
No need to do f.save(commit=True) since the True is default.
for more info check docs:
docs.djangoproject.com/en/3.1/topics/forms/modelforms/
Hi im following the tango with django tutorial.. I've searched for a solution to this but nothing!
the error:
IntegrityError at /rango/add_category/
UNIQUE constraint failed: rango_category.name
my model:
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
def __unicode__(self):
return self.name
class Page(models.Model):
category = models.ForeignKey(Category) #ForeignKey denotes a relationship between page and category
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __unicode__(self):
return self.title
my add_category view:
def add_category(request):
# Get the context from the request.
context = RequestContext(request)
# A HTTP POST?
if request.method == 'POST':
form = CategoryForm(request.POST)
#Have we been provided with a valid form?
if form.is_valid():
#save the new category to the database
form.save(commit=True)
# Now call the index() view.
# The user will be shown the Homepage.
return index(request)
else:
# The supplied form contained errors - just print them to the terminal
print (form.errors)
else:
form = CategoryForm()
# Bad form (or form details), no form supplied...
# Render the form with error message(if any).
return render_to_response('rango/add_category.html', {'form':form}, context)
my forms:
from django import forms
from rango.models import Page, Category
class CategoryForm(forms.ModelForm):
names = forms.CharField(max_length=128, help_text="please enter the category name.")
views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
#an inline class to to provide additional information on the form
class Meta:
# provide an association between the Modelform and a model
model = Category
fields = ('views', 'likes')
class PageForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the title of the page")
url = forms.URLField(max_length=200, help_text="Please enter the url of the page")
views = forms.IntegerField(widget=forms.HiddenInput(),initial=0)
class Meta:
# Provide an association between the ModelForm and a model
model = Page
#what fields do we want to include in our form
# this way we dont need every field in the model present
# Some fields may allow NULL values, so we may not want to include them...
# Here we are hiding.
fields = ('title', 'url', 'views')
'name' field is missing in CategoryForm's Meta 'fields'. Since Category::name is a unique field and default is not possible, any attempt to save will fail.
If the model does not allow the missing fields to be empty, and does
not provide a default value (not possible for unique) for the missing fields, any attempt to save() a ModelForm with missing fields will fail.
I have a models in models.py
class Page(models.Model):
url = models.CharField(verbose_name="url", unique=True, db_index=True, max_length=255)
template = models.ForeignKey(Template)
class PageToBlock(models.Model):
page = models.ForeignKey(Page)
placeholder = models.ForeignKey(Placeholder)
block = models.ForeignKey(Block,null=True)
and some code in views
PTBFormSet = inlineformset_factory(models.Page, models.PageToBlock, extra=0, can_delete=False)
formset = PTBFormSet(instance=page)
for form in formset:
# i need initial here for processing
print form.fields['placeholder'].initial #print None!, but in final rendered form it has value
How to extract initial?
form.initials['placeholder'] works fine
I am developing my first Google App Engine project and I think I am misunderstanding something fundamental about the database and form models. I have the following python code:
class RegData(db.Model):
title = db.StringProperty()
forename = db.StringProperty()
surname = db.StringProperty()
interest = db.StringListProperty(choices=['TV','COMPUTING','SOCCER'])
class RegForm(djangoforms.ModelForm):
class Meta:
model = RegData
What I want to do is have the form render the 'interest' property as a set of check boxes instead of a text area. Is this possible?
Thanks.
from django import forms as form
you must add the above module in models.py
models.py
interest=(
('Tv', 'TV'),
('Computing', 'COMPUTING'),
('Soccer', 'SOCCER'),
)
class RegData(db.Model):
title = db.StringProperty()
forename = db.StringProperty()
surname = db.StringProperty()
interest = db.StringListProperty()
class RegForm(djangoforms.ModelForm):
interest= form.CheckboxSelectMultiple(choices=interest)
class Meta:
model = RegData
RegData is the table in your database (entity) , RegForm is that the user will see this form on your page.
main.py
class ShowForm(webapp.RequestHandler):
def get(self):
show(self)
def post(self):
show(self)
def show(self):
get = self.request.GET
post = self.request.POST
data = models.RegData()
if post:
form = models.RegForm(data=post, instance=RegDate)
if form.is_valid():
entity = form.save(commit=False)
entity.put()
else:
form = models.RegForm(instance=RegDate)