Re: [mezzanine-users] Extending Displayable Model, Views

2017-07-07 Thread marcusguttenplan
It's an ImportError (ImportError at /news Could not import 'news'. The path 
must be fully qualified.) and trying to follow the traceback have narrowed 
it down to either how I am importing the model in my views (if that's even 
necessary) or to how I am calling the defined `news` view in the app's 
urlconf.

views.py:
from .models import News, NewsCategory

def news(request, slug):
return HttpResponse('Test')

urls.py
from .models import News
import views

urlpatterns = [
'news.views',
url("^%s(?P.*)%s$" % _slashes, "news", name="news"),
]

And the root urls.py pattern, with `kdi` being the name of my app:
url(r'^news/',include('kdi.urls')),


Slowly trying to reverse engineer the blog's views and urls to get to a 
pared down version, but there is a lot going on. Because my custom 
Displayable model does not need to be Ownable, there is no need to be any 
calling of the User model or referencing the request.user or author; there 
is also no need for a Detail view or feeds, or much filtering at all. That 
leaves only date and category in the pared views.py. That leaves something 
like this:

def news(request, tag=None, year=None, month=None, category=None, 
template="blog/blog_post_list.html", extra_context=None):

templates = []
blog_posts = BlogPost.objects.published(for_user=request.user)
if tag is not None:
tag = get_object_or_404(Keyword, slug=tag)
blog_posts = blog_posts.filter(keywords__keyword=tag)
if year is not None:
blog_posts = blog_posts.filter(publish_date__year=year)
if month is not None:
blog_posts = blog_posts.filter(publish_date__month=month)
try:
month = _(month_name[int(month)])
except IndexError:
raise Http404()
if category is not None:
category = get_object_or_404(BlogCategory, slug=category)
blog_posts = blog_posts.filter(categories=category)
templates.append(u"templates/blog_post_list_%s.html" %
  str(category.slug))

prefetch = ("categories", "keywords__keyword")
blog_posts = 
blog_posts.select_related("user").prefetch_related(*prefetch)
blog_posts = paginate(blog_posts, request.GET.get("page", 1),
  settings.BLOG_POST_PER_PAGE,
  settings.MAX_PAGING_LINKS)
context = {"blog_posts": blog_posts, "year": year, "month": month,
   "tag": tag, "category": category, "author": author}
context.update(extra_context or {})
templates.append(template)
return TemplateResponse(request, templates, context)

And this is where I have some questions. Going line by line, `
BlogPost.objects.published(for_user=request.user)`, would removing the 
`request.user` return all of the published objects, in this case 
News.objects?

Filtering by tags, dates, and categories makes sense, until we reach 
select_related `blog_posts = 
blog_posts.select_related("user").prefetch_related(*prefetch)`. Because 
this is focused on the user which is not necessary, is it possible to just 
prefetch all posts with the custom model, or to select_related based on the 
category? 

Pagination is also not necessary for this use case, so is it possible to 
remove entirely `blog_posts = paginate(blog_posts, request.GET.get("page", 
1), settings.BLOG_POST_PER_PAGE, settings.MAX_PAGING_LINKS)`? The hacky 
solution would be to keep this bit of code, and then set 
`BLOG_POST_PER_PAGE` to a large number in settings.

And then in the `context` dict, is it safe to remove unneeded key/val 
pairs? Specifically `author`? Because there is so much heavy lifting going 
on with the blog that's not needed here, I'm afraid of breakage.

