Django 'unicode' object has no attribute 'field' - django

I recently added crispy_forms to my django project and it caused me to get the 'unicode' object has no attribute 'field' error. Can't figure out why.
models.py
class Trip(models.Model):
location_name = models.CharField(max_length=60)
trip_date = models.DateField()
trip_rating = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)])
fishing_vehicle = models.ForeignKey(FishingVehicle)
water_body = models.ForeignKey(WaterBody)
user = models.ForeignKey(User)
def __unicode__(self):
return self.location_name
views.py
#login_required
def logtrip(request):
if request.method == 'POST':
form = forms.TripForm(request.POST)
if form.is_valid():
trip = form.save(commit=False)
trip.user = request.user
trip.save()
return redirect('home')
else:
print form.errors
else:
form = forms.TripForm()
return render_to_response('logtrip.html', {'form': form}, context_instance=RequestContext(request))
forms.py
class TripForm(ModelForm):
CHOICES = (('1', 'None',), ('2', 'Below Average Amount',), ('3', 'Average Amount',), ('4', 'Above Average Amount',), ('5', 'A Lot/Limited Out',))
trip_rating = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES, label='Fish Caught')
class Meta:
model = Trip
exclude = ['user']
widgets = {'trip_date': forms.DateInput(attrs={'class':'datepicker'})}
logtrip.html
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
<!-- Example row of columns -->
<div class="row">
<div class="col-md-4">
<form action="/logtrip/" method="post">
{% csrf_token %}
{{ form.as_p|crispy }}
<input type="submit" value="Submit" />
</form>
</div>
</div>
</div>
{% endblock %}
Everything works correctly when I remove the |crispy filter.

For anyone else getting this error, my problem was solved by changing {{ form.as_p|crispy }} to {{ form|crispy }}.

Related

Django Model Objects cannot seen in Django Template

Rendered django model object cannot give any output in template. My Code is:
model.py:
class MyModel(models.Model):
address = models.GenericIPAddressField(
max_length=15,
verbose_name=_('address')
)
Path = models.CharField(
max_length=300,
verbose_name='path',
)
activate = models.CharField(max_length=5, default='off', )
views.py:
class MyView(ListView):
model = models.MyModel.objects.all()[0]
template_name = '../on_off.html'
context_object_name = 'obj_list'
admin.py:
class MyAdmin(admin.ModelAdmin):
list_display = ('address', 'Path', )
exclude = ('activate', )
change_list_template = '../on_off.html'
on_off.html:
{% extends 'admin/change_list.html' %}
{% block object-tools %}
{% if obj_list %}
<form id="on_off_status" method="POST">
<label id="onoff" class="switch">
{% csrf_token %}
<input type="checkbox" id="togBtn" value=" {{ obj_list.activate }} ">
<div class="slider round"></div>
</label>
</form>
{% endif %}
...
In Django model, the system accepts only one object and I want to give to toggle switch button value in template using activate field in MyModel model. But it is not rendered in template, I couldn't get any object data even if I try <h1> {{ obj_list }} </h1>, it turns <h1> </h1> . Any help or suggestion appreciated.
Render the field manually
<label id="onoff" class="switch">
{% csrf_token %}
{{ obj_list.activate }}
<div class="slider round"></div>
</label>
Instead of using the views.py, django-admin provide a function named changelist_view(). Now it is working, I deleted the funtion in views.py and I added changelist_view() function to my admin.py looks like:
class MyAdmin(admin.ModelAdmin):
list_display = ('address', 'Path',)
exclude = ('activate',)
change_list_template = '../nfs_on_off.html'
def changelist_view(self, request, extra_context=None):
object = self.model.objects.all()
context={
'obj_list': object,
}
return super(MyAdmin, self).changelist_view(request, context)

My form keep saying "This(image) field is required!" Django 3.0

