Dynamic generate urlpatterns for django 2
Create dynamic urlpatterns for classed based views
- django
- dynamic
- urlpatterns
Create dynamic urlpatterns for classed based views
If you require lots of forms in your project and do not want to be creating an extended template for each one I propose this solution. Classes in the html correspond to bootstrap, you can work without them if you do not use bootstrap.
Store in SiteID a local var store for save SITE_ID thread-safe and set it with middleware. It's base on https://djangosnippets.org/snippets/1099/ but with call to local() in SiteID and using custom models for web site and domains.
Django's built-in {% regroup %} template tag is great, but sometimes, you need to pass in the attribute you want to group on instead of declaring the attribute when you define the tag. {% dynamic_regroup %} is identical in function to {% regroup %}, except that it will attempt to resolve a context variable for the attribute you want to group by. {% dynamic regroup %} is also backward compatible, so you can also hand in the attribute literal and it will work as expected. See the end of the code for an example of usage.
This snippet shows how to add additional parameters to the queryset of a ModelChoiceField, enabling you to for instance filter the query.
Allow you to specify a "General case formset/modelformset" and then alter the attributes of that formset, specificly: extra, can_order, can_delete and max_num. So you specify: >>> formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O')) and then you want to dynamically add multiple fields with javascript and save the new ones. By default a formset only has 1 extra field. With this you can return a new formset (using the same queryset, forms, formset base class, etc) but with different attributes. So you could then add 10 extra fields if the user added 10 new forms.
Background ========== Two years ago, Malcolm Tredinnick put up an excellent post about doing dynamic Django forms. There have been several excellent write-ups on it since - Google is your friend. One year ago, I attempted to make a dynamic Formset - see [this snippet](http://www.djangosnippets.org/snippets/1290/). Malcolm posted a cleaner solution two weeks later, and I liked his solution better. Some time after that happened, his site tanked. I'm re-posting my snippet using his technique, so that everyone can see how it is done. Credit to goes to Malcolm - I'm just the messenger. If his site ever comes back up , check out his complex formset post [here](http://www.pointy-stick.com/blog/2009/01/23/advanced-formset-usage-django/). I'll use Malcolm's example code, with as few changes as possible to use a formset. The models and form don't change, and the template is almost identical. I won't reproduce all of Malcolm's code - I'm just show the form setup. There are no models here - you'll have to use your imagination for Quiz, Question, and Answer models. He did some fancy validation as well - I'm not going to here. Problem ======= Build a formset based on dynamically created forms. Solution ======== The core idea in this code is found in the `_construct_form` method. Typically, this is where a formset makes new forms - it handles indexing them so that everything is nice and unique. We can take advantage of this by overriding the method and inserting a `kwarg` that will be passed on to our form class, then calling the parent `_contruct_form` method to let it finish doing everything else for us. This is what Malcolm, a core Django developer, knows about, and I, a random Django user, typically do not. Code ==== This pattern greatly simplifies building formsets dynamically, and it really only requires a few bits of knowledge. 1. If we `pop()` special arguments out of `kwargs` dictionaries, we then can pass the remaining `kwargs` along to parent methods and let them do the rest of the setup for us. See code tricks #1 and #3. 2. If we have a form and need to add dynamic fields that we didn't declare the usual way, we can just add them to the `self.fields` dictionary. See code trick #2. 3. If we need to add forms dynamically to a formset, we can use the `self.extra` variable to specify how many we want, based on the length of a custom queryset. See code trick #4. 4. If we want to pass some special arguments to a form that will be part of a formset when it is constructed, we can add them to the `kwargs` dict in `_construct_form`, taking advantage of the `index` variable to track which object from our queryset we wanted. See code trick #5.
A very plugable way to get Stanislaus jquery dynamic formset working in the admin with adding just one template. Add the following to templates/admin/APP/MODEL/change_form.html and also update the MODEL in the prefix setting. Thanks Stanislaus [http://elo80ka.wordpress.com/2009/10/10/jquery-plugin-django-dynamic-formset/](http://elo80ka.wordpress.com/2009/10/10/jquery-plugin-django-dynamic-formset/) [http://go2.wordpress.com/?id=725X1342&site=elo80ka.wordpress.com&url=http%3A%2F%2Fcode.google.com%2Fp%2Fdjango-dynamic-formset%2F](http://go2.wordpress.com/?id=725X1342&site=elo80ka.wordpress.com&url=http%3A%2F%2Fcode.google.com%2Fp%2Fdjango-dynamic-formset%2F) [http://www.djangosnippets.org/snippets/1389/](http://www.djangosnippets.org/snippets/1389/)
Ok... this is really a hack. But I love it. I hate setting up all of my test cases into suites, and making sure that I remember to add them each time I add a new python file... annoying! This allows me to have a tests package and then just add python files and packages to that test package (mirroring my app setup). Each of the files are then dynamically imported and every test case is automatically executed. If you don't want one to execute, add it to the ignore list. If you add 'views' to the ignore list, it will ignore all views, otherwise you would have to specify 'package.views' if it is in a package. So... in short this is a bit ghetto, but it saves me a lot of time just setting up all my tests... now I can just write them! Hope it's useful to someone. Greg
superSearch is intended to make it easier to make complex OR queries, thusly hitting the database less. EXAMPLE: Searching for a user named 'Eric Neuman' would be difficult because first_name and last_name are separate fields. However, with superSearch, it's a breeze. query = ['Eric Neuman'] f = ['first_name','last_name'] s = query.split(' ') m = ['icontains'] results = superSearch(User, f, m,s)
This is an example of how you change a ChoiceField select widget into a hidden field if the right GET variable is passed. In this example code it would change the select widget into something like the following if something like "?d=3" was passed. `<p><label for="id_designation">Designation</label>Designation Option<input type="hidden" name="designation" value="3" id="id_designation" /></p>`
This jQuery javascript enables dynamic add/delete of rows in tabular inlines. It adds a "+" icon at the bottom of the inline to allow addition of new rows, and replaces the default delete checkbox with a "x" icon for deletion, giving you the possibility to add/delete rows instantly without reloading the page. In addition, it gives you drag-n-drop ordering functionality with a named position model field using jQuery UI Sortable. **Usage (see below for example):** Just include the javascript on your admin page, together with jQuery, and it'll automatically affect all tabular inlines. Optionally, also include jQuery UI Sortable and an Integer field in your inline model named "position" (or whatever you set "position_field" to), which will automatically hide the position field and enable drag-n-drop sorting. **Developed for:** * jQuery 1.3.2 * jQuery UI 1.7.1 * Django trunk (tested in Django v1.0.2) * (Might work with other versions with or without adjustments, but not tested) **Settings (in top of javascript):** * "position_field" is the name of an integer model field that is used for ordering the inline model. If left empty or not found, the drag-n-drop functionality is dropped. Defaults to "position". * "add_link_html" for custom look of "add"-buttons. Defaults to Django's built-in "+" image icon. * "delete_link_html" for custom look of "delete"-buttons. Defaults to Django's built-in "x" image icon. **Use example: ** *admin.py:* class NameInline(admin.TabularInline): model = Name extra = 1 class PersonAdmin(admin.ModelAdmin): inlines = [NameInline] class Media: js = ['js/jquery-1.3.2.min.js', 'js/ui/ui.core.js', 'js/ui/ui.sortable.js', 'js/dynamic_inlines_with_sort.js',] css = { 'all' : ['css/dynamic_inlines_with_sort.css'], } admin.site.register(Person, PersonAdmin) *models.py:* class Person(models.Model): year_born = models.PositiveIntegerField(_('year born'), null=True, blank=True) class Name(models.Model): profile = models.ForeignKey(Profile, verbose_name=_('profile')) position = models.PositiveIntegerField(_('position'), default=0) name = models.CharField(_('name'), max_length=100) class Meta: ordering = ('position',) *dynamic_inlines_with_sort.css:* /* To make row height of saved items same as others */ .inline-group .tabular tr.has_original td { padding-top:0.5em; } .inline-group .tabular tr.has_original td.original p { display:none; } Please post bugs in comments.
This is an example how to dynamically import modules other than `models.py` from installed apps. It allows you to define the full module path just once in `INSTALLED_APPS` in the settings. Using this technique makes it possible to write extensible and reusable apps as mentioned in [Abstract Models and Dynamicly Assigned Foreign Keys](http://djangotricks.blogspot.com/2009/02/abstract-models-and-dynamicly-assigned.html). Probably, it would be great to have some helpers for doing this in django itself. For example: from django.db import models from django.utils import importlib def import_installed(path): """ Imports a module from an installed app >>> import_installed("myapp.forms") <module 'myproject.apps.myapp.forms'> """ app_name, module = path.split(".", 1) app = models.get_app(app_name) return importlib.import_module(app.__name__[:-6] + module) UPDATE: Reported as ticket [#10703](http://code.djangoproject.com/ticket/10703)
This code demonstrates two simple techniques: 1. so-called "dynamic" forms, in which the form is created at run time by the model 2. using a widget (forms.widgets.HiddenInput) for a field of the form. I feel like this could be highlighted more in the documentation. You need to do something similar to get a textarea (forms.CharField(widget=forms.widgets.Textarea()) and it took me too long to figure this out. There are, no doubt, good reasons not to do what I'm doing here the way I'm doing it. Peanut gallery?
I often use it so I hope it helps! Usage: urlpatterns = patterns('', url(r'^nav/$', redirect('/navigation/')), url(r'^search/(?P<category_name>\w+)/$', redirect('/documents/%(category_name)s/')), and so on... ) It keeps GET arguments too.
27 snippets posted so far.