File Upload fails using ModelForm - no error messages though - django-forms

I'm using ModelForms with the generic editing views (create, update, delete). One of my aims in this exercise is to get to know some frameworks (Django + Bootstrap + a plugin (e.g. PDF.js)) and use as little custom code as possible.
I can create a 'document' record through the Admin site and the upload is saved in the 'files' location I set. When I try through my site, no file is uploaded, although the other fields will be updated (evidently the form validates).
(The FileField IS nullable, because I want to be able to have a pointer to a non-digital asset). The relevant code:
# models.py
class document(models.Model):
ref_file = models.FileField(upload_to='documents/', blank=True, null=True)
def get_absolute_url(self):
return reverse('knowledge_manager:doc_detail', kwargs={'pk': self.pk})
# urls.py
urlpatterns = [
url(r'^doc$', views.docIndex.as_view(), name='doc_index'),
url(r'^doc/(?P<pk>\w+)/det', views.docUpdate.as_view(), name='doc_detail'),
url(r'^doc/new/$', views.docCreate.as_view(), name='doc_create'),
url(r'^doc/(?P<pk>\w+)/update', views.docUpdate.as_view(), name='doc_update'),
url(r'^doc/(?P<pk>\w+)/del', views.docDelete.as_view(), name='doc_delete')
]
# views.py
class docIndex(generic.ListView):
model = document
template_name = 'knowledge_manager/_index.html'
context_object_name = 'document_set'
class doc_detail(generic.DetailView):
model = reference
template_name = 'knowledge_manager/doc_detail.html'
context_object_name = 'document'
form_class = doc_form
success_url = reverse_lazy('knowledge_manager:doc_index')
class docCreate(generic.CreateView):
model = document
template_name = 'knowledge_manager/doc_detail.html'
form_class = doc_form
success_url = reverse_lazy('knowledge_manager:doc_index')
class docUpdate(generic.UpdateView):
model = document
template_name = 'knowledge_manager/doc_detail.html'
context_object_name = 'document'
form_class = doc_form
success_url = reverse_lazy('knowledge_manager:doc_index')
class docDelete(generic.DeleteView):
model = document
success_url = reverse_lazy('knowledge_manager:doc_index')
# forms.py
class doc_form(ModelForm):
class Meta:
model = document
fields = '__all__'
Questions:
what do you think is going wrong? Surely ModelForms with FileFields initialise using 'request.FILES' as well as 'instance' and 'request.POST'?
what's a good way to get debugging messages about what is actually
getting posted? Using function views I used to just pop 'print('made it to
here, value X is', value_x) - is there a better way than just overloading the standard functions of ModelForms etc?

I had overlooked this solution (stackoverflow), which pointed out that the form needs this tag to correctly send material to request.FILES.
<form action="" method="post" **enctype="multipart/form-data"**>

Related

Django REST Framework - optimizing nested serialization of a queryset

I have a model and serializer like this:
models.py
class CalendarEvent(BaseMixin):
title = models.TextField(blank=True, null=True)
class CalendarEventReminder(BaseMixin):
event = models.ForeignKey(CalendarEvent, related_name = 'reminders')
minutes = models.CharField()
class Meta:
managed = False
db_table = 'calendar_event_reminder'
def __str__(self):
return self.minutes
serializer.py
class CalendarEventSerializer(serializers.ModelSerializer):
reminders = serializers.StringRelatedField(many=True)
class Meta:
model = CalendarEvent
fields = ('title', 'reminders')
In my view, I do the following:
def test(request):
#...
event = CalendarEvent.objects.filter(id__in = [930, 935])
serializer = CalendarEventSerializer(event, many = True)
print (serializer.data)
#...
When I open the Debug Toolbar, I see that the database hits reminders table twice for each of the calendar events.
The question is, how this behavior could be optimized.
The most straight-forward way would be prefetching the CalendarEventReminders of the CalendarEvents in your view:
# views.py
def get(request):
event = CalendarEvent.objects.filter(id__in = [930, 935]) \
.prefetch_related('reminders')
# ...
This will prefetch all CalendarEventReminders while getting the CalendarEvents.
Note that this will not trigger a sql join like select_related() would do. We can't use select_related() in this case because we're following the relation backwards. :)
Check out the Django Docs regarding prefetch_related.

