Django: How do I create a generic url routing to views?

I have a pretty standard django app, and am wondering how to set the url routing so that I don't have to explicitly map each url to a view.

For example, let's say that I have the following views: Project, Links, Profile, Contact. I'd rather not have my urlpatterns look like this:

(r'^Project/$', ''),
(r'^Links/$', ''),
(r'^Profile/$', ''),
(r'^Contact/$', ''),

And so on. In Pylons, it would be as simple as:


And it would automatically grab the right controller and function. Is there something similar in Django?

Asked by: Rafael623 | Posted: 28-01-2022

Answer 1

mods = ('Project','Links','Profile','Contact')

urlpatterns = patterns('',
   *(('^%s/$'%n, ''%n.lower()) for n in mods)

Answered by: Ted703 | Posted: 01-03-2022

Answer 2

Unless you have a really huge number of views, writing them down explicitly is not too bad, from a style perspective.

You can shorten your example, though, by using the prefix argument of the patterns function:

urlpatterns = patterns('',
    (r'^Project/$', 'project'),
    (r'^Links/$', 'links'),
    (r'^Profile/$', 'profile'),
    (r'^Contact/$', 'contact'),

Answered by: Ted588 | Posted: 01-03-2022

Answer 3

You might be able to use a special view function along these lines:

def router(request, function, module):
    m =__import__(module, globals(), locals(), [function.lower()])
        return m.__dict__[function.lower()](request)
    except KeyError:
        raise Http404()

and then a urlconf like this:

(r'^(?P<function>.+)/$', router, {"module": ''}),

This code is untested but the general idea should work, even though you should remember:

Explicit is better than implicit.

Answered by: Melissa608 | Posted: 01-03-2022

Similar questions

python - Django: class views, generic views, etc

I'm coming back to Django after a brief encounter with version 1.2, and now in version 1.3 the favored approach to views seems to be using classes. Keeping in mind code style, maintainability and modularity: when should I use classes, and when functions? Should I always extend from generic class views (there seems to be no harm in using TemplateView), or should I use my own view callable objects? Thanks in ...

python - Django: Generic detail view must be called with either an object pk or a slug

Getting this error when submitting the form associated with this view. Not sure what exactly is the problem, considering I have a form with a very similar structure and it works fine. class Facture_Creer(SuccessMessageMixin, CreateView): model = Facture template_name = "facturation/nouvelle_facture.html" form_class= FormulaireFacture # permet de retourner a l'URL pointant vers le ...

python - django: generic delete view

I want to build a generic delete view for my application. Basically I want to have the same behaviour as the standard django admin. E.g. I want to be able to delete different objects using the same view (and template). I was looking on django docs, and looks like that DeleteViews are coupled with the models they are supposed to delete. E.g. class AuthorDelete(DeleteView): model = Author suc...

python - Django: create view inline generic update view

I am working on Django 1.11. I have two models, the first one has a foreign key like this : class Book(models.Model): name=models.CharField(max_length=100) owner = models.ForeignKey(Owner, on_delete=models.PROTECT, null=True, default=None) other_properties class Owner(models.Model): some_property I use the generic.UpdateView to update my Books :

python - Django: Model name clash

I am trying to use different open source apps in my project. Problem is that there is a same Model name used by two different apps with their own model definition. I tried using: class Meta: db_table = "db_name" but it didn't work. I am still getting field name clash error at syncdb. Any suggestions. Update I am actually trying to integ...

python - Django: How to set initial values for a field in an inline model formset?

I have what I think should be a simple problem. I have an inline model formset, and I'd like to make a select field have a default selected value of the currently logged in user. In the view, I'm using Django's Authentication middleware, so getting the user is a simple matter of accessing request.user. What I haven't been able to figure out, though, is how to set that user as the default selected v...

python - Django: Get an object form the DB, or 'None' if nothing matches

Is there any Django function which will let me get an object form the database, or None if nothing matches? Right now I'm using something like: foo = Foo.objects.filter(bar=baz) foo = len(foo) &gt; 0 and foo.get() or None But that's not very clear, and it's messy to have everywhere.

python - Django: how to include the file?

I have a Django Application. I want to have all my models to be separated in files and lay in the specific directory, for instance: /usr/project/models/ Is it any possible? Just importing through from myModel import * doesn't work, unfortunately. Is there any specific way to do this?

python - Django: How to modify a text field before showing it in admin

I have a Django Model with a text field. I would like to modify the content of the text field before it's presented to the user in Django Admin. I was expecting to see signal equivalent of post_load but it doesn't seem to exist. To be more specific: I have a text field that takes user input. In this text field there is a read more separator. Text before the separato...

python - Django: Blank Choices in Many To Many Fields

When making forms in Django, the IntegerField comes with a blank choice (a bunch of dashes "------") if called with blank=True and null=True. Is there any way to get ManyToManyField to include such an explicit blank choice? I've tried subclassing ManyToManyField with no success: class ManyFieldWithBlank(ManyToManyField): """ A Many-to-Many Field with a blank choice """ def ...

python - Django: How should I store a money value?

I'm running into a paradigm problem here. I don't know whether I should store money as a Decimal(), or if I should store it as a string and convert it to a decimal myself. My reasoning is this: PayPal requires 2 decimal places, so if I have a product that is 49 dollars even, PayPal wants to see 49.00 come across the wire. Django's DecimalField() doesn't set a decimal amount. It only stores a maximu...

python - Django: Setting one page as the main page

I'm a newbie at Django and I want to do something that I'm not sure how to do. I have a model SimplePage, which simply stands for a webpage that is visible on the website and whose contents can be edited in the admin. (I think this is similar to FlatPage.) So I have a bunch of SimplePages for my site, and I want one of them to be the main page. (a.k.a. the index page.) I know how to make it available on the...

python - Django: sqlite for dev, mysql for prod?

Closed. This question is opinion-based. It is not c...

python - Django: create HTML input array using a django form

I am trying to automate the creation of something like this: &lt;input type='text' name='asdf[]' /&gt; &lt;input type='text' name='asdf[]' /&gt; &lt;input type='text' name='asdf[]' /&gt; By cycling through a range in the form. I've been trying things like this, along with several other variations: # in a model class for i in range(1, prim+1): self.fields['asdf'] = forms...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python