Django url namespaces giving errors - django-templates

I am new to the django framework. I currently started learning from an online video tutorial and I came across some errors. I have an app called groups which has two separate view files namely company and family. Due to that I have my groups/url file as this:
from django.urls import path, include, re_path
from . views import company
from . views import family
app_name = 'groups'
company_patterns = [
path('create/', company.Create.as_view(), name='create'),
re_path(r'^edit/(?P<slug>\w+)/$', company.Update.as_view(), name='update'),
path('<str:slug>/', company.Details.as_view(), name='detail'),
]
family_patterns = [
path('create/', family.Create.as_view(), name='create'),
path('edit/<str:slug>/', family.Update.as_view(), name='update'),
path('<str:slug>/', family.Details.as_view(), name='detail'),
]
urlpatterns = [
path('companies/', include(company_patterns, namespace='companies')),
path('families/', include(family_patterns, namespace='families')),
]
But anytime I run the application from my dashboard template. I get this error:
'Specifying a namespace in include() without providing an app_name '
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.
Please, can anyone assist me with further explanation and solution? thank you

define app_name in another urls.py file

Related

Testing pages with streamfields in Wagtail

I'm parsing HTML in a StreamField's richtext element via get_context, and want to be able to test that the context I've made contains the relevant modifications. But I'm really struggling to create a mock/stub that has a populated StreamField.
I'm looking at https://docs.wagtail.io/en/stable/advanced_topics/testing.html but need to do more than just test whether creation succeeds and the rich_text function etc. don't seem to output in the right format for other matters (like appending to the body attribute); I've had a little success with making fixtures via dumpdata but they're breaking other tests (presumably due to making the database inconsistent or something)
Are there any good examples out there of tests pre-populating a StreamField?
... turns out it's remarkably simple, once it's been pointed out to you!
Once you've got your page (where pagetype is the module name and PageName the class name)
from modules.pagetype.models import PageName
page = PageName()
add some JSON to the StreamField object (here called body)
import json
page.body = json.dumps(
[
{"type": "rich_text", "value": "<h2>Hello, World!</h2>"},
{"type": "rich_text", "value": "<h4>Here's another field</h4>"}
]
)
You may then want to then publish the post and look at the output.
from django.test import Client
page.save_revision().publish()
rv = Client().get(page.url)
assert "something_about_my_output_html" in str(rv.rendered_content)

Reference mongoose schema definition in swagger-jsdoc?

I've built a express.js project with a mongoDB backend using mongoose.
Since I've created the mongoose models via mongoose schemas, I was wondering if it is possible to reference to the mongoose schema definition instead of re-typing all it's contents.
I'm currently using swagger-jsdoc.
Thanks and best regards
[/EDIT]
I understand, that mongoose-to-swagger basically performs this task.
However, I have no clue how I can reference to such a generated swagger schema within my swagger-jsdoc code comments.
I had the exact same issue and how i resolved it was i made a file called swaggerSchemas where i exported all the schemas like in the following example:
export default {
user: m2s(User),
};
Where User is the mongoose model.
And finally inside your swagger jsdoc options you need something like the following:
const options = {
definition: {
...
components: {
schemas: swaggerSchemas,
},
...
},
...
};

Wagtail: Extend page model

