Include Django Project specific objects in Django package - python

I'm developing a web-app with common components and decided to pack those common components (some views, templates, logic) in a Django package.
Now the problem is: I want to access variables of my specific Django project, depending on the project, from the package. In this specific instance:
My Django package has an admin panel. A custom-made admin panel that allows me to manage a list of algorithms. However, these algorithms change. In one specific Django project I might have 3 algorithms, in another one I might have 5.
The admin panel in the Django package allows me to edit custom algorithm components, such as weights, test cases, etc.
Now my problem is, in the Django view, in the package, I want to access the Django project's algorithms in order to show them. As a list, for selection/editing/deleting, but also to view them in detail and edit them.
Now my problem is, obviously, I can't include something from the Django project in the Django package, otherwise it would become a dependency. And the algorithms are different and unique in each specific project.
So, in short, the question is how to access specific data of a Django project by a package used by that project, without making the package dependent of anything.

OK, so after some more investigation I found a possible solution for this. Will leave it here for informational purposes while waiting for an answer.
Instead of loading the package URLs as a module I use a custom function that passes the Django project's variables to the package URLs, and therefore, the views.
So in the project urls.py, instead of:
url(r'^package/$', include('package.urls'))
I use
url(r'^package/$', obtain_package_urls(custom_content))
where obtain_package_urls() is a function in the package:
def obtain_package_urls(custom_content):
urlpatterns = patterns('',
url(r'^url1$', view1, {'custom_content': custom_content},
url(r'^url2$', view2, {'custom_content': custom_content},
)
return (urlpatterns, None, None)
The goal is to, instead of the include function that includes the static URL-view mapping of Django, to use this function that returns a dynamic URL-view mapping with the custom content included in the views.
So in effective terms with the algorithms I ended up doing:
#Django project settings.py
obtain_algorithm_list():
return Algorithm.objects.all()
#Django project urls.py
from project.settings import obtain_algorithm_list
urlpatterns = ...
...
url(r'^package/$', obtain_package_urls(obtain_algorithm_list())
...
#In the package urls.py
urlpatterns = ...
url(r'^view1/$', view1, {'algorithms': algorithms},
...
#And then in each package view
def view(request, algorithms=[]):
...
use_for_something(algorithms)

Related

Django: generate python code from command line

Is here a way to write a Django command to generate code automatically?
In my case: every time I create a new model I must create the following stuff too:
Create Administration classes in admin.py
Create service functions related to this model.
Create a factory using FactoryBoy.
Create test classes.
It would be nice if there was a command that generates this stuff automatically. Not everything, of course, but just the basic, the definition.
Is there something like this today in Django? Or is there a way I can write Django commands to generate code?
I have not personally used it yet but you could try to use the third-party package
Django baker Django Baker that offers that functionality
Django Baker wants to help you get your projects up and running
quickly. Given one or more app names, s/he will automatically generate
views, forms, urls, admin, and templates for all of the models in the
models.py file. All files are pep-8 compliant (with exception to the
maximum line length rule, which I don't agree with).
Once you add a single urlpattern to your project's URLconf, you'll
have a working list view, detail view, create view, update view, and
delete view for each model in your app.
Optionally you may specify which models in an app to bake if you'd
rather not generate files for all of them.
Try django commands and jinja2 templates.
With the execution of custom defined command, set of file templates can be updated with appropriate content and copied to respective folders as per need.

Subclassing and overriding Django Class based views

I'm building a website using django-all auth for it's authentication and social authentication functions. The forms that come bundled with the app are hardly great to look at and hence I decided to create my own views.
The problem is: How do I create them while ensuring that the backend of Django all auth is still available to me? I've dug into the source code and found that it uses class based views for rendering and performing CRUD operations.
I want to know if I can subclass those views in my own app/views.py and just change their template_name field to my own templates. Any advice would be most helpful.
Thanks.
You can of course subclass the views, as long as you change your URLs to point to the overridden versions. However, there is no need to do this just to use your own templates; Django's template loader is specifically written with this use case in mind. Simply create your own directory inside your templates folder to match the one allauth is using, and create your own template files inside it; Django will find yours first and use them.

Using custom forms in Django instead of modifying the source files

Let me preface this by saying I'm VERY new to Django and am also having a hard time with some of the documentation. I know that this question has surely been asked and answered a thousand times, but I can't seem to phrase my query properly.
I'm making a project that uses django-registration-redux, and I wanted to customize the template and the forms to accept additional user information. First, I noticed that my changes to the template files weren't having any effect , then I realized that it was using the template files from my Python install location instead of my actual project. I fixed this by setting the templates folder setting, but I also need to modify the registration-redux forms, and can't figure out how to override the default forms with local forms in my application.
You need not change the template settings for your existing project, but you have to make sure you have included 'registration' in the list of your INSTALLED_APPS. In the documentation its mentioned that
You can extend and customize the included templates as needed
Though its not very clear here, django registration redux is built on top of the in built django registration module. What you need to do is build your own custom registration form which is already explained in this answer.
In your case the template that you need to modify/extend is registration/registration_form.html.
Other useful resources that can help you:
http://www.tangowithdjango.com/book17/chapters/login_redux.html
https://www.youtube.com/watch?v=qkFWkOw-ByU

How do I define custom filters for minimal use of django templates?

I have a python project that I'm using Django templates for to generate C++ source code.
I picked Django because the template language is quite restrictive and has a very large community making it easy for end-use developers to use and get help with.
I'm failing to add custom filters for my project (to translate one set of type names into another) because I have not done the normal django setup.
Instead:
from django.template import Context, Template
import django
if not django.conf.settings.configured : django.conf.settings.configure()
django.setup()
Lets me use Django templates perfectly but not define custom filters.
My custom filter is called ctypes_filters.py and I reference it in the template as
{% load ctypes_filters %}
Running my generation script results in the following error:
django.template.base.TemplateSyntaxError: 'ctypes_filters' is not a valid tag library: Template library ctypes_filters not found, tried
django.templatetags.ctypes_filters
How can I get django to find the filter without setting up a full Django project (database definitions etc)?
I know that other templating solutions are available (and are probably more light-weight) but I'm really keen to use Django's simple and elegant templates.
The location of Django template tags is done by convention rather than a configuration setting (see the code layout section of the template tags docs).
Put the ctypes_filter.py in a templatetags directory in an installed app (I've called it myapp here). Add an empty __init__.py to both the myapp and templatetags directories. The app doesn't need any other files you might commonly find in a Django app, like models.py or views.py.
myapp/
__init__.py
templatetags/
__init__.py
ctypes_filter.py
Then include myapp in your INSTALLED_APPS when configuring your settings.
django.conf.settings.configure(
INSTALLED_APPS=('myapp',),
)

django app organization

I have been reading some django tutorial and it seems like all the view functions have to go in a file called "views.py" and all the models go in "models.py". I fear that I might end up with a lot of view functions in my view.py file and the same is the case with models.py.
Is my understanding of django apps correct?
Django apps lets us separate common functionality into different apps and keep the file size of views and models to a minimum? For example: My project can contain an app for recipes (create, update, view, and search) and a friend app, the comments app, and so on.
Can I still move some of my view functions to a different file? So I only have the CRUD in one single file?
First, large files are pretty common in python. Python is not java, which has one class per file, rather one module per file.
Next, views, even as the standard used, is a python module. A module need not be a single file. It can be a directory containing many files, and __init__.py
And then, views.py is only a convention. You, the application programmer are referring to it, and django itself doesn't refer anywhere. So, you are free to put it in as many files and refer appropriate functions to be handed over, the request to, in the urls.py
They don't have to go in views.py. They have to be referenced there.
views.py can include other files. So, if you feel the need, you can create other files in one app that contain your view functions and just include them in views.py.
The same applies to models.py.
Django apps lets us separate common
functionality into different apps and
keep the file size of views and models
to a minimum? For example: My project
can contain an app for recipes
(create, update, view, and search) and
a friend app, the comments app, and so
on.
I don't know about the "to a minimum" part - some apps are just big in views, others big in models. You should strive to partition things well, but sometimes there is just a lot of code. But other than that, this is a fair summary of Django apps, yes.
I also very much dislike long files.
Of course what you read in the other answers is true, but I exploit some very nifty python equivalence:
views.py
and
views/__init__.py
are pretty much functionally equal - by that I mean that if the both contain def my_view() then
from views import my_view
will work the same in both cases!
From there it's easy to structure your long files into smaller ones, yet keeping the naming convention that every django developer is used to:
views/__init__.py
views/largemodel_view.py
then in __init__.py don't forget to import the views from largemodel_view.py.
With large applications I do the same with models though you must remember to set the Meta.app_name:
class MyModel(models.Model):
...
class Meta:
app_name = 'yourappname'
because django will not pick it up magically otherwise for the Admin (but it will still load it, thanks to Python!)
so my apps usually end up looking something like:
project/settings/__init__.py
/..othersettings..
/app_1/models/__init__.py
/...
/views/__init__.py
/...
/templates/
/static/
urls.py
/urls.py
etc.
though of course there's no limit (urls could be split too, etc.etc.)

Categories