django-cms: reverse url to an/another apphook - multilingual - python

I have two apphooks (on a multilingual page) and need create one url with url reverse to the other apphook, but it gives me a
NoReverseMatch
Error.
Any ideas how to fix it?
Django CMS version: 2.4.3
Django version 1.5.5
These are my apphook files of one (working) apphook, the other one is quite similar.
cms_app.py:
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
class ProjectsAppHook(CMSApp):
name = _("Projects")
urls = ["projects.urls"]
apphook_pool.register(ProjectsAppHook)
views.py:
def projectsCategoryOverview(request):
projectCategories=ProjectCategory.objects.all().order_by('name').select_related()
#return render(request,'projectCategoryOverview.html', {'projectcategories': projectCategories})
return render_to_response('projectCategoryOverview.html',
{'projectcategories': projectCategories},
context_instance=RequestContext(request))

ok I'v found the problem.
I haven't created the page to which it should link to in the language the source page was displayed.

Related

Django Admin template override

I am following the tutorial on django website to create my first django app.
Now I am stuck trying to override Django Admin template.
My project directory is this:
First I tried creating a new admin template in the surveys app. It works.
Then, I tried with the override function. For this I created at surveys/admin.py the following code:
from django.contrib.admin import AdminSite
from django.utils.translation import ugettext_lazy
class SurveysAdminSite(AdminSite):
site_header = ugettext_lazy('Test administration')
surveys_admin_site = SurveysAdminSite()
And add to computationalMarketing/urls.py the following:
from .admin import surveys_admin_site
urlpatterns = [
path('admin/', surveys_admin_site.urls, name='admin'),
]
It doesn't work, so I search, and tried something different. Add this same previous code to surveys/urls.py. Neither works. Then I rollback the changes to save the code to computationalMarketing/urls.py, but this time I changed the code from surveys/admin.py to computationalMarketing/admin.py (in fact I created the file because it doesn't exists.
It works and now I see the site header that I want, but I get You don't have permission to edit anything. I have seen that is something related with superuser creation, but until now I was able to admin my surveys app without problem, so I believe in some solution related with override properly the admin.py at surveys app
Does anybody knows why this does not works as expected?
You are overriding the complete admin site. You may want to override only specific templates and keep using the default admin site.
A first approach to solve your problem is to add models to your admin site:
surveys/admin.py:
from django.contrib.admin import AdminSite
from django.utils.translation import ugettext_lazy
from surveys.models import OneModel, OtherModel
class SurveysAdminSite(AdminSite):
site_header = ugettext_lazy('Test administration')
surveys_admin_site = SurveysAdminSite()
surveys_admin_site.register(OneModel)
surveys_admin_site.register(OtherModel)
And maybe use ModelAdmin objects to add advanced behavior.
Hope this helps.

save() doesn't work in Mongoengine

I'm trying to perform a simple insert operation using Mongoengine and Django.
Regarding my project structure simply I have a project, AProject and an app, AnApp. I have a running mongo in a remote machine with an IP of X.X.X.X. I am able to insert document using Robomongo in it.
I have removed the default Database configuration part of the settings.py located inside the AProject directory. The newly added lines are shown below:
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
import mongoengine
# ----------- MongoDB stuff
from mongoengine import register_connection
register_connection(alias='default', name='AProject', host='X.X.X.X')
# ----------
Now let me show the models.py and the views.py located inside AnApp.
models.py
from mongoengine import Document, StringField
class Confession(Document):
confession = StringField(required=True)
views.py
from django.http import HttpResponse
from models import Confession
from mongoengine import connect
def index(request):
connect('HacettepeItiraf', alias='default')
confession = Confession()
confession.confession = 'First confession from the API'
print(confession.confession + ' Printable') # The output is --First confession from the API Printable--
print(confession.save()) # The output is --Confession object--
return HttpResponse(request)
The urls.py located inside AProject is simply as below:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^confessions/', include('confession.urls')),
url(r'^admin/', admin.site.urls),
]
When I enter http://127.0.0.1:10000/confessions/ I see a blank screen which I expect. However there is nothing saved from the API. I get the expected output except Confession object.
How can I solve this problem?
EDIT:
I found the concrete proof that currently MongoEngine's support for Django is unstable and it is corresponding to Django version 1.9:
MongoEngine documentation on Django support states:
Django support has been split from the main MongoEngine repository. The legacy Django extension may be found bundled with the 0.9 release of MongoEngine.
and
6.1. Help Wanted!
The MongoEngine team is looking for help contributing and maintaining a new Django extension for MongoEngine! If you have Django experience and would like to help contribute to the project, please get in touch on the mailing list or by simply contributing on GitHub.
Which leads to this repo, where the following is stated:
THIS IS UNSTABLE PROJECT, IF YOU WANT TO USE IT - FIX WHAT YOU NEED
Right now we're targeting to get things working on Django 1.9
So it may be possible that it cannot play well with Django at this state or with your version and thus the problem occurs.
Initial attempt, leaving it here for legacy reasons.
I believe that the problem occurs on how you are initializing your object, although I do not have a set up to test this theory.
It is generally considered that is better to make a new object with the .create() method:
def index(request):
connect('HacettepeItiraf', alias='default')
confession = Confession.objects.create(
confession='First confession from the API'
)
print(confession.confession + ' Printable')
confession.save()
return HttpResponse(request)
Have a look at the Django & MongoDB tutorial for more details.
In this tutorial, the supported Django version is not mentioned, but I haven't found concrete proof that MongoDB Engine can or can't play well with Django version > 1.8.
Good luck :)