I have created in the past multiple pages for Wagtail.
Example:
class PlainPage(Page):
body = StreamField(BasicStreamBlock, null=True, blank=True)
content_panels = Page.content_panels + [
StreamFieldPanel('body'),
]
Now I would like to an extend all this pages by giving them the possibility to set them to no-index.
For this reason I would like to add a boolean field to the promote_panel.
What would be the best way adding this feature to all pages I have already created?
no_index = models.BooleanField(default=False)
promote_panels = Page.promote_panels + [
FieldPanel('no_index'),
]
What would be the correct Wagtail way, to extend all my Page classes with this code?
Using Django's Class Mixins, it is possible to add fields to all existing models without too much hassle.
1. Create a Mixin
First - create a new CustomPageMixin (name this whatever you want) that extends the Page model and has the meta abstract=True set.
class CustomPageMixin(Page):
class Meta:
abstract=True
no_index = models.BooleanField(default=False)
# adding to content_panels on other pages will need to use THIS promote_panels
# e.g. promote_panels = CustomPageMixin.promote_panels + [...]
promote_panels = Page.promote_panels + [
FieldPanel('no_index'),
]
2. Update ALL existing page models
Update all your models in use to use the mixin, instead of extending the Page class, they will actually extend your mixin directly.
from ... import CustomPageMixin
class StandardPage(CustomPageMixin):
#...
class HomePage(CustomPageMixin):
#...
3. Run Migrations
Note: This will add the no_index field to ALL pages that now extend your new mixin.
./manage.py makemigrations
./manage.py migrate
Potential Issues with this approach
This may not be the best way to do this, as it is a bit indirect and hard to understand at first glance.
This does not actually change the Page model fields, so it will only be available when you access the actual specific models' instance via Page.specific
It will be a bit more tricky to use this for special Page types such as AbstractEmailForm.

What is the markdown syntax for .NET Core templating

I have a .NET Core template and wondering how I can hide partial content from markdown file based on the flags set?
As you may see below I tried what I do in CS project files but it didn't work.
README.md
# Steps
- createSolutionFile.ps1
<!--#if (CacheSqlServer)-->
- sql-cache.ps1
1. create database `DistributedCache`
2. create schema `cache`
3. run the script
<!--#endif-->
- user-secrets.ps1
<!--#if (EntityFramework)-->
- scaffold.ps1
- migrate.ps1
<!--#endif-->
- build.ps1
<!--#if (WindowsService)-->
- windows-service.ps1
<!--#endif-->
The templating engine by default only supports these conditional operators only in a certain list of file types, sometimes with varying syntax. You can find that list of files in the source of the orchestrator. As of now, the list does not include Markdown files though, which is why you are not getting any functionality there.
Fortunately, there appears to be a way to configure special custom operations on custom file types inside the template.json, which allows you to define custom operations e.g. for conditional operators.
Adding something like this should work:
"SpecialCustomOperations": {
"**/*.md": {
"operations": [
{
"type": "conditional",
"configuration": {
"if": ["---#if"],
"else": ["---#else"],
"elseif": ["---#elseif", "---#elif"],
"endif": ["---#endif"],
"trim" : "true",
"wholeLine": "true",
}
}
]
}
}
It should allow you to use conditionals like this in your .md files:
# This is an example Markdown
---#if (FooBar)
Foo bar
---#elif (BarBaz)
Bar baz
---#else
Baz qux
---#endif
Note that I used a different syntax here as a single-line based syntax is a lot easier to configure.

Document serialization with Doctrine MongoDB ODM