Django Rest Framework - return reverse foreign key property?

I think this is simple and probably a duplicate, but I cannot figure it out by looking at the documentation.
I have Django models as follows:
class Image(models.Model):
manor = models.ForeignKey(Manor, related_name='image_for_manor')
filename = models.CharField(max_length=30, null=True, blank=True)
class Manor(models.Model):
id = models.IntegerField(primary_key=True)
I want the user to be able to query the Manor and see the related Image. I'd like this JSON to be returned:
{
id: 572,
image: 'my/filepath.png'
}
This is my view:
#api_view(['GET'])
def manor(request, id):
mymanor = Manor.objects.get(id=id)
serializer = ManorSerializer(mymanor)
return JSONResponse(serializer.data)
And these are my serializers:
class ImageFilePathSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = ('filename',)
class ManorSerializer(serializers.ModelSerializer):
image = ImageFilePathSerializer(source="image_for_manor")
class Meta:
model = Manor
fields = ('id', 'image')
But this doesn't work: I get an empty dictionary for image. (Even if it weren't empty, I realise it wouldn't be right, because I don't want the image property to be a dictionary: I want it to be a string.)
How can I change this to be correct? I cannot work it out.
As Kevin suggested , why dont you use ImageField which will give you url where your image is uploaded. although if you dont want to do that , here are some changes you have to do to get the result format you wanted.(Following solution assumes that only one image will be for one minor)
views.py ( why dont you ImageFilePathSerializer instead of another one as it also contains all the data you wanted)
#api_view(['GET'])
def manor(request, id):
mymanor = Image.objects.get(manor__id=id)
serializer = ImageFilePathSerializer(mymanor)
return Response(serializer.data)
serializers.py (add Id with filename in ImageFilePathSerializer)
class ImageFilePathSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = ('id', 'filename',)
class ManorSerializer(serializers.ModelSerializer):
filename = serializers.ImageField(source="image_for_manor")
class Meta:
model = Manor
fields = ('id', 'filename')

Django 1.3 CreateView, ModelForm and filtering fields by request.user

I am trying to filter a field on a ModelForm. I am subclassing the generic CreateView for my view. I found many references to my problem on the web, but the solutions do not seem to work (for me at least) with Django 1.3's class-based views.
Here are my models:
#models.py
class Subscriber(models.Model):
user = models.ForeignKey(User)
subscriber_list = models.ManyToManyField('SubscriberList')
....
class SubscriberList(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=70)
....
Here is my view:
#views.py
class SubscriberCreateView(AuthCreateView):
model = Subscriber
template_name = "forms/app.html"
form_class = SubscriberForm
success_url = "/app/subscribers/"
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
return super(SubscriberCreateView, self).form_valid(form)
Here is my original form for adding a Subscriber, with no filter:
#forms.py
class SubscriberForm(ModelForm):
class Meta:
model = Subscriber
exclude = ('user', 'facebook_id', 'twitter_id')
Here is my modified form, attempting to filter, but doesn't work:
#forms.py
class SubscriberForm(ModelForm):
class Meta:
model = Subscriber
exclude = ('user', 'facebook_id', 'twitter_id')
def __init__(self, user, **kwargs):
super(SubscriberForm, self).__init__(**kwargs)
self.fields['subscriber_list'].queryset = SubscriberList.objects.filter(user=user)
If I change this modified form as so:
def __init__(self, user=None, **kwargs)
It works - It brings me NO subscriber lists. But any way I try to pass the request user, I invariably get a a name "request" or name "self" not defined error.
So, how can I modify my code to filter subscriber_list by the request.user, and still use Django 1.3's CreateView.
I see you've been posting this question in various places.. and the way I found that is because I was trying to figure out the same thing. I think I just got it working, and here's what I did. I overwrote get_form() from FormMixin to filter a specific form fields queryset:
class MyCreateView(CreateView):
def get_form(self, form_class):
form = super(MyCreateView,self).get_form(form_class) #instantiate using parent
form.fields['my_list'].queryset = MyObject.objects.filter(user=self.request.user)
return form

How to subclass django's generic CreateView with initial data?

