I wanted to save image to profile's image field from template, but I'm not able to save in media root
class SettingFormView(FormView):
form_class = ProfileSettingsForm
template_name = 'profile.html'
success_url = '/'
def get_initial(self):
if self.request.user.is_authenticated():
profile = Profile.objects.get(user_id__exact=self.request.user.id)
self.initial['first_name'] = profile.first_name
self.initial['last_name'] = profile.last_name
self.initial['fathers_name'] = profile.fathers_name
self.initial['email'] = profile.email
self.initial['mobile'] = profile.mobile
self.initial['entity'] = profile.entity
self.initial['image'] = profile.image
return self.initial.copy()
def form_valid(self, form):
if self.request.user.is_authenticated():
form = ProfileSettingsForm(self.request.POST, self.request.FILES)
user = User.objects.get(username__exact=self.request.user.username)
if form:
profile = Profile.objects.get(user_id__exact=self.request.user.id)
profile.first_name = self.request.POST['first_name']
profile.last_name = self.request.POST['last_name']
profile.fathers_name = self.request.POST['fathers_name']
if user.email != self.request.POST['email']:
profile.email = self.request.POST['email']
user.email = self.request.POST['email']
profile.mobile = self.request.POST['mobile']
profile.entity = self.request.POST['entity']
profile.image = self.request.POST['image']
**profile.image.async = self.request.POST['image']**
profile.save()
user.save()
return super(SettingFormView, self).form_valid(form)
else:
return redirect('/profile/sign')
I get the following exception:
Exception Type: MultiValueDictKeyError Exception Value: "'image'"
Uploaded files are in request.FILES, not request.POST. Alos take a lok at the Documentation.
'Plain' version
f = request.FILES['image']
with open('upload/destination.ext', 'wb+') as dest:
for chunk in f.chunks():
dest.write(chunk)
Model version
Documentation
profile_form = ProfileSettingsForm(request.POST, request.FILES)
if profile_form.is_valid():
profile = Profile(image=request.FILES['image'])
profile.first_name = request.POST.get('first_name')
# ...
profile.save()
Related
I have genericview which handle 3 difference form(2 formsets), when i try check cleaned_data, i have error, but when i try make the same by debugger i didn't see anything problem, who may know why i can't make it?
My View :
class CompanyCreateView(LoginRequiredMixin, CreateView):
model = Company
template_name = 'main/company/create_page.html'
form_class = CompanyCreateForm
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['page'] = Page.objects.active().filter(slug='add_company').first()
if self.request.POST:
context['images'] = ImageGalleryFormSet(self.request.POST, self.request.FILES)
context['company_locations'] = CompanyLocationFormset(self.request.POST)
else:
context['images'] = ImageGalleryFormSet(self.request.GET or None)
context['company_locations'] = CompanyLocationFormset(self.request.GET or None)
return context
#transaction.atomic
def form_valid(self, form):
context = self.get_context_data()
images = context['images']
company_locations = context['company_locations']
self.object = form.save()
self.object.active = False
self.object.status = CompanyConstants.CompanyStatus.NEW
self.object.owner = self.request.user
self.object.save()
for image in range(len(images)):
key_image = 'gallery_items-' + str(image) + '-image'
form_image = self.request.FILES.get(key_image)
if form_image:
ImageGallery(image=form_image, company_id=int(self.object.id)).save()
print(company_locations.forms[0].get_cleaned_data)
for location in range(len(company_locations)):
key_locations = 'form-' + str(location) + '-location'
key_address = 'form-' + str(location) + '-address'
if self.request.POST.get(key_locations):
location = self.request.POST.get(key_locations)
address = self.request.POST.get(key_address)
company = self.object
CompanyLocation.objects.create(location=clean_location(location), address=address, company=company)
return super().form_valid(form)
def get_success_url(self):
return reverse('main:profile', args=[self.request.user.username])
When i try print this i have error, this code that i have works correct but, he is bad.
MY FORM :
class CompanyLocationForm(forms.ModelForm):
location = geo_forms.PointField(widget=GooglePointFieldWidget)
class Meta:
model = CompanyLocation
fields = ('location', 'address')
CompanyLocationFormset = formset_factory(CompanyLocationForm, max_num=10)
you need to clean your data to check the problem
#transaction.atomic
def form_valid(self, form):
def clean(self):
all_clean_data = super().clean()
all_clean_data[['page'] = Page.objects.active().filter(slug='add_company').first()
...
So i see a lot off data Just test
def Test(request):
if request.method == "POST":
form =CompanyLocationForm(data=request.POST)
if form.is_valid():
print(company_locations.forms[0].get_cleaned_data)
i have a small form in my blog detail view and it has a name,last name,email and an image field. the first three work fine but when i add the imagefield in the form, the form wont save from the page but it works from admin page.
this is my views.py:
def campaign_detail_view(request, id):
template_name = 'gngo/campaign-detail.html'
campaign = get_object_or_404(Campaign, id = id)
comments = CampaignForm.objects.filter(campaign=campaign).order_by('-id')
form = FormCamp(request.POST)
if request.method == 'POST':
if form.is_valid():
name = request.POST.get('name')
last = request.POST.get('last')
email = request.POST.get('email')
comment = CampaignForm.objects.create(campaign=campaign,name=name,last=last,email=email)
comment.save()
return redirect('campaign-detail',id=id)
else:
form = FormCamp()
context = {
'campaign':campaign,
'comments':comments,
'form':form,
}
context["object"] = Campaign.objects.get(id = id)
return render(request, template_name, context)
and this is my comment model:
class CampaignForm(models.Model):
campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
last = models.CharField(max_length=100)
email = models.EmailField()
image = models.ImageField(upload_to='images')
this is a non user form, so everyone can fill it. please help me understand how to add the ability to upload an image in this form
oh and this the form:
class FormCamp(forms.ModelForm):
class Meta:
model = CampaignForm
fields = ('name','last','email', 'image',)
THANKS ALOT FOR THE ANSWERS AND SUPPORTS
Instead of using the form to validate and then manually extracting the fields again, you should use the save method of your ModelForm and pass request.FILES to your form when creating it.
And as the campaign is not an editable field, it shall be added after creating the object.
def campaign_detail_view(request, id):
template_name = 'gngo/campaign-detail.html'
campaign = get_object_or_404(Campaign, id = id)
comments = CampaignForm.objects.filter(campaign=campaign).order_by('-id')
if request.method == 'POST':
form = FormCamp(request.POST, request.FILES)
if form.is_valid():
campaign_form = form.save(commit=False)
campaign_form.campaign = campaign
campaign_form.save()
return redirect('campaign-detail',id=id)
else:
form = FormCamp()
context = {
'campaign':campaign,
'comments':comments,
'form':form,
}
context["object"] = Campaign.objects.get(id = id)
return render(request, template_name, context)
https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/#the-save-method
https://docs.djangoproject.com/en/2.2/topics/forms/#the-view
Try this:
def campaign_detail_view(request, id):
template_name = 'gngo/campaign-detail.html'
campaign = get_object_or_404(Campaign, id = id)
comments = CampaignForm.objects.filter(campaign=campaign).order_by('-id')
form = FormCamp(request.POST, request.FILES)
if request.method == 'POST':
if form.is_valid():
comment = form.save(commit=False)
comment = CampaignForm.objects.create(campaign=campaign,name=name,last=last,email=email)
comment = request.FILES['image']
comment.save()
return redirect('campaign-detail',id=id)
else:
form = FormCamp()
context = {
'campaign':campaign,
'comments':comments,
'form':form,
}
context["object"] = Campaign.objects.get(id = id)
return render(request, template_name, context)
class FormCamp(forms.ModelForm): to this;
class FormCamp(forms.Form):
Don't forget to add enctype=multipart/form-data in your form in template.
I am writing an application on Django.
How can I save data (provider.category) from form using form.instance.
models
class RequestProvider(models.Model):
category = models.ManyToManyField(Category, related_name="provider_request")
forms
class ProviderForm(forms.ModelForm):
class Meta:
model = RequestProvider
fields = ('category',)
widgets = {
'category': forms.SelectMultiple(
attrs={
'class': 'select2',
'style': 'width: 246px;'
}
),
}
views
#method_decorator(currency_account_dec, name='dispatch')
class ProviderCreateView(CreateView):
form_class = ProviderForm
template_name = 'provider_create.html'
def form_valid(self, form):
provider_id = self.kwargs.get('provider_id',None)
session_user = self.request.user
if provider_id:
form.instance.provider = Provider.objects.get(pk=provider_id)
form.instance.user = self.request.user
#form.instance.category = form.cleaned_data.get('category')
return super(ProviderCreateView,self).form_valid(form)
def get_context_data(self, **kwargs):
provider_id = self.kwargs.get('provider_id',None)
ss = RequestProvider.objects.filter(user=self.request.user)
for s in ss:
print(s.category)
ctx = super(ProviderCreateView, self).get_context_data(**kwargs)
ctx['organizations'] = Organization.objects.filter(user=self.request.user)
ctx['payments'] = Payment.objects.all()
if provider_id:
this_provider = Provider.objects.get(pk=provider_id)
ctx['this_provider'] = this_provider
ctx['categories'] = Category.objects.all()
ctx['roles'] = this_provider.role.all()
ctx['payments'] = Payment.objects.all()
ctx['deliveries'] = Delivery.objects.all()
return ctx
I believe you can do form.save()
No need to rewrite the form_valid.
#method_decorator(currency_account_dec, name='dispatch')
class ProviderCreateView(CreateView):
form_class = ProviderForm
template_name = 'provider_create.html'
def post(self, request):
provider_id = self.kwargs.get('provider_id',None)
session_user = request.user
form = ProviderForm(request.POST)
if form.is_valid():
rq = form.save(commit=False)
if provider_id:
rq.provider = Provider.objects.get(pk=provider_id)
rq.user = self.request.user
rq.save()
rq.category = form.cleaned_data.get('category')
return HttpResponseRedirect('/providers/')
else:
return HttpResponseRedirect('/providers/create/')
i am using class based generic view in my Subject_En roll application
my view.py is
cc = 0
#login_required
def add_subject_enroll(request):
user = request.user
obj = StudentRegistration.objects.get(user=user)
print "obj.first_name",obj.first_name
first_name = obj.first_name
print "first_name",first_name
if obj.user:
print "object exist"
#form = Subject_EnrollForm(request.POST or None, initial={'student_name' : first_name})
#form = Subject_EnrollForm( initial={'student_name' : obj.first_name})
form = Subject_EnrollForm(request.POST or None, request.FILES or None)
form.fields["student_name"].initial = first_name
form.fields["birth_place"].initial = obj.birth_place
form.fields["gender"].initial = obj.gender
form.fields["phone"].initial = obj.phone
form.fields["email"].initial = obj.email
form.fields["phone"].initial = obj.phone
form.fields["nationality"].initial = obj.nationality
form.fields["religion"].initial = obj.religion
form.fields["blood_group"].initial = obj.blood_group
form.fields["nationality"].initial = obj.nationality
form.fields["nationality"].initial = obj.nationality
form.fields["nationality"].initial = obj.nationality
form.fields["nationality"].initial = obj.nationality
else:
print "object not found"
Subject_EnrollForm(request.POST or None, request.FILES or None)
if request.POST:
if form.is_valid():
a = form.save()
a.user = request.user
a.save()
#user.save()
messages.add_message(request,messages.SUCCESS, "your Profile was added")
#return HttpResponseRedirect('/app/all')
return HttpResponseRedirect('/')
args = {}
args.update(csrf(request))
args['form'] = form
context = RequestContext(request,
{'request': request,
'user': request.user,
'form': form})
return render_to_response('subject_enroll/add_subject_enroll.html', args, context)
class Subject_EnrollListView(ListView):
"""View to display all published and visible news entries."""
template_name = "subject_enroll/subject_enroll_list.html"
def get_queryset(self):
return Subject_Enroll.objects.all()
class DetailViewMixin(object):
"""Mixin to handle different DetailView variations."""
model = Subject_Enroll
#slug_field = 'translations__slug'
def get_queryset(self):
#return Subject_Enroll.objects.all()
return Subject_Enroll.objects.lang(self.request, False)
class Subject_EnrollDetailView(DetailViewMixin, DetailView):
def get_context_data(self, **kwargs):
context = super(Subject_EnrollDetailView, self).get_context_data(**kwargs)
context['subject_enrolls'] = Subject_Enroll.objects.all()
return context
class Subject_EnrollUpdateView(UpdateView):
form_class = Subject_EnrollForm
model = Subject_Enroll
template_name = 'subject_enroll/subject_enroll_detail.html'
def get(self, request, **kwargs):
self.object = Subject_Enroll.objects.get(id=self.request.id)
form_class = self.get_form_class()
form = self.get_form(form_class)
context = self.get_context_data(object=self.object, form=form)
return self.render_to_response(context)
def get_object(self, queryset=None):
obj = Subject_Enroll.objects.get(id=self.kwargs['id'])
return obj
i try with pass form in context of Detilviewmixin
class DetailViewMixin(object):
"""Mixin to handle different DetailView variations."""
model = Subject_Enroll
#slug_field = 'translations__slug'
def get_context_data(self, **kwargs):
context = super(DetailViewMixin, self).get_context_data(**kwargs)
#context['form'] = Subject_EnrollForm
#context['form'] = Subject_EnrollForm()
return context
def get_queryset(self):
#return Subject_Enroll.objects.all()
return Subject_Enroll.objects.lang(self.request, False)
in that form are render on template but when i press save button so it can't save record
from this code i get all field access in "subject_enroll/subject_enroll_detail.html" like {{ object.student_name }}
{{ object.enroll_status }}
so it gives value of that field but now i want to edit record in subject_enroll_detail.html template like s
subject_enroll values "draft" to "submit" with click on some buttons in subject_enroll_detail.html template
i tried with form view and updateview but can't find solution
pls help!!!
Thanks in advance!!
from django.views.generic import UpdateView
class StudentRegistrationUpdateView(UpdateView):
model = StudentRegistration
form_class = Subject_EnrollForm #don't need if you are editing all the fields
template_name = 'subject_enroll/add_subject_enroll.html'
https://docs.djangoproject.com/en/1.7/ref/class-based-views/generic-editing/#updateview
in your urls.py
import StudentRegistrationUpdateView
in urls.py don't forget to include 'pk' like below, this determines which object to be updated
url(r'student/(?P<pk>\d+)/update/$', StudentRegistrationUpdateView.as_view(), name='student_registration_update'),
Ok, so I'm fairly new to Django, but have been reading both the online django book and the djangoproject documentation, but I can't seem to figure this error out:
I've got an 'Orders' model:
class Orders(models.Model):
client_id = models.ForeignKey(Client)
order_date = models.DateField(auto_now_add = True)
due_date = models.DateField()
completion_date = models.DateField(blank=True, null=True)
rush_order = models.BooleanField(default=False)
billing_option = models.ForeignKey(Billing)
patient_first_name = models.CharField(max_length=30)
patient_middle_name = models.CharField(max_length=30, blank=True)
patient_last_name = models.CharField(max_length=30)
client_patient_id = models.CharField(max_length=30, blank=True)
emodel_patient_id = models.CharField(max_length=30)
special_instructions = models.TextField(blank=True)
order_items = models.ManyToManyField(Order_Items)
def __unicode__(self):
return '%s : %s %s O: %s F: %s' % (self.client_id, self.patient_first_name, self.patient_last_name, self.order_date, self.completion_date)
class Meta:
ordering = ['client_id']
I've got a 'SearchOrderForm' modelform:
class SearchOrderForm(ModelForm):
class Meta:
model = Orders
exclude = ('rush_order', 'billing_option', 'client_patient_id', 'special_instructions', 'order_items',)
and I've got an 'order_status' function:
def order_status(request):
error = False
error_searching = False
if request.method == 'POST':
OrderFormSet = SearchOrderForm()
formset = OrderFormSet()
if formset.is_valid():
cd = formset.cleaned_data()
emodels_results = cd()
emodels_results = cd(queryset = Order.objects.filter(Q(patient_first_name=search)|Q(patient_last_name=search)|Q(client_id=search)))
patient_first_name = request.POST('patient_first_name', None)
if patient_first_name:
emodels_results = emodels_results(queryset = Order.objects.filter(patient_first_name=patient_first_name))
patient_last_name = request.POST('patient_last_name', None)
if patient_last_name:
emodels_results = emodels_results(queryset = Order.objects.filter(patient_last_name=patient_last_name))
client_id = request.POST('client_id', None)
if client_id:
emodels_results = emodels_results(queryset = Order.objects.filter(client_id=client_id))
return render_to_response('search_results.html', {'models': emodels_results})
else:
emodels_results = "Still messed up!"
return render_to_response('search_results.html', {'models': emodels_results})
else:
error_searching = True
form = SearchOrderForm()
return render_to_response('order_status.html', {'form': form, 'error': error, 'error_searching': error_searching})
I can fill out my form with no problems, but when I submit the form I get back the following error message:
Traceback:
File "C:\Python26\lib\site-packages\django\core\handlers\base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "C:\emodel_tracking..\emodel_tracking\tracker\views.py" in order_status
105. formset = OrderFormSet()
Exception Type: TypeError at /accounts/profile/orderstatus/
Exception Value: 'SearchOrderForm' object is not callable
Does anyone know what I'm doing wrong with my SearchOrderForm that's causing Django to say that it is not callable?
I think you want either of these:
OrderFormSet = SearchOrderForm()
if OrderFormSet.is_valid():
formset = SearchOrderForm()
if formset.is_valid()
With the second way being the preferred syntax style. As a matter of nitpicking, Django offers a FormSet type which is different than the Form type so it is convention to refer to instances of Forms as "form":
form = SearchOrderForm()
if form.is_valid():
You are going to have some other problems with your code:
def order_status(request):
error = False
error_searching = False
if request.method == 'POST':
#instead of:
#OrderFormSet = SearchOrderForm()
#formset = OrderFormSet()
#instantiate an instance of your ModelForm
#(I'd normally name it "form")
formset = SearchOrderForm()
if formset.is_valid():
cd = formset.cleaned_data()
#cd is now a Python dictionary
#these next 2 lines don't make sense, what is your intention?
emodels_results = cd()
emodels_results = cd(queryset = Order.objects.filter(Q(patient_first_name=search)|Q(patient_last_name=search)|Q(client_id=search)))
#you've already used your form to process and clean
#the incoming POST data. use the cleaned data instead
#patient_first_name = request.POST('patient_first_name', None)
patient_first_name = cd.get('patient_first_name','')
#use data from the form's cleaned_data as in the line above
#I'm not sure what your intention is with how the emodels_results
#is but you'll need to rework that for it all to work
if patient_first_name:
emodels_results = emodels_results(queryset = Order.objects.filter(patient_first_name=patient_first_name))
patient_last_name = request.POST('patient_last_name', None)
if patient_last_name:
emodels_results = emodels_results(queryset = Order.objects.filter(patient_last_name=patient_last_name))
client_id = request.POST('client_id', None)
if client_id:
emodels_results = emodels_results(queryset = Order.objects.filter(client_id=client_id))
return render_to_response('search_results.html', {'models': emodels_results})
else:
emodels_results = "Still messed up!"
return render_to_response('search_results.html', {'models': emodels_results})
else:
error_searching = True
form = SearchOrderForm()
return render_to_response('order_status.html', {'form': form, 'error': error, 'error_searching': error_searching})