I'm trying to set up auto documentation generation using tastypie swagger, as documented here. However, Django doesn't seem to be a fan of the following line in my setup:
TASTYPIE_SWAGGER_API_MODULE = 'mainsite.urls.api'
as evidenced by this error when I try to hit /api/doc:
ImproperlyConfigured at /api/doc/
mainsite.urls is not a valid python path
I am working off of a Django 1.4 project I found online to introduce myself to some of the technologies. The Django structure looks like this:
project_directory
src
urls.py
manage.py
settings.py
etc...
app
models.py
views.py
api.py
etc...
Any ideas?
You're not supposed to cut and paste 'mainsite.urls.api'. You're supposed to replace it with your tastypie api that you created according to the tastypie docs.
Specifically, see here:
http://django-tastypie.readthedocs.org/en/latest/tutorial.html#adding-to-the-api
If you blindly copied the tastypie setup instructions, you should have something like:
TASTYPIE_SWAGGER_API_MODULE = 'urls.v1_api'
I had this error with the current (March 2016) version of tastypie-swagger. The setting for me that worked was this:
from tastypie.api import Api
v1_api = Api(api_name='v1')
v1_api.register(MyResource())
urlpatterns = [
...
url(r'^api/', include(v1_api.urls)),
url(r'api/v1/doc/',
include('tastypie_swagger.urls', namespace='api_tastypie_swagger'),
kwargs={"tastypie_api_module": v1_api, "namespace": "api_tastypie_swagger"}
),
]
so tastypie_api_module is v1_api without quotes
Related
I was using the Django version 3, but then upgraded it to Django version 4(django==4.0.6).
After logging to admin panel of Django project, it said that CSRF token is invalid.
I found this link in Django documentation and tried to put such variable in settings.py:
ALLOWED_ORIGINS = ['https://*', 'http://*']
But it didn't help. What am I doing wrong?
ALLOWED_ORIGINS is not related to CSRF token. To fix problems related to your issue, you must specify the following setting for the project in production mode to settings.py module:
CSRF_TRUSTED_ORIGINS = [
'https://subdomain.example.com',
'https://*.blob.com',
...
]
For reading more information related to this topic you can read CSRF_TRUSTED_ORIGINS in django documentation.
I have been trying to setup password reset functionality in DRF using django-rest-auth. Earlier I was getting error TemplateDoesNotExist:registration/password_reset_email.html which I resolved by adding the following code
serializer.py
from rest_auth.serializers import PasswordResetSerializer
from allauth.account.forms import ResetPasswordForm
class PasswordSerializer(PasswordResetSerializer):
password_reset_form_class = ResetPasswordForm
settings.py
REST_AUTH_SERIALIZERS = {
'PASSWORD_RESET_SERIALIZER': 'api.serializers.PasswordSerializer',
}
However, Now I am getting into another issue - "NoReverseMatch: Reverse for 'account_reset_password_from_key' not found. 'account_reset_password_from_key' is not a valid view function or pattern name.". And haven't found any solution or workaround for this.
Any help would be appreciated.
So, finally I got the password reset functionality working. Here is how it goes -
We just need one URL in our urls.py -
urlpatterns = [
url(r'^account/', include('allauth.urls')),
url(r'^rest-auth/', include('rest_auth.urls')),
# This is the only URL required for BASIC password reset functionality.
# This URL creates the confirmation link which is sent via e-mail. All of the rest
# password reset features get their reverse lookup via django-allauth and django-rest-auth.
url(r'^password-reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', TemplateView.as_view(), name='password_reset_confirm'),
url(r'^rest-auth/registration/account-confirm-email/(?P<key>[-:\w]+)/$', allauthemailconfirmation,
name="account_confirm_email"),
url(r'^rest-auth/registration/', include('rest_auth.registration.urls'), name='account_signup'),
]
Using this URL configuration raised TemplateDoesNotExist at /api/rest-auth/password/reset/ error first. After a lot of debugging, I found that the issue was raised for the template - registration/password_reset_email.html which resides under the Django Admin's template directory. This happened due to another Django app that I was using and it had disabled the django admin app.
So, adding 'django.contrib.admin' under INSTALLED_APPS and removing the serializers resolved the issue.
I hope this resolves issue for others as well.
PS: Debugger is your best friend. ;)
I'm writing some API functionality for my project using Python 3.4 and Django 1.6.
All functionality works fine, but I want execute one function for all that kind of requests.
For Example: I have following urls.py file in my API application in Django project
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^getposts', 'Postigs.views.get_posts', name='getPosts'),
url(r'^addpost', 'Postigs.views.add_post', name='addPost'),
url(r'^addcomment', 'Postigs.views.add_comment', name='addComment'),
)
And views.py for that URL requests handling.
So is it possible to execute some function for Example:
def pre_execute(request):
do_something_before_view_function()
I've worked before with many PHP frameworks , there are always some pre_execute() function ... also I've worked with ASP.NET MVC , Node.js Express.js , and all have that function which is firing before request action.
I don't believe that Django didn't have it , but I can't find how implement that functionality.
Thanks.
Middlewares are what you want: https://docs.djangoproject.com/en/dev/topics/http/middleware/
example middleware: https://github.com/django/django/blob/master/django/middleware/common.py
Like iskorum mentioned above, Middlewares is the answer. Or there is also a chance that you are looking for View Decorators. Here is the link https://docs.djangoproject.com/en/dev/topics/http/decorators/
I am writing a simple Django app - say, called base - which has a few models. I am using Django's built-in admin site to manipulate the app's data. The admin is accessible via the default ^admin/ URL pattern.
Aside from Django's default INSTALLED_APPS (minus django.contrib.sites), base is the only app installed in my project. Is there any way to remove base/ from the URL, such that I can access base's models by simply using a path such as /admin/model/ instead of /admin/base/model/?
I would ideally like django.contrib.auth's models to still be accessible via /admin/auth/.
If you don't want base in the URL, don't put it there. It's not there unless you have specifically asked it to be. Just create your URLs without that prefix.
Edit Apologies, I misread your question: I thought you were asking about your app's own views, not the sub-sections with admin.
This is tricky. One way of doing it would be to use the hooks for adding URLs to the base AdminSite as described in the docs. You will probably need to copy the code from the ModelAdmin.get_urls method and hard-code the model name, since there won't be a way of doing that automatically.
Customizing or overriding your default Django admin site is quite easy. Here's the Django documentation on this. The following is an example of overriding the default admin site.
Create an admin.py in your Django project directory (if it's not there yet). Subclass the AdminSite.
To remove the 'appname' from the admin URLs override the get_urls() function:
# myproject/admin.py
from django.contrib import admin
class MyAdminSite(admin.AdminSite):
def get_urls(self):
urlpatterns = super().get_urls()
for model, model_admin in self._registry.items():
urlpatterns += [
path('%s/' % (model._meta.model_name), include(model_admin.urls)),
]
return urlpatterns
Creae an apps.py in your project directory (if it's not there yet):
# myproject/admin.py
from django.contrib.admin.apps import AdminConfig
class MyAdminConfig(AdminConfig):
default_site = 'myproject.admin.MyAdminSite'
Register this in your settings.py:
INSTALLED_APPS = [
...
'myproject.apps.MyAdminConfig', # replaces 'django.contrib.admin'
...
]
I have the following structure (Django 1.4):
containing_dir/
myproject/
myapp1/
myapp2/
myapp3/
myproject, myapp1, myapp2, and myapp3 all have init.py, so they're all modules.
In manage.py (under containing_dir) I have os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
in myproject.settings i define:
[..]
ROOT_URLCONF = 'myproject.urls'
INSTALLED_APPS = (
[..]
'myproject.myapp1',
'myproject.myapp2',
'myproject.myapp3',
)
[..]
In myapp1.urls.py I define:
urlpatterns = patterns('myapp1',
url(r'^agent/$', 'views.agent', name='agent')
)
and I try to import it in myproject.urls I try to import myapp1 urls like this:
(r'^myapp1/', include('myproject.myapp1.urls'))
but whenever I try lo load localhost:8000/myapp1/agent I get
Exception Value: No module named myapp1
I think thrown from withing myapp1.urls
Any help? thanks
You must have a
__init__.py
file inside your "myproject" directory. When you say:
(r'^myapp1/', include('myproject.myapp1.urls'))
you are saying "myproject" (as well as myapp1) is a python packege.
In myproject.settings make following changes :
INSTALLED_APPS = (
[..]
'myapp1',
'myapp2',
'myapp3',
)
Try:
urlpatterns = [
...
url(r'^app_name/', include('app_name.urls', namespace='project_name'))
...
]
Does ROOT_URLCONF need to point to myproject.urls?
If you place your apps inside of myproject you need to use the proper view prefix.
urlpatterns = patterns('myproject.myapp1',
...
To solve this issue just select "myproject" directory in PyCharm and set this as a source root.
Your project don't know from which root it has to search for given app.
It fixed the issue for me.
Thank you.
Recently, In new versions of Django introduces path(route, view, kwargs=None, name=None) instead of old url() regular expression pattern.
You must have __init__.py file in app folders to recognize it as a package by django project i.e myproject
Django project i.e. myproject urls.py file must be updated to include examples like:
path('', include('django_app.urls'))
path('url_extension/', include('django_another_app.urls'))
Above example includes two apps urls in it. One is without adding any extension to path in url and another is with extension to path in current url.
Also, Do not forget to add django apps in INSTALLED_APPS in settings.py file to recognise it as app by django project something like this.
ROOT_URLCONF = 'myproject.urls'
INSTALLED_APPS = [
...
django_app,
django_another_app
...
]
For more information look at documentation.