Django admin - add custom link to change list view

Firstly thanks for taking the time to read my problem
I tried to add a custom button to my admin changeList view, but it always gives me Page not found (404)
This my modelAdmin code:
class MyModelAdmin(admin.ModelAdmin):
class Media:
js = ('admin/js/additional_js.js',)
model = MyModel
def get_urls(self):
urls = super(MyModelAdmin, self).get_urls()
analyze_url = patterns('',
(r'^(?P<pk>\d+)/analyze/$',
self.admin_site.admin_view(self.analyze_view))
)
return analyze_url + urls
def analyze_view(self, request, pk):
# some code here
HttpResponseRedirect(
reverse('admin:myapp_MyModel_change', args=(pk,))
)
My jQuery code for adding custom link to change list view:
(function($) {
$(document).ready(function($) {
$(".object-tools").append('<li>Analyze</li>');
});
})(django.jQuery);
when I click my custom link it gives me this:
MyModel object with primary key '3/change/analyze' does not exist.
I see that the link does not point to the view
Can someone help me fix this issue.
Thanks
In Django 1.9, the admin change url has changed to /admin/<app>/<model>/<pk>/change/ (release notes).
Therefore, it doesn't make sense to link to href="analyze/" in your html. The relative url is treated as /admin/<app>/<model>/3/change/analyze, not /admin/<app>/<model>/3/analyze as you expect.
You can probably fix the problem by changing the link to:
<a href="../analyze/" ...
Ideally, it would be better to reverse the url rather than having a relative link. I think this would make the code less fragile.
Since you are using Django 1.9, you can update your code to use a list rather than patterns:
from django.conf.urls import url
analyze_url = [
url(r'^(?P<pk>\d+)/analyze/$', self.admin_site.admin_view(self.analyze_view)),
]

Django: Django-Rest-Framework gives Attribution error (pagination)

I'm trying to create migrations of a project which uses Rest Framework pagination.
But I'm getting error as Attribution error: 'module' object has no attribute BasePaginationSerializer. I have tried uninstalling-resinstalling the said versions of Python, Django and RestFramework. But I still get that error.
Here's the screenshot of terminal showing error.
Here's a chunk of the code present in paginator.py
import urlparse
from django.core.paginator import EmptyPage, Page, PageNotAnInteger, Paginator
from django.utils.http import urlencode
from rest_framework import serializers, pagination
class CustomPaginationSerializer(pagination.BasePaginationSerializer):#Here it shows the error.
meta = MetaSerializer(source='*')
results_field = 'objects'
Can someone help me out in getting this issue resolved?
Info:
- Here's the project which I'm trying to build. https://github.com/mozilla/zamboni
I'm using Ubuntu 15.10
Python - 2.7.10
Django - 1.8.7
Django Rest Framework doesn't provide anything like BasePaginationSerializer, that's why you're getting an error - because it doesn't exist. You probably want to use BasePagination

Django, Testing Redirects to External Pages

I have a routing rule in my Django app for downloads that redirect to a external CDN. I am now writing tests for my app, and I want to test that the route does successfully redirect to the configured url in my Django settings. Here is a simplified example that should help explain what I'm trying to do:
from django.test import SimpleTestCase
from django.test.client import Client
from django.conf import settings
class MyTestCase(SimpleTestCase):
def setUp(self):
self.client = Client()
def test_download(self):
response = self.client.get('/download/mac/')
self.assertRedirects(response, settings.URLS.get('mac'))
Now this doesn't work, the redirect gets a 404 even though when I print settings.DOWNLOAD_URL in this method it is correct, and a copy/paste into the browser proves it works. I started to look into why it wasn't working, and I noticed this in the Django source code:
Note that assertRedirects won't work for external links since it uses
TestClient to do a request.
So then, how does one test these redirects? I'm not looking for anything super fancy, what I expect to check is the response's status_code and location. I saw that response has a follow parameter, and tried something like this, but it still didn't work:
def test_download(self):
response = self.client.get('/download/mac/', follow=True)
self.assertEqual(response.status_code, 302)
self.assertEqual(response['Location'], settings.URLS.get('mac')
It was requested that I include the relevant parts from my urls.py and views.py, here they are:
# urls.py
from django.conf.urls import patterns, url
urlpatterns = patterns('myapp.views',
url(r'^download/(?P<platform>\w+)/$', 'download_app', name='download'),
)
#views.py
from django.conf import settings
from django.shortcuts import redirect
from django.http import Http404
def download_app(request, platform):
if platform in settings.URLS:
return redirect( settings.URLS.get(platform) )
else:
raise Http404
Any help in solving this would be much appreciated. Thanks in advance.
Probably the original poster has solved his problems and moved on long ago, but the solution here is to not specify follow=True as he did in the alternative proposal that didn't work either.
The following will simply check that the view being tested redirects as expected, without relying on the external resources.
def test_download(self):
response = self.client.get('/download/mac')
self.assertEqual(response.status_code, 302)
self.assertEqual(response['Location'], 'http://external/resource')
In Django 1.7 assertRedirect got a new parameter fetch_redirect_response which can be set to False to get the same effect, but I haven't tried it myself.

Categories