Пример #1
0
def task_create(
    request,
    model=None,
    template_name=None,
    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 = get_model_and_form_class(model, form_class)
    if request.method == "POST":
        p = Project.objects.get_or_create_by_owner_and_title(request.user, request.POST.get("project_title_inbox"))
        form = form_class(request.POST, request.FILES)
        if form.is_valid():
            new_object = form.save(commit=False)
            new_object.project = p
            new_object.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:
        form = form_class()
    if not template_name:
        template_name = "%s/%s_insert_form.html" % (model._meta.app_label, model._meta.object_name.lower())
    return render_to_response(template_name, {"form": form}, RequestContext(request))
Пример #2
0
def create_text_content(request, model=None, form_class=None):
    """Creates a view based on template_name template and fills in the user"""
    assert model or form_class
    model, form_class = get_model_and_form_class(model, form_class)
    template_name = os.path.join('content', 'textcontent_form.html')
    instance = model(user=request.user)
    if request.method == 'POST':
        form = form_class(request.POST or None,
                          request.FILES or None,
                          instance=instance)
        if form.is_valid():
            new_object = form.save()
            request.user.message_set.create(message=ugettext(
                    "The %(verbose_name)s was created successfully.")
                    % {"verbose_name": model._meta.verbose_name})
            return HttpResponseRedirect(new_object.get_absolute_url())
    else:
        form = form_class(instance=instance)
    if not template_name:
        template_name = "%s/%s_form.html" % (model._meta.app_label,
                                         model._meta.object_name.lower())
    template = loader.get_template(template_name)
    context = RequestContext(request, {
        'form': form,
    })
    return HttpResponse(template.render(context))
Пример #3
0
def create_obj(model, data, form_class=None):
    model, form_class = get_model_and_form_class(model, form_class)
    form = form_class(data)
    if form.is_valid():
        new_object = form.save()
        return new_object.id
    else:
        return 0
Пример #4
0
def update_obj(model, object_id, data, form_class=None):
    model, form_class = get_model_and_form_class(model, form_class)
    obj = get_obj(model, pk__exact=object_id)
    form = form_class(data, instance=obj)
    if form.is_valid():
        obj = form.save()
        return obj.id
    else:
        return 0
Пример #5
0
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))
Пример #6
0
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
Пример #7
0
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))
Пример #8
0
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
Пример #9
0
def create_user_owned_object(
    request,
    model=None,
    template_name=None,
    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 = 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 = Task()
            new_object = form.save(commit=False)
            # ~ relation with session user
            new_object.owner = request.user
            new_object.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:
        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())

    return render_to_response(template_name, {"form": form}, RequestContext(request))

    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
Пример #10
0
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))
Пример #11
0
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

    if extra_context is None: extra_context = {}
    if login_required and not request.user.is_authenticated():
        return redirect_to_login(request.path)

    try:
        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)
                    response = redirect(post_save_redirect, obj)
        else:
            form = form_class(instance=obj)
    except (IOError, PermissionDenied), e:
        messages.error(request, e)
        return None