I'm trying to code a class handling serialization of documents by reading their metadata. I got inspired by this implementation for entities with Doctrine ORM and modified it to match how Doctrine ODM handles documents. Unfortunatly something is not working correctly as one document is never serialized more than once even if it is refered a 2nd time thus resulting on incomplete serialization.
For example, it outputs this (in json) for a user1 (see User document) that belongs to some place1 (see Place document). Then it outputs the place and the users belonging to it where we should see the user1 again but we don't :
{
id: "505cac0d6803fa1e15000004",
login: "user1",
places: [
{
id: "505cac0d6803fa1e15000005",
code: "place1",
users: [
{
id: "505c862c6803fa6812000000",
login: "user2"
}
]
}
]
}
I guess it could be related to something preventing circular references but is there a way around it ?
Also, i'm using this in a ZF2 application, would there be a better way to implement this using the ZF2 Serializer ?
Thanks for your help.
I have a serializer already written for DoctrineODM. You can find it in http://github.com/superdweebie/DoctrineExtensions - look in lib/Sds/DoctrineExtensions/Serializer.
If you are are using zf2, then you might also like http://github.com/superdweebie/DoctrineExtensionsModule, which configures DoctrineExtensions for use in zf2.
To use the Module, install it with composer, as you would any other module. Then add the following to your zf2 config:
'sds' => [
'doctrineExtensions' => [
'extensionConfigs' => [
'Sds\DoctrineExtensions\Serializer' => null,
),
),
),
To get the serializer use:
$serializer = $serivceLocator->get('Sds\DoctrineExtensions\Serializer');
To use the serializer:
$array = $serializer->toArray($document)
$json = $serializer->toJson($document)
$document = $serializer->fromArray($array)
$document = $serializer->fromJson($json)
There are also some extra annotations available to control serialization, if you want to use them:
#Sds\Setter - specify a non standard setter for a property
#Sds\Getter - specify a non standard getter fora property
#Sds\Serializer(#Sds\Ignore) - ignore a property when serializing
It's all still a work in progress, so any comments/improvements would be much appreciated. As you come across issues with these libs, just log them on github and they will get addressed promptly.
Finally a note on serializing embedded documents and referenced documents - embedded documents should be serialized with their parent, while referenced documents should not. This reflects the way data is saved in the db. It also means circular references are not a problem.
Update
I've pushed updates to Sds/DoctrineExtensions/Serializer so that it can now handle references properly. The following three (five) methods have been updated:
toArray/toJson
fromArray/fromJson
applySerializeMetadataToArray
The first two are self explainitory - the last is to allow serialization rules to be applied without having to hydrate db results into documents.
By default references will be serialized to an array like this:
[$ref: 'CollectionName/DocumentId']
The $ref style of referencing is what Mongo uses internally, so it seemed appropriate. The format of the reference is given with the expectation it could be used as a URL to a REST API.
The default behaviour can be overridden by defineing an alternative ReferenceSerializer like this:
/**
* #ODM\ReferenceMany(targetDocument="MyTargetDocument")
* #Sds\Serializer(#Sds\ReferenceSerializer('MyAlternativeSerializer'))
*/
protected $myDocumentProperty;
One alternate ReferenceSerializer is already included with the lib. It is the eager serializer - it will serialize references as if they were embedded documents. It can be used like this:
/**
* #ODM\ReferenceMany(targetDocument="MyTargetDocument")
* #Sds\Serializer(#Sds\ReferenceSerializer('Sds\DoctrineExtensions\Serializer\Reference\Eager'))
*/
protected $myDocumentProperty;
Or an alternate shorthand annotation is provided:
/**
* #ODM\ReferenceMany(targetDocument="MyTargetDocument")
* #Sds\Serializer(#Sds\Eager))
*/
protected $myDocumentProperty;
Alternate ReferenceSerializers must implement Sds\DoctrineExtensions\Serializer\Reference\ReferenceSerializerInterface
Also, I cleaned up the ignore annotation, so the following annotations can be added to properties to give more fine grained control of serialization:
#Sds\Serializer(#Sds\Ignore('ignore_when_serializing'))
#Sds\Serializer(#Sds\Ignore('ignore_when_unserializing'))
#Sds\Serializer(#Sds\Ignore('ignore_always'))
#Sds\Serializer(#Sds\Ignore('ignore_never'))
For example, put #Sds\Serializer(#Sds\Ignore('ignore_when_serializing')) on an email property - it means that the email can be sent upto the server for update, but can never be serialized down to the client for security.
And lastly, if you hadn't noticed, sds annotations support inheritance and overriding, so they play nice with complex document structures.
Another very simple, framework independent way to transforming Doctrine ODM Document to Array or JSON - http://ajaxray.com/blog/converting-doctrine-mongodb-document-tojson-or-toarray
This solution gives you a Trait that provides toArray() and toJSON() functions for your ODM Documents. After useing the trait in your Document, you can do -
<?php
// Assuming in a Symfony2 Controller
// If you're not, then make your DocmentManager as you want
$dm = $this->get('doctrine_mongodb')->getManager();
$report = $dm->getRepository('YourCoreBundle:Report')->find($id);
// Will return simple PHP array
$docArray = $report->toArray();
// Will return JSON string
$docJSON = $report->toJSON();
BTW, it will work only on PHP 5.4 and above.