Now looking at simplifying urlpatterns so that it will successfully direct 
to the News model's get_absolute_url + the object's slug (something like 
 http://x/news/slug):
'news.views',
url("^%s(?P.*)%s$" % _slashes, "news", name="news"),

Is this structured correctly? Should the slug come after the absolute url? 
Something like `url("^news/(?P.*)%s$" % _slashes, "news", name="news")
`?

Sorry to ask so many questions, and thank you for your help! I've been a 
bit intimidated by Django's urls.py and views.py for a while, and have 
managed to do almost all of my logic through custom models and custom 
templatetags. Even just learning the correct things to google helps a ton, 
and I appreciate any help at all!




On Friday, July 7, 2017 at 8:09:00 AM UTC-7, Eduardo Rivas wrote:
>
> Could you share the error message you’re getting?
>

-- 
You received this message because you are subscribed to the Google Groups 
"Mezzanine Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to mezzanine-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


RE: [mezzanine-users] Extending Displayable Model, Views

2017-07-07 Thread Eduardo Rivas
Could you share the error message you’re getting?

-- 
You received this message because you are subscribed to the Google Groups 
"Mezzanine Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to mezzanine-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: [mezzanine-users] Extending Displayable Model, Views

2017-07-06 Thread marcusguttenplan
Getting closer! Imported into root with 
url(r'^news/',include('app.urls')),

Throwing a new error about the path not being fully qualified, but progress.


On Thursday, July 6, 2017 at 9:38:22 PM UTC-7, marcusgu...@gmail.com wrote:
>
> I originally put that url pattern into the root conf, but it wasn't 
> working there either. Embarrassingly, I'm not sure how to import my app's 
> conf or define a new pattern that would point to it.
>
> This is what the root urls.py looks like:
> from __future__ import unicode_literals
>
> from django.conf.urls import include, url
> from django.conf.urls.i18n import i18n_patterns
> from django.contrib import admin
> from django.views.i18n import set_language
>
> from mezzanine.core.views import direct_to_template
> from mezzanine.conf import settings
>
>
> admin.autodiscover()
>
> urlpatterns = i18n_patterns(
> # Change the admin prefix here to use an alternate URL for the
> # admin interface, which would be marginally more secure.
> url("^admin/", include(admin.site.urls)),
> )
>
> if settings.USE_MODELTRANSLATION:
> urlpatterns += [
> url('^i18n/$', set_language, name='set_language'),
> ]
>
> urlpatterns += [
>
> url("^$", direct_to_template, {"template": "index.html"}, name="home"),
>
> # REST API URLs
> url("^api/", include("mezzanine_api.urls")),
>
> url("^", include("mezzanine.urls")),
> ]
>
> handler404 = "mezzanine.core.views.page_not_found"
> handler500 = "mezzanine.core.views.server_error"
>
>
>
>
> On Thursday, July 6, 2017 at 9:13:26 PM UTC-7, Eduardo Rivas wrote:
>>
>> I see you created a urlconf for your app, but have you added it to your 
>> root urls.py? If so, is if above or below Mezzanine's catch-all pattern? 
>>
>> On Jul 6, 2017 9:12 PM,  wrote:
>>
>>> Hi, thanks for such a great resource! I have googled around for a few 
>>> days and have made some headway this problem, but have hit a wall. I'm 
>>> trying to use the Displayable model to create an easy way to add news 
>>> stories and have them displayed as a simple list view, which is very 
>>> similar behavior to the blog app. If there is a better solution using a 
>>> ForeignKey, please point me in the right direction!
>>>
>>> I read an older post 
>>> 
>>>  about 
>>> creating a new Displayable, and have used Mezzanine's source code to 
>>> successfully extend the Displayable model and have it appear correctly in 
>>> the admin. The issue now is that I can't seem to get the views (views.py) 
>>> and url patterns to work. When clicked "view on site" from the admin, the 
>>> url seems to grab the model's slug ("news"), but ends up linking to 
>>> http://localhost:8000/en/admin//news/%28u/, and doesn't work 
>>> linking directly to the actual item's slug. Exploring the source code for 
>>> Mezzanine's blog's urls and views, I'm unsure how to correctly refactor. I 
>>> understand that I will need to create my own templates to act as 
>>> blog_post_list.html 
>>> and blog_post_detail.html, but don't know how to create the super basic 
>>> views to point to them.
>>>
>>> models.py:
>>> class News(Displayable, RichText):
>>>
>>> pagetitle = models.CharField('Title', max_length=255, blank=True)
>>> url = models.CharField('Link', max_length=255, blank=True)
>>> summary = models.CharField('Summary', max_length=255, blank=True)
>>> date = models.DateField(_("Date"), default=datetime.date.today)
>>> categories = models.ManyToManyField("NewsCategory",
>>> verbose_name=_("Categories 
>>> (Magazine, Award, etc.)"),
>>> blank=True, 
>>> related_name="newsitems")
>>> related_news = models.ManyToManyField("self",
>>>  verbose_name=_("Related News"), 
>>> blank=True)
>>>
>>> class Meta:
>>> verbose_name = _("News Item")
>>> verbose_name_plural = _("News Items")
>>>
>>> def get_absolute_url(self):
>>> url_name = 'news'
>>> kwargs = {
>>> 'slug': self.slug,
>>> }
>>> return (url_name, (), kwargs)
>>>
>>>
>>> class NewsCategory(Slugged):
>>> """
>>> A category for grouping news items into a series.
>>> """
>>>
>>> class Meta:
>>> verbose_name = _("News Category")
>>> verbose_name_plural = _("News Categories")
>>> ordering = ("title",)
>>>
>>> @models.permalink
>>> def get_absolute_url(self):
>>> return ("news_item_list_category", (), {"category": self.slug})
>>>
>>> admin.py
>>> news_fieldsets = deepcopy(DisplayableAdmin.fieldsets)
>>> news_fieldsets[0][1]["fields"].insert(1, "categories")
>>> news_fieldsets[0][1]["fields"].extend(["pagetitle", "url", "summary", 
>>> "date"])
>>> news_fieldsets = list(news_fieldsets)
>>> news_fieldsets.insert(1, (_("Other News"), {
>>> "classes": ("collapse-closed",),
>>> "fields": ("related_news",)}

Re: [mezzanine-users] Extending Displayable Model, Views

2017-07-06 Thread marcusguttenplan
I originally put that url pattern into the root conf, but it wasn't working 
there either. Embarrassingly, I'm not sure how to import my app's conf or 
define a new pattern that would point to it.

This is what the root urls.py looks like:
from __future__ import unicode_literals

from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.views.i18n import set_language

from mezzanine.core.views import direct_to_template
from mezzanine.conf import settings


admin.autodiscover()

urlpatterns = i18n_patterns(
# Change the admin prefix here to use an alternate URL for the
# admin interface, which would be marginally more secure.
url("^admin/", include(admin.site.urls)),
)

if settings.USE_MODELTRANSLATION:
urlpatterns += [
url('^i18n/$', set_language, name='set_language'),
]

urlpatterns += [

url("^$", direct_to_template, {"template": "index.html"}, name="home"),

# REST API URLs
url("^api/", include("mezzanine_api.urls")),

url("^", include("mezzanine.urls")),
]

handler404 = "mezzanine.core.views.page_not_found"
handler500 = "mezzanine.core.views.server_error"




On Thursday, July 6, 2017 at 9:13:26 PM UTC-7, Eduardo Rivas wrote:
>
> I see you created a urlconf for your app, but have you added it to your 
> root urls.py? If so, is if above or below Mezzanine's catch-all pattern? 
>
> On Jul 6, 2017 9:12 PM, > wrote:
>
>> Hi, thanks for such a great resource! I have googled around for a few 
>> days and have made some headway this problem, but have hit a wall. I'm 
>> trying to use the Displayable model to create an easy way to add news 
>> stories and have them displayed as a simple list view, which is very 
>> similar behavior to the blog app. If there is a better solution using a 
>> ForeignKey, please point me in the right direction!
>>
>> I read an older post 
>> 
>>  about 
>> creating a new Displayable, and have used Mezzanine's source code to 
>> successfully extend the Displayable model and have it appear correctly in 
>> the admin. The issue now is that I can't seem to get the views (views.py) 
>> and url patterns to work. When clicked "view on site" from the admin, the 
>> url seems to grab the model's slug ("news"), but ends up linking to 
>> http://localhost:8000/en/admin//news/%28u/, and doesn't work 
>> linking directly to the actual item's slug. Exploring the source code for 
>> Mezzanine's blog's urls and views, I'm unsure how to correctly refactor. I 
>> understand that I will need to create my own templates to act as 
>> blog_post_list.html 
>> and blog_post_detail.html, but don't know how to create the super basic 
>> views to point to them.
>>
>> models.py:
>> class News(Displayable, RichText):
>>
>> pagetitle = models.CharField('Title', max_length=255, blank=True)
>> url = models.CharField('Link', max_length=255, blank=True)
>> summary = models.CharField('Summary', max_length=255, blank=True)
>> date = models.DateField(_("Date"), default=datetime.date.today)
>> categories = models.ManyToManyField("NewsCategory",
>> verbose_name=_("Categories 
>> (Magazine, Award, etc.)"),
>> blank=True, 
>> related_name="newsitems")
>> related_news = models.ManyToManyField("self",
>>  verbose_name=_("Related News"), 
>> blank=True)
>>
>> class Meta:
>> verbose_name = _("News Item")
>> verbose_name_plural = _("News Items")
>>
>> def get_absolute_url(self):
>> url_name = 'news'
>> kwargs = {
>> 'slug': self.slug,
>> }
>> return (url_name, (), kwargs)
>>
>>
>> class NewsCategory(Slugged):
>> """
>> A category for grouping news items into a series.
>> """
>>
>> class Meta:
>> verbose_name = _("News Category")
>> verbose_name_plural = _("News Categories")
>> ordering = ("title",)
>>
>> @models.permalink
>> def get_absolute_url(self):
>> return ("news_item_list_category", (), {"category": self.slug})
>>
>> admin.py
>> news_fieldsets = deepcopy(DisplayableAdmin.fieldsets)
>> news_fieldsets[0][1]["fields"].insert(1, "categories")
>> news_fieldsets[0][1]["fields"].extend(["pagetitle", "url", "summary", 
>> "date"])
>> news_fieldsets = list(news_fieldsets)
>> news_fieldsets.insert(1, (_("Other News"), {
>> "classes": ("collapse-closed",),
>> "fields": ("related_news",)}))
>> news_list_filter = deepcopy(DisplayableAdmin.list_filter) + 
>> ("categories",)
>>
>>
>> class NewsAdmin(DisplayableAdmin):
>> """
>> Admin class for news posts.
>> """
>>
>> fieldsets = news_fieldsets
>> # list_display = news_list_display
>> list_filter = news_list_filter
>> filter_horizontal = ("categories", "related_news",)
>>
>> def save_form(sel

Re: [mezzanine-users] Extending Displayable Model, Views

2017-07-06 Thread Eduardo Rivas
I see you created a urlconf for your app, but have you added it to your
root urls.py? If so, is if above or below Mezzanine's catch-all pattern?

On Jul 6, 2017 9:12 PM,  wrote:

> Hi, thanks for such a great resource! I have googled around for a few days
> and have made some headway this problem, but have hit a wall. I'm trying to
> use the Displayable model to create an easy way to add news stories and
> have them displayed as a simple list view, which is very similar behavior
> to the blog app. If there is a better solution using a ForeignKey, please
> point me in the right direction!
>
> I read an older post
> 
>  about
> creating a new Displayable, and have used Mezzanine's source code to
> successfully extend the Displayable model and have it appear correctly in
> the admin. The issue now is that I can't seem to get the views (views.py)
> and url patterns to work. When clicked "view on site" from the admin, the
> url seems to grab the model's slug ("news"), but ends up linking to
> http://localhost:8000/en/admin//news/%28u/, and doesn't work
> linking directly to the actual item's slug. Exploring the source code for
> Mezzanine's blog's urls and views, I'm unsure how to correctly refactor. I
> understand that I will need to create my own templates to act as 
> blog_post_list.html
> and blog_post_detail.html, but don't know how to create the super basic
> views to point to them.
>
> models.py:
> class News(Displayable, RichText):
>
> pagetitle = models.CharField('Title', max_length=255, blank=True)
> url = models.CharField('Link', max_length=255, blank=True)
> summary = models.CharField('Summary', max_length=255, blank=True)
> date = models.DateField(_("Date"), default=datetime.date.today)
> categories = models.ManyToManyField("NewsCategory",
> verbose_name=_("Categories
> (Magazine, Award, etc.)"),
> blank=True,
> related_name="newsitems")
> related_news = models.ManyToManyField("self",
>  verbose_name=_("Related News"),
> blank=True)
>
> class Meta:
> verbose_name = _("News Item")
> verbose_name_plural = _("News Items")
>
> def get_absolute_url(self):
> url_name = 'news'
> kwargs = {
> 'slug': self.slug,
> }
> return (url_name, (), kwargs)
>
>
> class NewsCategory(Slugged):
> """
> A category for grouping news items into a series.
> """
>
> class Meta:
> verbose_name = _("News Category")
> verbose_name_plural = _("News Categories")
> ordering = ("title",)
>
> @models.permalink
> def get_absolute_url(self):
> return ("news_item_list_category", (), {"category": self.slug})
>
> admin.py
> news_fieldsets = deepcopy(DisplayableAdmin.fieldsets)
> news_fieldsets[0][1]["fields"].insert(1, "categories")
> news_fieldsets[0][1]["fields"].extend(["pagetitle", "url", "summary",
> "date"])
> news_fieldsets = list(news_fieldsets)
> news_fieldsets.insert(1, (_("Other News"), {
> "classes": ("collapse-closed",),
> "fields": ("related_news",)}))
> news_list_filter = deepcopy(DisplayableAdmin.list_filter) +
> ("categories",)
>
>
> class NewsAdmin(DisplayableAdmin):
> """
> Admin class for news posts.
> """
>
> fieldsets = news_fieldsets
> # list_display = news_list_display
> list_filter = news_list_filter
> filter_horizontal = ("categories", "related_news",)
>
> def save_form(self, request, form, change):
> """
> Super class ordering is important here - user must get saved first.
> """
> DisplayableAdmin.save_form(self, request, form, change)
> return DisplayableAdmin.save_form(self, request, form, change)
>
> class NewsCategoryAdmin(BaseTranslationModelAdmin):
> """
> Admin class for blog categories. Hides itself from the admin menu
> unless explicitly specified.
> """
>
> fieldsets = ((None, {"fields": ("title",)}),)
>
> def has_module_permission(self, request):
> """
> Hide from the admin menu unless explicitly set in
> ``ADMIN_MENU_ORDER``.
> """
> for (name, items) in settings.ADMIN_MENU_ORDER:
> if "blog.BlogCategory" in items:
> return True
> return False
>
>
> admin.site.register(News, NewsAdmin)
> admin.site.register(NewsCategory, NewsCategoryAdmin)
>
> urls.py:
> from .models import News
> import .views
>
> _slashes = (
> "/" if settings.BLOG_SLUG else "",
> "/" if settings.APPEND_SLASH else "",
> )
>
> urlpatterns = patterns(
> 'news.views',
> url("^%s(?P.*)%s$" % _slashes, "news", name="news"),
> )
>
> views.py:
> from django.shortcuts import render
>
> def news(request, slug):
> return HttpResponse('Test')
>
> The view is currently not even returning "Test." Any direction at all
> wo