I create a custom models.Model and register to snippet.
I wish that this model have a field to a Wagtail document.
How can I do that ?
#register_snippet
class Product(Model):
name = CharField(max_length=255)
bill = ReferenceToWagtailDocument() <-- how to code that
Ideally, I wish that bill can be selectable in Wagtail Snippet.
Any idea to do that ?
Best regards.
I have found a solution by adding a ForeignKey like the following.
#register_snippet
class Product(Model):
name = CharField(max_length=255)
bill = ForeignKey(Document, on_delete=CASCADE, null=True)
Hope that I can help somebody.
One drawback, I don't have the file selector.
Best regards.
Related
How to create ArrayField() in TortoiseORM
from common.base_model import AbstractBaseModel
from tortoise.fields import CharField, BooleanField, ForeignKeyField, ArrayField
class City(AbstractBaseModel):
name = CharField(max_length=100, unique=True)
district = CharField(max_length=100, null=True)
state = CharField(max_length=100)
country = ArrayField() # not working
is_verified = BooleanField(default=True)
There is no ArrayField in TortoiseORM, here is an article about fields in TortoiseORM from its documentation.
As you can see, there is no matching field in TortoiseORM, so you have to extend the existing field class.
I suggest extending the basic class Field because your subclass' to_db_value method has to return the same type as extended field class' to_db_value method, and in the class Field it's not specified.
Next time, try harder - read the documentation and make better questions (add more info, show your attempts).
To achieve the result you want,which I'm assuming is having a field to hold multiple countries, you'd have to create another table for your country field and have a many to many relationship between that table and your city table,its a more conventional implementation that wont have you extend the existing field class.
I have a simple Django App having database interactions. I need to make the functionality of Video Visiting counter. So that I need to update- increment the counter each time when user visit the video.
I have a video object on template page(video-details.html).
This is how I access the video_file_name.
<h1 id="video1">{{video_obj.video_file_name}}</h1>
I have video model as:
class Video_Mapping(models.Model):
video_file_name = models.CharField(max_length=100)
video_description = models.CharField(max_length=2000, default='Video Description')
created_at = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
video_category_id = models.IntegerField(default=1)
video_seen_count = models.IntegerField(default=0)
I want to update the video_seen_count model value on template page.
More info: As I can do similar thing in View like following.
video = Video_Mapping.objects.get(pk=video_id);
video.video_description = description; video.save();
Please suggest me the best way to do it in the video-detail.html template page.
The simplest thing which I have done here is as per #birophilo'suggestion.
I was actually finding the way to increment the video_seen_count value from template(html page).
But after doing more research and try as suggested in comment, I decided to make this increment operation before the template renders(So in the view).
So it worked like:
video.video_screen_count += 1
video.save();
Thanks.
I am trying to achieve a category model where name has unique=True,
but practically I can still add same category name with different cases.
i.e. I have a category called Food
I am still able to add food, FOOD, fOod, FOOd
Is their any philosophy behind this? or it is a work in progress.
Cause in real world if I think of Category Food, it will always be food, no matter what case it has used to mention itself.
Thank you in advance to look at this.
To answer my own question:
I have found I can have clean method on my model. So I added
class Category(models.Model):
name = models.CharField(max_length=200, unique=True)
def clean(self):
self.name = self.name.capitalize()
It is capitalising the first letter, which is then handled by the save method, which calls the validate_unique method to raise error.
You can use Postgre specific model field called Citext fields (case insensitive fields).
There are three option at the moment:
class CICharField(**options), class CIEmailField(**options) and class CITextField(**options)
Example:
from django.db import models
from django.contrib.postgres.fields import CICharField
class Category(models.Model):
name = CICharField(verbose_name="Name", max_length=255)
But don't forget to create an extension for the citext fields.
See here.
Basically, you have to add the extension class in the migration file, inside the operations array, before the first CreateModel operation.
# migration file
operations = [
CITextExtension(), # <------ here
migrations.CreateModel(
...
),
...,
]
Setting the column to case-insensitive collation should fix this. You may need to do it at the SQL level.
I've spent the last few hours looking at Django Docs and similar questions on here but I'm still unclear on how to tackle the problem...
In essense I want to access the list of email addresses relevent to a certain group, so I can send an email to these customers who are part of this group (named group_one, group_two etc)
class Group(models.Model):
name = models.CharField(primary_key=True)
mailing_list = models.ManyToManyField("Customer", null=True)
class Customer(models.Model):
name = models.CharField()
email = models.EmailField(primary_key=True)
I've tried
group_mail_list = Group.objects.filter(name=group_two)
And this returns an Query Object for group_two but when I try to do a __contains filter I get a error:
TypeError: Related Field has invalid lookup: contains
Anyone help me out? Not sure if it's because it's a many-to-many relationship perhaps?
Thanks in advance :)
What you really want is Customers, then. It seems counter-intuitive on the surface, because you're wanting emails for a Group, but that field is on Customer not Group:
Customer.objects.filter(group__name='group_two').values_list('email')
i'm experimenting with django and the builtin admin interface.
I basically want to have a field that is a drop down in the admin UI. The drop down choices should be all the directories available in a specified directory.
If i define a field like this:
test_folder_list = models.FilePathField(path=/some/file/path)
it shows me all the files in the directory, but not the directories.
Does anyone know how i can display the folders?
also i tried doing
test_folder_list = models.charField(max_length=100, choices=SOME_LIST)
where SOME_LIST is a list i populate using some custom code to read the folders in a directory. This works but it doesn't refresh. i.e. the choice list is limited to a snapshot of whatever was there when running the app for the first time.
thanks in advance.
update:
after some thinking and research i discovered what i want may be to either
1. create my own widget that is based on forms.ChoiceField
or
2. pass my list of folders to the choice list when it is rendered to the client
for 1. i tried a custom widget.
my model looks like
class Test1(models.Model):
test_folder_ddl = models.CharField(max_length=100)
then this is my custom widget:
class FolderListDropDown(forms.Select):
def __init__(self, attrs=None, target_path):
target_folder = '/some/file/path'
dir_contents = os.listdir(target_folder)
directories = []
for item in dir_contents:
if os.path.isdir(''.join((target_folder,item,))):
directories.append((item, item),)
folder_list = tuple(directories)
super(FolderListDropDown, self).__init__(attrs=attrs, choices=folder_list)
then i did this in my modelForm
class test1Form(ModelForm):
test_folder_ddl = forms.CharField(widget=FolderListDropDown())
and it didn't seem to work.What i mean by that is django didn't want to use my widget and instead rendered the default textinput you get when you use a CharField.
for 2. I tried this in my ModelForm
class test1Form(ModelForm):
test_folder_ddl = forms.CharField(widget=FolderListDropDown())
test_folder_ddl.choices = {some list}
I also tried
class test1Form(ModelForm):
test_folder_ddl = forms.ChoiceField(choices={some list})
and it would still render the default char field widget.
Anyone know what i'm doing wrong?
Yay solved. after beating my head all day and going through all sorts of examples by people i got this to work.
basically i had the right idea with #2. The steps are
- Create a ModelForm of our model
- override the default form field user for a models.CharField. i.e. we want to explcitly say use a choiceField.
- Then we have to override how the form is instantiated so that we call the thing we want to use to generate our dynamic list of choices
- then in our ModelAdmin make sure we explicitly tell the admin to use our ModelForm
class Test1(models.Model):
test_folder_ddl = models.CharField(max_length=100)
class Test1Form(ModelForm):
test_folder_ddl = forms.choiceField()
def __init__(self, *args, **kwargs):
super(Test1Form, self).__init__(*args, **kwargs)
self.fields['test_folder_ddl'].choices = utility.get_folder_list()
class Test1Admin(admin.ModelAdmin):
form = Test1Form
I use a generator:
see git://gist.github.com/1118279.git
import pysvn
class SVNChoices(DynamicChoice):
"""
Generate a choice from somes files in a svn repo
""""
SVNPATH = 'http://xxxxx.com/svn/project/trunk/choices/'
def generate(self):
def get_login( realm, username, may_save ):
return True, 'XXX', 'xxxxx', True
client = pysvn.Client()
client.callback_get_login = get_login
return [os.path.basename(sql[0].repos_path) for sql in client.list(self.SVNPATH)[1:]]