Пример #12
0
def my_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
    """
    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()
            new_object.creator = request.user
            new_object.save()
            if request.user.is_authenticated():
                Message(
                    user=request.user,
                    message=ugettext("The %(verbose_name)s was created successfully.")
                    % {"verbose_name": model._meta.verbose_name},
                ).put()
            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)
    return HttpResponse(t.render(c))
Пример #13
0
def task_update(
    request,
    model=None,
    object_id=None,
    slug=None,
    slug_field="slug",
    template_name=None,
    extra_context=None,
    post_save_redirect=None,
    login_required=False,
    context_processors=None,
    template_object_name="object",
    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 = get_model_and_form_class(model, form_class)
    obj = lookup_object(model, object_id, slug, slug_field)

    if request.method == "POST":
        # ~ recuperar o crear el proyecto
        p = Project.objects.get_or_create_by_owner_and_title(request.user, request.POST.get("project_title"))
        form = form_class(request.POST, request.FILES, instance=obj)
        del form.fields["project"]
        if form.is_valid():
            obj = form.save(commit=False)
            obj.project = p
            obj.save()
            msg = ugettext("The %(verbose_name)s was updated successfully.") % {
                "verbose_name": model._meta.verbose_name
            }
            messages.success(request, msg, fail_silently=True)
            if "_continue" not in request.POST:
                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())
    return render_to_response(template_name, {"form": form, "object": obj}, RequestContext(request))
Пример #14
0
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))
Пример #15
0
def async_form(request, app_name, model_name, object_id='', win_id=''):
    print "async_form POST data:\n", request.POST
    model = get_model(app_name, model_name)
    model, form_class = get_model_and_form_class(model, None)
    auto_id = "id_%s"
    if win_id: auto_id += "_" + win_id
    if request.method == 'POST':
        #form = Form(request.POST, auto_id=auto_id)
        form = form_class(request.POST, auto_id=auto_id)
        if form.is_valid(): form.save()
        else:
            errors = form.errors
            return render_to_response('%s/errors.html' % get_template_dir(app_name), {'errors': errors})
        #return HttpResponseRedirect('/async/%(app_name)s/%(model_name)s/%(object_id)s/%(win_id)s/' % vars())
        return JsonResponse({'result': 'OK'})
    else:
        if object_id:
            object = get_object_or_404(model, pk=object_id)
            form = form_class(instance=object, auto_id=auto_id)
        else:
            form = form_class(auto_id=auto_id)
        params = {
            'debug': False,
            'form': form,
            'edit_object': False,
            'is_owner': True,
            'app': app_name,
            'model': model_name,
            'win_id': win_id,
            'object_id': object_id,
        }
        template_name = '%s/%s_form.html' % (get_template_dir(app_name), model_name)
        try:
            template = get_template(template_name)
        except TemplateDoesNotExist:
            template = Template(template_for_model(model))
        context = RequestContext(request, params)
        return HttpResponse(template.render(context))
Пример #16
0
def create_object_related(request,  model=None, form_class=None, #foreign_model=None,
    foreign_id=0,foreign_model=None, foreign_field_name='',#~ initial={}
    extra_context={},template_name=None,post_save_redirect=None, ajax=None):
    """
    This view allows you to add an object that belongs to a father model. 
    In the template you won't view the foreign key field. It will take the 
    parent id automatically. 
    """
    from django.views.generic.create_update import get_model_and_form_class
    from django.views.generic.create_update import redirect
    from django.utils.translation import ugettext
    #~ 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 not post_save_redirect:
            try:
                post_save_redirect=foreign_model.objects.get(pk=foreign_id).get_absolute_url()
            except:
                pass
        form = form_class(request.POST, request.FILES)
        del form.fields[foreign_field_name]
        if form.is_valid():
            new_object = form.save(commit=False)
            #~ new_object.contact=foreign_id
            setattr(new_object,foreign_field_name+'_id',foreign_id)
            new_object.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:
        form = form_class()
        del form.fields[foreign_field_name]
    # Create the template, context, response
    if not template_name:
        template_name = "%s/%s_form.html" % (model._meta.app_label, model._meta.object_name.lower())
    return render_to_response(template_name, {'foreign_id':foreign_id,'form': form,'opts':model._meta}, context_instance=RequestContext(request))
Пример #17
0
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))
Пример #18
0
def generic_crud(request, obj_id, model, template, redirect,
                 extra_context={}, form_class=None,
                 template_object_name="object", pre_save=None,
                 post_save=None, success_msg=None):
    """
    Generic way to create/update a bit more advanced than the django's generic
    views. The context will contain the form as C{form}, the object when
    updating as the value in C{template_object_name} which defaults to
    "object", and anything specified in C{extra_context}.
    
    @param request: The request object
    @param obj_id: The object's id to update or None if creating an object
    @param model: The model class
    @param template: the name of the template to use
    @param redirect: callable that takes the created/saved instance as argument
        and returns a URL to redirect to.
    @keyword extra_context: dict of fields to add to the template context.
    @keyword form_class: the form class to use for the object (ModelForm subclass)
    @keyword template_object_name: name of the object field in the template
        context. This is only available when updating.
    @keyword pre_save: function to call before saving the object instantiated
        from the form. Called with arguments (C{instance}, C{created}).
    @keyword post_save: function to call after saving the object instantiated
        from the form but before calling m2m_save() on it. Called with argument
        (C{instance}, C{created}).
    @keyword success_msg: callable that should take instance as parameter and
        return a string to be put in a success DatedMessage and sent to the
        user on success. 
    """
    
    model, form_class = get_model_and_form_class(model, form_class)

    if obj_id != None:
        instance = get_object_or_404(model, pk=obj_id)
    else:
        instance = None
        
    if request.method == "GET":
        form = form_class(instance=instance)
    elif request.method == "POST":
        form = form_class(request.POST, instance=instance)
        if form.is_valid():
            instance = form.save(commit=False)
            if pre_save:
                pre_save(instance, obj_id == None)
            instance.save()
            if post_save:
                post_save(instance, obj_id == None)
            form.save_m2m()
            if success_msg:
                DatedMessage.objects.post_message_to_user(
                    success_msg(instance), request.user,
                    msg_type=DatedMessage.TYPE_SUCCESS)
            return HttpResponseRedirect(redirect(instance))
    else:
        return HttpResponseNotAllowed("GET", "POST")

    context = {"form": form}
    context.update(extra_context)
    if obj_id != None:
        context[template_object_name] = instance

    return simple.direct_to_template(
        request,
        template=template,
        extra_context=context,
        form=form,
    )
Пример #19
0
    def __init__(self):
        #same as Django generic views
        self.model, self.form = get_model_and_form_class(self.model, self.form)

        self.store = self.direct_store()
Пример #20
0
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
Пример #21
0
	def getFormFromModel(model, form_class=None):
		model, form_class = get_model_and_form_class(model, form_class)
		return form_class
Пример #22
0
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))
Пример #23
0
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
Пример #24
0
def list(request, fields, model=None, queryset=None, form_class=None, 
        template=DEFAULT_LIST_TEMPLATE, object_name=None, app_name=None, 
        object_verbose_name=None, rights={}, 
        acl_handler=DEFAULT_ACL_HANDLER, extra_context={}, *args, 
        **kwargs):
    """A generic List method, that allows to specify the list of what we want
    to display.

    You could either pass a model or a queryset to loop on. 
    This view also display a creation form, if a form is provided and the user 
    has the rights to do so.

    The rights are defined with the right arguments, wich is a dict.
    This is mainly used to know if the current user can do CRUD actions.

    If these are not defined, list uses the acl_handler, if given, to
    determine wich rights to set for the current user. If not defined, this
    callable use DEFAULT_ACL_HANDLER.

    By default, the list action use a template defined by 
    DEFAULT_LIST_TEMPLATE, but you can change this behavior by setting the
    `template` parameter.
    """

    if model is None and queryset is not None:
        model = queryset.model
    if model:
        model, form_class = get_model_and_form_class(model, form_class) 
    if queryset is None:
        queryset = model.objects.all()
    queryset = queryset._clone()

    list_params = {}
    if queryset:
        for obj in queryset:
            list_params[obj.id] = []
            for (key, attrs) in fields:
                item = obj
                for attr in attrs.split('.'):
                    if hasattr(item, attr):
                        item = getattr(item, attr)
                        if callable(item):
                            try:
                                item = item()
                            except Exception:
                                item = ""
                    else:
                        item = ""
                list_params[obj.id].append((key, item))
    try:
        if object_name is None:
            object_name = model.__name__.lower()
        if app_name is None:
            app_name = model.__module__.split('.')[0]
    except AttributeError:
        object_name, app_name = None, None
    
    #Gruik
    if request.is_ajax():
        return HttpResponse(json.dumps([dict(list_params[m]) 
                            for m in list_params]))

    return_context = {
        'elements': list_params,
        'object_name': object_name,
        'app_name': app_name,
        'object_verbose_name': object_verbose_name or object_name,
        'form': form_class(),
    }

    return_context = _process_rights(request, acl_handler, return_context, 
        rights, *args, **kwargs)
        
    # add extra_context
    for key, value in extra_context.items():
        return_context[key] = value
    return render_to_response(template, return_context, request)
def form_user_default(request):
    if request.method == 'POST':
        model, custom_form = get_model_and_form_class(Resource,None)
        custom_form.author = request.user
        return {'form':custom_form}
    else: return {}