def main(self, request, form_class=None, template_name=None, extra_context={}): """ Main Function of view """ if not self.is_available(): return HttpResponseRedirect(reverse(self.error_redirect)) form_class = self.get_form(form_class) params = {} facets = [] sort_links = [] paginator = None if request.GET: form = form_class(request.GET) if form.is_valid(): # Get all the get params params.update(dict(request.GET.items())) # Overwrite those with anything you might of changed in the form. params.update(form.cleaned_data) paginator = SearchPaginator(params, request) facets = utils.get_facets_links(request, paginator.results) sort_links = utils.get_sort_links(request) else: form = form_class() # Get Context context = self.get_context(request, paginator, facets, sort_links, form) apply_extra_context(extra_context, context) template = self.get_template(request, template_name) #Render Template rendered_template = template.render(context) return HttpResponse(rendered_template)
def show_cart(request, template_name, extra_context=None): """Lists cart's items""" context = {'cart': Cart(request),} apply_extra_context(extra_context or {}, context) return direct_to_template(request, template=template_name, extra_context=context)
def share_document(request, object_id, template="share_form.html", form_class = ShareForm, extra_context=None): """Share document by id when with other people""" document = get_object_or_404(Document, id=object_id, user=request.user) form = form_class(request.POST or None, request.FILES or None) if form.is_valid(): send_message(form.cleaned_data["email"], "email/share.html","email/share_subject.txt", sender=request.user, extra_context={"document": document, "message": form.cleaned_data["message"]}) return TemplateResponse(request, template, {"success": True,}) context = { "form": form, "document": document } apply_extra_context(extra_context or {}, context) return TemplateResponse(request, template, context)
def create_object(request, model=None, template_name=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, form_class=None, current_user=False, pre_save_signal=None, post_save_signal=None, signal_kwarg_name='object'): ''' Generic create_object view with extra functionality: current_user update __init__ of the form class to use current user as initial pre_save_signal signal to send before save post_save signal signal to send after save ''' if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) model, form_class = create_update.get_model_and_form_class(model, form_class) if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): new_object = form.save(commit=False) if current_user: new_object.user = request.user signal_kwargs = { 'sender': new_object.__class__, signal_kwarg_name: new_object, 'request': request } # Signal that the object is about to be saved if pre_save_signal: pre_save_signal.send(**signal_kwargs) new_object.save() form.save_m2m() # Signal that object was saved if post_save_signal: post_save_signal.send(**signal_kwargs) msg = ugettext("The %(verbose_name)s was created successfully.") %\ {"verbose_name": model._meta.verbose_name} messages.success(request, msg, fail_silently=True) return create_update.redirect(post_save_redirect, new_object) else: form = form_class() # Create the template, context, response if not template_name: template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { 'form': form, }, context_processors) create_update.apply_extra_context(extra_context, c) return HttpResponse(t.render(c))
def create_message(request, model=None, template_name=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, form_class=None): if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) model, form_class = create_update.get_model_and_form_class( model, form_class) if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): new_object = form.save() msg = ugettext("The %(verbose_name)s was created successfully.") %\ {"verbose_name": model._meta.verbose_name} messages.success(request, msg, fail_silently=True) new_object.sender = request.user new_object.save() if new_object.type == DatedMessage.TYPE_U2U: try: send_mail( settings.EMAIL_SUBJECT_PREFIX + "User %s has sent you a message" % (new_object.sender), "Original Message:\n\"%s\"\n\n\nYou can check the new message at https://%s/messagecenter/\n\n" % (new_object.msg_text, settings.SITE_DOMAIN), from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=User.objects.filter( id__in=request.POST.getlist('users')).values_list( 'email', flat=True), #recipient_list=[settings.ROOT_EMAIL], ) except Exception as e: print "User email notification could no be sent" return create_update.redirect(post_save_redirect, new_object) else: form = form_class() # Create the template, context, response if not template_name: template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { 'form': form, }, context_processors) create_update.apply_extra_context(extra_context, c) return HttpResponse(t.render(c))
def _update_object(request, model=None, object_id=None, slug=None, slug_field='slug', template_name=None, template_loader=template_loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, template_object_name='object', form_class=None, msg=None, summary_template_name=None): """ Based of django.views.generic.create_update.update_object which displays a summary page before updating the object. """ if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) model, form_class = get_model_and_form_class(model, form_class) obj = lookup_object(model, object_id, slug, slug_field) if request.method == 'POST': form = form_class(request.POST, request.FILES, instance=obj) if form.is_valid(): verify = request.GET.get('verify') edit = request.GET.get('edit') if verify == '1': extra_context['show_form'] = False extra_context['form_data'] = form.cleaned_data template_name = summary_template_name elif edit == '1': extra_context['show_form'] = True else: obj = form.save() if not msg: msg = _( "The %(verbose_name)s was created successfully.") msg = msg % model._meta.__dict__ messages.success(request, msg, fail_silently=True) return redirect(post_save_redirect, obj) else: form = form_class(instance=obj) if not template_name: template_name = "%s/%s_form.html" % \ (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { 'form': form, template_object_name: obj, }, context_processors) apply_extra_context(extra_context, c) response = HttpResponse(t.render(c)) populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.attname)) return response
def create_object(request, spam_check_scope_attr, author_name_attr, model=None, template_name=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, form_class=None, initial=None, initial_with_get=False): """ Generic object-creation function. Templates: ``<app_label>/<model_name>_form.html`` Context: form the form for the object """ if not initial and initial_with_get: initial = request.GET.items() elif initial_with_get: initial.update(request.GET.items()) if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) model, form_class = get_model_and_form_class(model, form_class) if request.method == 'POST': if issubclass(form_class, ModelFormWithRequest): form = form_class(request, request.POST, request.FILES) else: form = form_class(request.POST, request.FILES) if form.is_valid(): # checking spam new_object = form.save(commit=False) body = getattr(new_object, spam_check_scope_attr, None) author = getattr(new_object, author_name_attr, None) if _is_spam(model, new_object, body, author, request): msg = ugettext("The %(verbose_name)s was created unsuccessfully.") %\ {"verbose_name": model._meta.verbose_name} messages.error(request, msg, fail_silently=True) else: new_object = form.save(commit=True) msg = ugettext("The %(verbose_name)s was created successfully.") %\ {"verbose_name": model._meta.verbose_name} messages.success(request, msg, fail_silently=True) return redirect(post_save_redirect, new_object) else: if issubclass(form_class, ModelFormWithRequest): form = form_class(request, initial=initial) else: form = form_class(initial=initial) # Create the template, context, response if not template_name: template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { 'form': form, }, context_processors) apply_extra_context(extra_context, c) return HttpResponse(t.render(c))
def _create_object(request, model=None, template_name=None, template_loader=template_loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, form_class=None, msg=None, summary_template_name=None): """ Based of django.views.generic.create_update.create_object which displays a summary page before creating the object. """ if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) model, form_class = get_model_and_form_class(model, form_class) extra_context['edit'] = 0 if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): verify = request.GET.get('verify') edit = request.GET.get('edit') if verify == '1': extra_context['show_form'] = False extra_context['form_data'] = form.cleaned_data template_name = summary_template_name elif edit == '1': extra_context['show_form'] = True else: new_object = form.save() if not msg: msg = _("The %(verbose_name)s was created successfully.") msg = msg % model._meta.__dict__ messages.success(request, msg, fail_silently=True) return redirect(post_save_redirect, new_object) else: form = form_class() # Create the template, context, response if not template_name: template_name = "%s/%s_form.html" % \ (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, {'form': form}, context_processors) apply_extra_context(extra_context, c) return HttpResponse(t.render(c))
def waybill_errors(request, waybill_pk, logger_action, queryset=ets.models.Waybill.objects.all(), template="waybill/error-list.html", extra_context=None): """utility that shows waybill's errors""" waybill = get_object_or_404(queryset, pk=waybill_pk) context = { 'object': waybill, 'logger_action': int(logger_action), } apply_extra_context(extra_context or {}, context) return direct_to_template(request, template, context)
def dashboard(request, template="notification/dashboard.html", extra_context=None): my_feeds = EmailFeed.objects.filter(subscriber_id=request.user.id) def feed_generator(feeds): for feed in feeds: summary = feed.get_update_summary() if summary: yield {'question': feed.content, 'summary': summary} context={'updates': feed_generator(my_feeds)} apply_extra_context(extra_context or {}, context) return notices(request, template, context)
def waybill_detail(request, waybill, template="waybill/detail.html", extra_context=None): """utility that shows waybill's details""" waybill_log = LogEntry.objects.filter(content_type__id=ContentType.objects.get_for_model(ets.models.Waybill).pk, object_id=waybill.pk) context = { 'object': waybill, 'items': waybill.loading_details.select_related(), 'waybill_history': waybill_log, } apply_extra_context(extra_context or {}, context) return direct_to_template(request, template, context)
def waybill_search( request, template='waybill/list2.html', form_class=WaybillSearchForm, extra_context=None): """Waybill search view. Simply a wrapper on waybill_list""" form = form_class(request.GET or None) search_string = form.cleaned_data['q'] if form.is_valid() else '' context = { "search_string": search_string, "ajax_source_url": reverse("table_waybills", kwargs={ 'filtering': 'user_related'}), } apply_extra_context(extra_context or {}, context) return direct_to_template(request, template, context)
def view_document(request, object_id, template="document_view.html", extra_context=None): """View document object by id: preview or download""" document = get_object_or_404(Document, id=object_id) context = { "d": document } apply_extra_context(extra_context or {}, context) return TemplateResponse(request, template, context)
def update_object(request, model=None, object_id=None, slug=None, slug_field='slug', template_name=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, template_object_name='object', form_class=None, initial=None): """ Generic object-update function. Templates: ``<app_label>/<model_name>_form.html`` Context: form the form for the object object the original object being edited """ if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) model, form_class = get_model_and_form_class(model, form_class) obj = lookup_object(model, object_id, slug, slug_field) if request.method == 'POST': if issubclass(form_class, ModelFormWithRequest): form = form_class(request, request.POST, request.FILES, instance=obj) else: form = form_class(request.POST, request.FILES, instance=obj) if form.is_valid(): obj = form.save() msg = ugettext("The %(verbose_name)s was updated successfully.") %\ {"verbose_name": model._meta.verbose_name} messages.success(request, msg, fail_silently=True) return redirect(post_save_redirect, obj) else: if issubclass(form_class, ModelFormWithRequest): form = form_class(request, instance=obj, initial=initial) else: form = form_class(instance=obj, initial=initial) if not template_name: template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { 'form': form, template_object_name: obj, }, context_processors) apply_extra_context(extra_context, c) response = HttpResponse(t.render(c)) populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.attname)) return response
def auth_success(request, template="publicauth/popup.html", extra_context=None): """View required for authentication processing. When user comes first time we need filling extra form and redirecting to LOGIN_REDIRECT_URL otherwise we have popup which should close itself. """ if request.session.has_key("extra"): # Filling extra form finished. Need redirect. return redirect(getattr(settings, "LOGIN_REDIRECT_URL", "/")) context = {} apply_extra_context(extra_context or {}, context) return TemplateResponse(request, template, context)
def main(self, request, form_class=None, template_name=None, extra_context={}): """ Main Function of view """ if not self.is_available(): return HttpResponseRedirect(reverse(self.error_redirect)) form_class = self.get_form(form_class) params = {} facets = [] sort_links = [] facet_dates = [] paginator = None if request.GET: form = form_class(request.GET) if form.is_valid(): # Get all the get params get_args = dict(request.GET.items()) # Add wildcards to q words = request.GET.get('q', '').split() words_wild = [] for word in words: words_wild.append(word.strip() + '* ') if words_wild: get_args['q'] = ' '.join(words_wild) params.update(get_args) # Overwrite those with anything you might of changed in the form. params.update(form.cleaned_data) paginator = SearchPaginator(params, request) facets = utils.get_facets_links(request, paginator.results) sort_links = utils.get_sort_links(request) else: form = form_class() # Get Context context = self.get_context(request, paginator, facets, sort_links, form) apply_extra_context(extra_context, context) template = self.get_template(request, template_name) #Render Template rendered_template = template.render(context) return HttpResponse(rendered_template)
def main(self, request, form_class=None, template=None, extra_context={}): """ Main Function of view """ form_class = self.get_form(form_class) params = [] facets = [] sort_links = [] facet_dates = [] paginator = None if request.GET: form = form_class(request.GET) if form.is_valid(): # Get all the get params params = deepcopy(request.GET) page = int(params.pop("page", [1])[0]) per_page = int(params.pop("per_page", [25])[0]) params.update(form.cleaned_data) query = self.index.query(params.items()) query.start = (page - 1) * per_page query.rows = per_page results = self.select(query) paginator = SearchPaginator(results, request, page, per_page) facets = utils.get_facets_links(request, paginator.results) sort_links = utils.get_sort_links(request) else: form = form_class() # Get Context context = self.get_context(request, paginator, facets, sort_links, form) apply_extra_context(extra_context, context) template = self.get_template(request, template) # Render Template rendered_template = template.render(context) return HttpResponse(rendered_template)
def create_message(request, model=None, template_name=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, form_class=None): if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) model, form_class = create_update.get_model_and_form_class(model, form_class) if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): new_object = form.save() msg = ugettext("The %(verbose_name)s was created successfully.") %\ {"verbose_name": model._meta.verbose_name} messages.success(request, msg, fail_silently=True) new_object.sender = request.user new_object.save() if new_object.type == DatedMessage.TYPE_U2U: try: send_mail( settings.EMAIL_SUBJECT_PREFIX + "User %s has sent you a message" % (new_object.sender), "Original Message:\n\"%s\"\n\n\nYou can check the new message at https://%s/messagecenter/\n\n" % (new_object.msg_text, settings.SITE_DOMAIN), from_email=settings.DEFAULT_FROM_EMAIL, recipient_list= User.objects.filter(id__in = request.POST.getlist('users')).values_list('email', flat=True), #recipient_list=[settings.ROOT_EMAIL], ) except Exception as e: print "[WARNING] User e-mail notification could not be sent. Details: %s" % str(e) return create_update.redirect(post_save_redirect, new_object) else: form = form_class() # Create the template, context, response if not template_name: template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { 'form': form, }, context_processors) create_update.apply_extra_context(extra_context, c) return HttpResponse(t.render(c))
def delete_object(request, model, post_delete_redirect, object_id=None, slug=None, slug_field='slug', template_name=None, template_loader=loader, extra_context=None, login_required=False, context_processors=None, template_object_name='object'): """ Generic object-delete function. The given template will be used to confirm deletetion if this view is fetched using GET; for safty, deletion will only be performed if this view is POSTed. Templates: ``<app_label>/<model_name>_confirm_delete.html`` Context: object the original object being deleted """ if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) obj = lookup_object(model, object_id, slug, slug_field) if request.method == 'POST': obj.delete() if request.user.is_authenticated(): request.user.message_set.create(message=ugettext("The %(verbose_name)s was deleted.") % {"verbose_name": model._meta.verbose_name}) return HttpResponseRedirect(post_delete_redirect) else: if not template_name: template_name = "%s/%s_confirm_delete.html" % (model._meta.app_label, model._meta.object_name.lower()) if hasattr(request, 'device'): d = getattr(request, 'device', {}) t = template_loader.get_template(template_name, d) else: t = template_loader.get_template(template_name) c = RequestContext(request, { template_object_name: obj, }, context_processors) apply_extra_context(extra_context, c) response = HttpResponse(t.render(c)) populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.attname)) return response
def waybill_list(request, queryset, template='waybill/list2.html', extra_context=None): """Shows waybill listing""" context = {'object_list': queryset.values( 'order', 'order__pk', 'pk', 'order__warehouse__location__name', 'order__warehouse__name', 'order__consignee__name', 'order__location__name', 'transport_dispach_signed_date', 'receipt_signed_date', 'validated', 'receipt_validated', 'sent_compas', 'receipt_sent_compas', 'destination__name', 'transaction_type' ),} apply_extra_context(extra_context or {}, context) return direct_to_template(request, template, context)
def main(self, request, form_class=None, template_name=None, extra_context={}): """ Main Function of view """ if not self.is_available(): return HttpResponseRedirect(reverse(self.error_redirect)) form_class = self.get_form(form_class) params = {} facets = [] sort_links = [] facet_dates = [] paginator = None form = form_class(request.GET) # Get all the get params # Overwrite those with anything you might of changed in the form. params.update(dict(request.GET.items())) q = request.GET.get("q") if q: params.pop("q") params["q"] = "text:%s^10 OR text:%s~" % (q, q) params["state"] = '"P"' else: params["q"] = 'state:"P"' params.update(dict(per_page=40)) params.pop("x", None) params.pop("y", None) paginator = SearchPaginator(params, request) facets = utils.get_facets_links(request, paginator.results) sort_links = utils.get_sort_links(request) # Get Context context = self.get_context(request, paginator, facets, sort_links, form) apply_extra_context(extra_context, context) template = self.get_template(request, template_name) # Render Template rendered_template = template.render(context) return HttpResponse(rendered_template)
def create_object(request, model=None, template_name=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, form_class=None): """ Generic object-creation function. Templates: ``<app_label>/<model_name>_form.html`` Context: form the form for the object """ if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) model, form_class = get_model_and_form_class(model, form_class) if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): new_object = form.save() if request.user.is_authenticated(): request.user.message_set.create(message=ugettext("The %(verbose_name)s was created successfully.") % {"verbose_name": model._meta.verbose_name}) return redirect(post_save_redirect, new_object) else: form = form_class() # Create the template, context, response if not template_name: template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower()) if hasattr(request, 'device'): d = getattr(request, 'device', {}) t = template_loader.get_template(template_name, d) else: t = template_loader.get_template(template_name) c = RequestContext(request, { 'form': form, }, context_processors) apply_extra_context(extra_context, c) return HttpResponse(t.render(c))
def create(request, template_name, form_class = RepositoryForm, post_save_redirect = None, extra_context = {}, template_loader = loader, context_processors = None, ): if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): new_object = form.save() return redirect(post_save_redirect, new_object) else: form = form_class() t = template_loader.get_template(template_name) c = RequestContext(request, { 'form': form, }, context_processors) apply_extra_context(extra_context, c) return HttpResponse(t.render(c))
def create( request, template_name, form_class=RepositoryForm, post_save_redirect=None, extra_context={}, template_loader=loader, context_processors=None, ): if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): new_object = form.save() return redirect(post_save_redirect, new_object) else: form = form_class() t = template_loader.get_template(template_name) c = RequestContext(request, { 'form': form, }, context_processors) apply_extra_context(extra_context, c) return HttpResponse(t.render(c))
def invitation_request(request, form_class=InvitationRequestForm, template_name="join_request.html", extra_context=None): if request.user.is_authenticated() \ and request.muaccount.members.filter(username=request.user.username).count(): return redirect('/') request_obj, form = None, None def _get_request_obj(muaccount, email): try: return InvitationRequest.objects.get(muaccount=muaccount, email=email) except InvitationRequest.DoesNotExist: pass if request.user.is_authenticated(): request_obj = _get_request_obj(request.muaccount, request.user.email) if request_obj is None: if request.method == "POST": form = form_class(request.POST) if form.is_valid(): request_obj = form.save() form = None if request.POST.get('email'): request_obj = _get_request_obj(request.muaccount, request.POST['email']) else: initial={'muaccount': request.muaccount.id} if request.user.is_authenticated(): initial['email'] = request.user.email form = form_class(initial=initial) context = {'form': form, 'join_request': request_obj} apply_extra_context(extra_context or {}, context) return render_to_response(template_name, context, context_instance=RequestContext(request))
def object_detail(request, cls, query = {}, extra_context = {}, template_name = None, template_name_field = None, template_object_name = 'object', template_loader = loader, context_processors = None, **kwargs ): if callable(extra_context): extra_context = extra_context(request, **kwargs) if callable(query): query = query(request, **kwargs) object = cls.objects.find_one(query) if object is None: raise Http404, 'Object was not found in collection "%s"' % cls.collection.name() if not template_name: template_name = "%s_detail.html" % cls.objects.collection_name if template_name_field: template_name_list = [getattr(obj, template_name_field), template_name] t = template_loader.select_template(template_name_list) else: t = template_loader.get_template(template_name) c = RequestContext(request, { template_object_name: object, }, context_processors) apply_extra_context(extra_context, c) return HttpResponse(t.render(c))
def object_detail(request, cls, query={}, extra_context={}, template_name=None, template_name_field=None, template_object_name='object', template_loader=loader, context_processors=None, **kwargs): if callable(extra_context): extra_context = extra_context(request, **kwargs) if callable(query): query = query(request, **kwargs) object = cls.objects.find_one(query) if object is None: raise Http404, 'Object was not found in collection "%s"' % cls.collection.name( ) if not template_name: template_name = "%s_detail.html" % cls.objects.collection_name if template_name_field: template_name_list = [getattr(obj, template_name_field), template_name] t = template_loader.select_template(template_name_list) else: t = template_loader.get_template(template_name) c = RequestContext(request, { template_object_name: object, }, context_processors) apply_extra_context(extra_context, c) return HttpResponse(t.render(c))
def create_object(request, model=None, template_name=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, form_class=None, inlines=None, initial={}, preprocess_form=lambda _:_): """ Generic object-creation function with inlines capability. Templates: ``<app_label>/<model_name>_form.html`` Context: form the form for the object xxx_formset ModelFormSet for model classes in ``inlines`` argument. """ if extra_context is None: extra_context = {} if inlines is None: inlines = () if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) formset_classes = [] formsets = [] tmodel, form_class = get_model_and_form_class(model, form_class) if True or issubclass(form_class, BaseForm): class InitialModelForm(form_class): class Meta: model = tmodel def __init__(self, *args, **kwargs): request_initial = dict(request.GET.items()) request_initial.update(initial) kwargs['initial'] = request_initial#{'field1': request.GET.get('field1','')} return super(InitialModelForm, self).__init__(*args, **kwargs) form_class = InitialModelForm model = tmodel for inline in inlines: formset_classes.append(inlineformset_factory(model, **inline)) if request.method == 'POST': form = form_class(request.POST, request.FILES) preprocess_form(form) if form.is_valid(): form_validated = True new_object = form.save() else: form_validated = False new_object = model() for klass in formset_classes: formset = klass(request.POST, request.FILES, instance=new_object) formsets.append(formset) if all_valid(formsets) and form_validated: new_object.save() for formset in formsets: formset.save() if request.user.is_authenticated(): request.user.message_set.create(message=ugettext("The " "%(verbose_name)s was created successfully.") % {"verbose_name": model._meta.verbose_name}) return redirect(post_save_redirect, new_object) else: form = form_class() preprocess_form(form) for klass in formset_classes: formset = klass() formsets.append(formset) if not template_name: template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower()) template = template_loader.get_template(template_name) context = RequestContext(request, { 'form': form, }, context_processors) apply_extra_context(extra_context, context) for formset in formsets: key = '%s_formset' % formset.model._meta.object_name.lower() context[key] = formset return http.HttpResponse(template.render(context))
messages.success(request, msg, fail_silently=True) response = redirect(post_save_redirect, new_object) else: form = form_class() except (IOError, PermissionDenied), e: messages.error(request, e) return None else: if response == None: # Create the template, context, response if not template_name: template_name = "%s/%s_form.html" %\ (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, {'form': form}, context_processors) apply_extra_context(extra_context, c) response = HttpResponse(t.render(c)) return response @commit_on_success_strict() def _update_object(request, model=None, object_id=None, slug=None, slug_field='slug', template_name=None, template_loader=template_loader, extra_context=None, post_save_redirect=None, login_required=False,
def index(request, template="index.html", queryset = Document.objects.all(), form_class = DocumentForm, extra_context=None): """Home page. Show list of user's files and process file upload.""" form = form_class(request.POST or None, request.FILES or None) document = None if request.user.is_authenticated(): # Show documents for owner. Anonymous users cant use system. documents = queryset.filter(user=request.user) if form.is_valid(): document = form.save(commit=False) document.user = request.user document.save() form = form_class() else: documents = queryset.none() context = { "documents": documents, "form": form, "d": document, } apply_extra_context(extra_context or {}, context) if request.POST: context["visible"] = True response = { "form":render_to_string("upload_form.html", context_instance=RequestContext( request, context) ) } if document is not None: response["document"] = render_to_string("document.html", context_instance=RequestContext( request, context) ) return HttpResponse('<textarea>%s</textarea>' % simplejson.dumps( response)) if request.is_ajax(): # For ajax request we need to send only parts of page. response = { "account": render_to_string("ajax/account_info.html", context_instance=RequestContext( request, context) ), "content": render_to_string("ajax/index_content.html", context_instance=RequestContext( request, context) ), } return HttpResponse(simplejson.dumps(response), content_type="application/json; charset=utf-8") return TemplateResponse(request, template, context)
def create_object_detail(request, queryset, current_user=True, object_id=None, slug=None, slug_field='slug', create_model=None, template_name=None, template_name_field=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, template_object_name='object', mimetype=None, form_class=None): """ Generic detail of an object with create form for other model. Templates: ``<app_label>/<model_name>_detail_<create_model_name>_form.html`` Context: object the object """ if extra_context is None: extra_context = {} if (login_required or current_user) and not request.user.is_authenticated(): return redirect_to_login(request.path) create_model, form_class = get_model_and_form_class(create_model, form_class) if current_user: form_class = get_current_user_form_class(form_class, request.user.id) # create_object part if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): new_object = form.save() msg = ugettext("The %(verbose_name)s was created successfully.") %\ {"verbose_name": create_model._meta.verbose_name} messages.success(request, msg, fail_silently=True) return redirect(post_save_redirect, new_object) else: form = form_class() # object_detail part model = queryset.model if object_id: queryset = queryset.filter(pk=object_id) elif slug and slug_field: queryset = queryset.filter(**{slug_field: slug}) else: raise AttributeError("Generic detail view must be called with either an object_id or a slug/slug_field.") try: obj = queryset.get() except ObjectDoesNotExist: raise Http404("No %s found matching the query" % (model._meta.verbose_name)) # Create the template, context, response if not template_name: template_name = "%s/%s_detail_%s_form.html" % (model._meta.app_label, model._meta.object_name.lower(), create_model._meta.object_name.lower()) if template_name_field: template_name_list = [getattr(obj, template_name_field), template_name] t = template_loader.select_template(template_name_list) else: t = template_loader.get_template(template_name) c = RequestContext(request, { template_object_name: obj, 'form': form, }, context_processors) apply_extra_context(extra_context, c) response = HttpResponse(t.render(c), mimetype=mimetype) populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.name)) return response
def update_object(request, model=None, object_id=None, slug=None, slug_field='slug', template_name=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, template_object_name='object', form_class=None, inlines=None): """ Generic object-update function with inlines. Templates: ``<app_label>/<model_name>_form.html`` Context: form the form for the object object the original object being edited xxx_formset ModelFormSet for model classes in ``inlines`` argument. """ if extra_context is None: extra_context = {} if inlines is None: inlines = () if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) formset_classes = [] formsets = [] model, form_class = get_model_and_form_class(model, form_class) obj = lookup_object(model, object_id, slug, slug_field) for inline in inlines: formset_classes.append(inlineformset_factory(model, **inline)) if request.method == 'POST': form = form_class(request.POST, request.FILES, instance=obj) if form.is_valid(): form_validated = True new_object = form.save() else: form_validated = False new_object = obj for klass in formset_classes: formset = klass(request.POST, request.FILES, instance=new_object) formsets.append(formset) if all_valid(formsets) and form_validated: new_object.save() for formset in formsets: formset.save() if request.user.is_authenticated(): request.user.message_set.create(message=ugettext("The " "%(verbose_name)s was updated successfully.") % {"verbose_name": model._meta.verbose_name}) return redirect(post_save_redirect, new_object) else: form = form_class(instance=obj) for klass in formset_classes: formset = klass(instance=obj) formsets.append(formset) if not template_name: template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower()) template = template_loader.get_template(template_name) context = RequestContext(request, { 'form': form, template_object_name: obj, }, context_processors) apply_extra_context(extra_context, context) for formset in formsets: key = '%s_formset' % formset.model._meta.object_name.lower() context[key] = formset response = http.HttpResponse(template.render(context)) populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.name)) return response
def create_update_object(request, model=None, object_id=None,template_name=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, form_class=None , formset_class=None, initial_form={}, initial_formset={}): """ Custom generic object-creation function. Templates: ``<app_label>/<model_name>_form.html`` Context: form the form for the object """ # TODO: Better this generic create_object if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated(): return redirect_to_login(request.path) model, form_class = get_model_and_form_class(model, form_class) formset = formset_class try: instance=model.objects.get(id=object_id) except: instance=False if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid() and not formset_class: if instance: form=form_class(request.POST, request.FILES, instance=instance) new_object = form.save() msg = ugettext("The %(verbose_name)s was created successfully.") %\ {"verbose_name": model._meta.verbose_name} messages.success(request, msg, fail_silently=True) return redirect(post_save_redirect, new_object) else: formset = formset_class(request.POST, request.FILES) if instance: form = form_class(request.POST,request.FILES, instance=instance) if formset.is_valid() and form.is_valid(): new_object=form.save() form_opts=new_object._meta obj=formset.save(commit=False) if hasattr(form_opts,'module_name') and hasattr(obj,form_opts.module_name+'_fk_id'): setattr(obj,form_opts.module_name+'_fk',new_object) else: raise Exception('Error the model %s must has a ForeignKey named %s_fk' % (obj._meta.module_name, form_opts.module_name) ) msg = ugettext("The %s was created successfully.") % model._meta.verbose_name messages.success(request, msg, fail_silently=True) formset.save() return redirect(post_save_redirect, new_object) else: form = form_class(**initial_form) if formset_class: formset = formset_class(**initial_formset) # Create the template, context, response if not template_name: template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { 'form': form, 'formset':formset }, context_processors) apply_extra_context(extra_context, c) return HttpResponse(t.render(c))
else: form = form_class() except (IOError, PermissionDenied), e: messages.error(request, e) return None else: if response == None: # Create the template, context, response if not template_name: template_name = "%s/%s_form.html" %\ (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) c = RequestContext(request, { 'form': form }, context_processors) apply_extra_context(extra_context, c) response = HttpResponse(t.render(c)) return response @commit_on_success_strict() def _update_object(request, model=None, object_id=None, slug=None, slug_field='slug', template_name=None, template_loader=template_loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, template_object_name='object', form_class=None, msg=None, summary_template_name=None): """ Based of django.views.generic.create_update.update_object which displays a summary page before updating the object. """ response = None