I made a project with net-ninja on youtube now I am adding "uploading media" feature in my own project but it is not working although every thing is set just tell me where i m going wrong.
My form is keep asking me to upload image file even though i had already done, every time i send a post request it renders the page again with no value in image field. what is wrong here, why it is not taking image input?Don't comment set the required to false that is not the solution i don't know why some people said this to others on stackoverflow when they asked the same question as me.
My model class looks like this
class Products(models.Model):
name = models.CharField(max_length=500, unique=True, )
price = models.IntegerField()
stock = models.IntegerField()
date_added = models.DateTimeField(verbose_name="date added", auto_now_add=True, )
thumb = models.ImageField(default='default.png', blank=True)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE, default=None,)
def __str__(self):
return self.name
class Meta():
verbose_name_plural = "Products"
My form looks like this
class AddProduct(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Product Name', 'required':'True', 'class': 'form-control'}))
price = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder':'Set Price', 'required':'True', 'class': 'form-control'}))
stock = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder':'Number of items', 'required':'True', 'class': 'form-control'}))
thumb = forms.ImageField(required=False, widget=forms.ClearableFileInput(attrs={'placeholder':'Upload Picture', 'enctype' : 'multipart/form-data'}))
class Meta():
model = Products
fields = ('name', 'price', 'stock','thumb', )
HTML looks like this
<form class="row contact_form" action="/shop/add_products" method="post">
{% csrf_token %}
{% for field in form %}
<div class="col-md-12 form-group p_star">
{{ field }}
{{ field.errors }}
</div>
{% endfor %}
<!-- {% for field in form %}
{% for error in field.errors %}
<div class="col-md-12 form-group p_star">
{{ error }}
</div>
{% endfor %}
{% endfor %} -->
{% if form.non_field_errors %}
<div class="col-md-12 form-group p_star">
{{ form.non_field_errors }}
</div>
{% endif %}
<div class="col-md-12 form-group">
<button type="submit" value="submit" class="btn_3">
Add Product
</button>
</div>
</form>
My views file looks like this
#login_required(login_url='/shop/login')
def shop_add_products(request):
if request.method == 'POST':
form = AddProduct(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.profile = request.user
instance.save()
return redirect("/shop/products")
else:
form = AddProduct()
return render(request, "pillow_site_html/add_product.html", { 'form':form })
Oh sorry i didn't understood the question here, you are getting that because in fact you are not sending the picture inside your form as you have to add this to your form so it can accept files handling
<form class="row contact_form" action="/shop/add_products" method="post" enctype="multipart/form-data">

error saving photo in database 'NoneType' object has no attribute 'user'

I have a model with Usuario where the profile foto goes and it saves perfectly in the database, so to be able to add more images as if it were a gallery, I created another model called Gallery, I copied the same specificiation of what was already working in the model Usuario, however he is not saving the photos in the database, and I do not know where I am going wrong.
I appreciate any help.
and I need the Gallery model to receive the foreign Usuario key
Erro:
IntegrityError at /gallery-novo/
null value in column "usuario_id_id" violates not-null constraint
DETAIL: Failing row contains (3, IMG_20180622_101716179_BURST006.jpg, eu e meu amor, null).
views.py
def gallery(request):
gallery = Gallery.objects.all()
form = GalleryForm()
data = {'gallery': gallery, 'form': form}
return render(request, 'gallery.html', data)
def gallery_novo(request):
if request.method == 'POST':
form = GalleryForm(request.POST, request.FILES)
if form.is_valid():
form.save(user=request.user)
return redirect('sistema_perfil')
else:
form = GalleryForm
return render(request, 'gallery.html', {'form': form})
models.py
class Gallery(models.Model):
gallery = StdImageField( blank=False, variations={
'large': (600, 400),
'thumbnail': (100, 100, True),
'medium': (300, 200),
})
titulo = models.CharField(max_length=50, blank=False)
usuario_id = models.ForeignKey(User, on_delete=models.CASCADE, blank=False)
forms.py
class GalleryForm(forms.ModelForm):
gallery = forms.FileField(
widget=forms.ClearableFileInput(attrs={'multiple': 'True'}))
titulo = forms.CharField()
class Meta:
model = Gallery
fields = ( 'gallery', 'titulo')
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
return super(GalleryForm, self).__init__(*args, **kwargs)
def save(self, commit=True, user=None):
form = super(GalleryForm, self).save(commit=False)
form.usario_id = user
if commit:
form.save()
return form
gallery.html
{%extends 'bases/base.html' %}
{% load static %}
{% load bootstrap %}
{% load widget_tweaks %}
{% load crispy_forms_tags %}
{% block main %}
<div class="card text-white bg-primary">
<div class="card-header"><p class="card-text">
<small class="text-muted">
Home /
<a class="text-white">Cadastro</a>
</small></a></p> Cadastro de Usúario
</div>
<div class="card title ">
<div class="card-body text-secondary">
<form class="exampleone" action="{% url 'sistema_gallery_novo' %}" method="POST" enctype="multipart/form-data" id="form" name="form" validate >
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-4">
{{ form.gallery | as_crispy_field }}
</div>
<div class="form-group col-md-4">
{{ form.titulo | as_crispy_field }}
</div>
<div class="form-group col-md-4">
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block">Cadastrar</button>
</form>
</div>
</div>
</div>
{% endblock %}
{% block rightcol %}
{% include 'bases/rightcol.html' %}
{% endblock %}
{% block footer %}
{% include 'bases/footer.html' %}
{% endblock %}
urls.py
url(r'gallery/$', gallery, name='sistema_gallery'),
url(r'gallery-novo/$', gallery_novo, name='sistema_gallery_novo'),
In my opinion, you are reinventing the wheel, the django right approach is to use commit=False on save method:
def gallery_novo(request):
if request.method == 'POST':
form = GalleryForm(request.POST, request.FILES)
if form.is_valid():
my_novo_gallery = form.save(commit=False) #save no commit
my_novo_gallery.user=request.user #set user
my_novo_gallery.save() #save to db
return redirect('sistema_perfil')

Django: ModelFormSet saving first entry only

Update:
The issue seemed to be in the coding for Django-formset. I was processing it as an inline formset and not a model formset. The answer below was also correct. Thanks!
I am working with a model formset for an intermediate model. I am using django-formset js to add additional formset fields on the template. Most everything works OK except that when I go to save the formset only the first entry is being saved to the DB. The first entry is saved and assigned correctly but any after than just disappear. It is not throwing any errors so I am not sure what is going wrong. Thanks!
The Model
class StaffAssignment(models.Model):
study = models.ForeignKey(Study, related_name='study_set', null=True, on_delete=models.CASCADE)
staff = models.ForeignKey('account.UserProfile', related_name='assigned_to_set', null=True, on_delete=models.CASCADE)
role = models.CharField(max_length=100, null=True)
assigned_on = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-role',)
def __str__(self):
return '{} is assigned to {}'.format(self.staff, self.study)
The Form:
class AddStaff(forms.ModelForm):
model = StaffAssignment
fields = ('staff',)
def __init__(self, *args, **kwargs):
super(AddStaff, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs.update({'class': 'form-control'})
The View:
def add_staff(request, study_slug):
study = get_object_or_404(Study, slug=study_slug)
staff_formset = modelformset_factory(StaffAssignment, form=AddStaff, fields=('staff',), can_delete=True)
if request.method == 'POST':
staffList = staff_formset(request.POST, request.FILES)
if staffList.is_valid():
for assignment in staffList:
assigned = assignment.save(commit=False)
assigned.study = study
assigned.role = assigned.staff.job_title
assigned.save()
return HttpResponseRedirect(reverse('studies:studydashboard'))
else:
HttpResponse('Something is messed up')
else:
staffList = staff_formset(queryset=StaffAssignment.objects.none())
return render(request, 'studies/addstaff.html', {'staffList': staffList, 'study': study})
The Template:
<form action="{% url 'studies:addstaff' study.slug %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="box-body">
{% for list in staffList %}
<div class="form-group" id="formset">
{% if list.instance.pk %}{{ list.DELETE }}{% endif %}
{{ list.staff }}
{% if list.staff.errors %}
{% for error in list.staff.errors %}
{{ error|escape }}
{% endfor %}
{% endif %}
</div>
{% endfor %}
{{ staffList.management_form }}
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
You are not including the primary key field in the template, as required by the docs. Add
{% for list in staffList %}
{{ list.pk }}
...
{% endfor %}

Uploading multiple images in Django for a single post

I am beginner in django . I would like to make an application that allows a user to record examinations and related images.
So i try to uploading multiple images in Django for a single post according this topic http://qasimalbaqali.com/uploading-multiple-images-in-django-for-a-single-post/.
But nothing happens when I press the button
I explain my models. A document is a generic class. An exam is a document, a document contains files.
class Document(models.Model):
class Meta:
db_table = 'Document'
slug = models.SlugField(max_length=100)
user = models.ForeignKey(User)
level = models.ForeignKey(ClassLevel, null=False, default=1)
school = models.ForeignKey(School, null=False, default=1)
nb_views = models.IntegerField(default=0)
name = models.CharField(max_length=100)
matter = models.ForeignKey(ClassTopic, null=False, default=1)
status = models.IntegerField(choices=DOCUMENT_STATUS, default=1)
creation_date = models.DateTimeField(auto_now_add=True)
deletion_date = models.DateTimeField(auto_now_add=False, default=None, null=True)
def __unicode__(self):
return self.name + " (" + str(self.status) + ") " + self.school.name
class DocumentFile(models.Model):
class Meta:
db_table = 'DocumentFile'
file = models.FileField(upload_to="photo/", null=True)
document = models.ForeignKey(Document)
def __unicode__(self):
return self.file
class Exam(Document):
class Meta:
db_table = 'Exam'
year_exam = models.IntegerField(choices=EXAM_YEAR_CHOICES, default=1)
mock_exam = models.IntegerField(choices=EXAM_TYPE, default=1)
def __unicode__(self):
return self.name + " " + self.matter
I create two forms. For exam and for file.
class UploadFileForm(ModelForm):
#description = forms.CharField(max_length=30)
file = forms.FileInput()
helper = FormHelper()
helper.form_id = 'file-input'
helper.form_show_labels = False
helper.layout = Layout(PrependedText('file', "", placeholder=""))
#helper.layout.insert(1, HTML("<input type='file' class='file' multiple data-show-upload='false' data-show-caption='true'>"))
class Meta:
model = DocumentFile
fields = ('file',)
#exclude = ("file_type", "file_path", "document")
class CreateExamForm(forms.ModelForm):
helper = FormHelper()
helper.form_id = 'CreateExam'
helper.form_show_labels = False
helper.layout = Layout(
PrependedText("matter", "", ""),
PrependedText("level", "<small class='text-warning'>Selectionner la classe. </small>", ""),
PrependedText("school", "<pre><small>Selectionner l\'établissement. </small></pre>", css_class="selectpicker"),
PrependedText("year_exam", ""),
PrependedText("mock_exam", ""))
class Meta:
model = Exam
exclude = ("slug", "user", "nb_views", "name", "status", "creation_date", "deletion_date")
My view
def createexam(request):
# Creation du formulaire + upload des images
doc_form = CreateExamForm(auto_id=True)
# Création du formset avec n itération : extra=2
file_form_set = modelformset_factory(DocumentFile, form=UploadFileForm, extra=1)
# Récupération du formulaire géré par le mécanisme formset
#formset = sortedfilesform()
if request.method == "POST":
doc_form = CreateExamForm(request.POST)
files_form = file_form_set(request.POST, request.FILES, queryset=DocumentFile.objects.none())
if doc_form.is_valid() and files_form.is_valid():
doc_save = doc_form.save(commit=False)
doc_save.user = request.user
for fileform in files_form.cleaned_data:
image = fileform['file']
one_image = DocumentFile(document=doc_save, file_value=image)
one_image.save(commit=False)
transaction.commit()
msg = FORM_PROPERTIES.FORM_EXAM_STORED.replace("user", request.user.nickname)
messages.add_message(request, messages.SUCCESS, msg)
form = LoginForm()
context = {'form': form}
return render_to_response(template_name='login.html', context=context, context_instance=RequestContext(request))
else:
messages.add_message(request, messages.SUCCESS, FORM_PROPERTIES.FORM_EXAM_ERROR)
context = {'doc_form': doc_form, 'file_form_set': file_form_set, }
return render(request, 'createexam.html', context)
else:
context = {'doc_form': doc_form, 'file_form_set': file_form_set, }
return render(request, 'createexam.html', context)
my url.py
urlpatterns = [
# Examples:
url(r'^$', home, name='home'),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', home),
url(r'^home', home),
url(r'^login', login),
url(r'^logout', logout),
url(r'^register$', register),
url(r'^createexam$', createexam),
url(r'^account/reset_password', reset_password, name="reset_password"),
]
My template is simple
<div id="login-overlay" class="modal-dialog">
<div class="row">
<div class="panel panel-info" >
<div class="panel-heading">
<div class="panel-title">Créer un examen</div>
</div>
<div class="panel-body" >
<div class="col-sm-12">
<form id="post_form" method="POST" action='.'
enctype="multipart/form-data">
{% csrf_token %}
{% for hidden in doc_form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in doc_form %}
{{ field }} <br />
{% endfor %}
{{ file_form_set.management_form }}
{% for form in file_form_set %}
{% crispy form %}
{% endfor %}
<input type="submit" value="Add recipe" class="submit" />
</form>
</div>
</div>
</div>
</div>
Everything seems good form me. But my submit does no think.
I 'm on it for two days.
I read and tried many things. Does anybody can help me please (Sorry for my english)
There are a couple of things wrong here.
Firstly you are not showing the form errors in the template, so the user has no way of knowing why their submission is invalid. Make sure you either do {{ field.errors }} after every field, or do {{ form.errors }} for the whole form at once; and remember to do this both form the main form and the image formset.
Secondly, you're saving the forms with commit=False, so they are not persisted to the database. It's fine to do that if you want to add extra data not included in the form, but you then need to remember to actually persist the object by calling eg doc_save.save().
I solved my problem when i put my main form body in <table> ... </table>
<form id="CreateExamForm" method="POST" enctypr="multipart/form-data">
{% csrf_token %}
<table>
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Classe - Matière - Date</h3>
<span class="pull-right"><i class="glyphicon glyphicon-chevron-up"></i></span>
</div>
<div class="panel-body">
{% crispy doc_form %}
{{ file_form_set.management_form }}
{% for f_form in file_form_set %}
<div class="form-inline">
{% crispy f_form %}
</div>
{% endfor %}
</div>
</div>
</table>
<input type="submit" value="Add recipe" class="submit" />
</form>