1

I had posted a question without any result. I fear it may be how I posed it...

In the admin, I would like the Add button to direct the user to a different view than the normal form (that would simply consist of a search field and button). After the 'search' form has been validated, it would then send the user to the standard add/change form with some instance data. What is the best method to achieve this?

1 Answer 1

1

So, I got the Tumbleweeds bronze star for dearth of responses to this question. I ended up partially solving it as follows...

Added a get_urls method to my model's admin

def get_urls(self):
    urls = super(MyModelAdmin, self).get_urls()
    addl = patterns(',
        (r'^add/$', 'MyApp.views.my_add_view)
    )

return addl + urls

Created a form for the 'Add' view

from django import forms
from MyApp.models import MyModel

class LookupForm(forms.Form):
    pk = ''
    url = forms.URLField(max_length=_URLMAXLEN, label='Video URL', 
                widget=forms.TextInput(attrs={'size':'60', 'autofocus':'autofocus'}))

    def clean_url(self):
        value = self.cleaned_data['url']

        #    some validation of 'value' here
        #    ...

        self.pk = somefoo(value)
        return value

And in views, I redirect to the change form after validating and saving the model instance

from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from MyApp.forms import LookupForm

def my_add_view(request):
    confirm = ''
    if request.method == 'POST':
        form = LookupForm(request.POST)

        if form.is_valid():
            if 'confirm_button' in request.POST:
                foo_save()  #   save model instance

                #   LookupForm's 'pk' property set during some clean_ method
                href = reverse('admin:MyApp_MyModel_change', args=(form.pk,))
                return HttpResponseRedirect(href)

            elif 'search_button' in request.POST:
                confirm = foo_context() #   some context from the search results

    else:
        form = LookupForm()

    return render(request, 'my_template.html', {'form': form, 'confirm': confirm})

Unfortunately I cannot achieve my goal of displaying the change form with instance data. Instead of having to save and redirect to the change_form, I would prefer to be able to direct with MyModelForm(instance=some_instance)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.