I'm trying to create a dialog which uses jquery's .load() function to slurp in a rendered django form. The .load function is passed the pk of the "alert" object. Also available in the class functions are things like self.request.user so I can pre-fill those fields, shown below in the Message model (models.py):
class Message(models.Model):
user = models.ForeignKey(User)
alert = models.ForeignKey(Alert)
date = models.DateTimeField()
message = models.TextField()
Subclassing django's CreateView makes it pretty easy to generate a context with an instance of the ModelForm (views.py):
class MessageDialogView(CreateView):
""" show html form fragment """
model = Message
template_name = "message.html"
def get_initial(self):
super(MessageDialogView, self).get_initial()
alert = Alert.objects.get(pk=self.request.POST.get("alert_id"))
user = self.request.user
self.initial = {"alert":alert.id, "user":user.id, "message":"test"}
return self.initial
def post(self, request, *args, **kwargs):
super(MessageDialogView, self).post(request, *args, **kwargs)
form_class = self.get_form_class()
form = self.get_form(form_class)
context = self.get_context_data(form=form)
return self.render_to_response(context)
The problem here is that self.initial does not get rendered with the form. I have insured that the form is indeed calling get_initial and the form instance has the proper initial data in post, but when the form is rendered in the template message.html it doesn't grab any of the initial data like I would expect. Is there a special trick to get this to work? I've scoured the docs (seems to be lacking examples on generic based class views) and source but I can't see what I'm missing.
get_initial() should just return a dictionary, not be bothered with setting self.initial.
Your method should look something like this:
def get_initial(self):
# Get the initial dictionary from the superclass method
initial = super(YourView, self).get_initial()
# Copy the dictionary so we don't accidentally change a mutable dict
initial = initial.copy()
initial['user'] = self.request.user.pk
# etc...
return initial
you can use like :
from django.shortcuts import HttpResponseRedirect
class PostCreateView(CreateView):
model = Post
fields = ('title', 'slug', 'content', 'category', 'image')
template_name = "create.html"
success_url = '/'
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return HttpResponseRedirect(self.get_success_url())
that's work for me
(Edited because what you're trying does actually work)
I ran into the same problem yesterday, but it's working now – I think I was returning an object instead of a dict in get_initial.
In terms of fixing your problem, I'm a little suspicious of how much you seem to be doing in post() – could you try it with the default (non-overrided) post()?
You could also use pdb (or print statements) to check the value of self.get_form_kwargs make sure that initial is being set.

Django Ajax field help

I have a Django application where I'm trying to have a form that populates a drop down dynamically based on a previous dropdown.
simplified Models:
class VehicleMake(models.Model):
make = models.CharField(max_length = 30)
class VehicleModel(models.Model):
model = models.CharField(max_length = 80)
make = models.ForeignKey(VehicleMake)
class Listing(models.Model):
make = models.ForeignKey(VehicleMake)
model = models.ForeignKey(VehicleModel)
Form:
class DynamicChoiceField(ModelChoiceField):
def clean(self, value):
return value
class MyForm(ModelForm):
category = ModelChoiceField(VehicleCategory.objects, widget=forms.Select(attrs={'onchange':'FilterMakes();'}))
make = DynamicChoiceField(VehicleMake.objects,widget=forms.Select(attrs={'disabled':'true','onchange':'FilterModels();'}), empty_label="Select Model")
model = DynamicChoiceField(VehicleModel.objects,widget=forms.Select(attrs={'disabled':'true'}), empty_label="Select Make")
class Meta:
model = Listing
View:
def new_listing(request):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
form.save()
else:
form = MyForm()
return render_to_response("newlisting.html", {
"form": form,'model_id':model_id,'make_id':make_id
})
I also have some ajax defined for the auto-populate but this is not the problem
When I submit the form I get the following:
Cannot assign "u'2'": "Listing.make" must be a "VehicleMake" instance.
if I try
make=VehicleMake.objects.get(pk=request.POST['make'])
form.fields['make'] = make
then I get
'VehicleMake' object has no attribute 'widget'
After the suggestion of one of the commenter's that the DynamicChoiceField class was the culprit I removed it and set the form objects for ModelChoiceFields with the exact same other parameters. The object appears to pass and validate correctly as well. The extra class existed based on an old tutorial I found. it appears that what the author did there works with the forms.ChoiceField but is not required for using a ModelChoiceField
thanks everyone for the help

Resources