return or not from super().method(*args, **kwargs)
Hi django-users, I have a a question that I don't know where to send. Since it happened programming in Django and I usually read this list I thought of sending it here. I would like to ask if someone has strong feelings or if I have missed some styling documentation. This could be a generic Python styling question when re-implementing a method of a base class. The example below is for models.Model. Let's say that you had a model such as: class Person(models.Model): name = models.CharField(max_length=100) def save(self, *args, **kwargs): # some things... # Question: do you do: super().save(*args, **kwargs) # or do you: return super().save(*args, **kwargs) Currently Model.save() returns None. My thoughts: -"return super().save(*args, **kwargs)": -Good: if some day the base class changes and starts returning something: the sub-class is forward-compatible :-) -Good: less thinking when implementing the derived method: just do the return always instead of having to check the base class method -Bad: a reader might assume that Person.save() returns a value (instead of None) -?: I haven't looked yet if I could add type hints for the return value of the the sub-class method saying "same as the base class". -"super().save(*args, **kwargs)": -Good: it's clear for the reader that nothing is returned -Easy to do the type hints "-> None" if used in the project Any thoughts? What would you prefer to see? Currently I tend to go for the "super().save(*args, **kwargs)" (no unnecessary return) as done in the Django documentation and to be explicit in the present (it doesn't return anything)... but I have my own doubts :-) Part of this happened when I was reading some code and I thought that I was in a "save()" for a form but I was in the model. For the form I need to not forget the "return". Thanks for any thoughts / comments :-) Cheers, -- Carles Pina i Estany https://carles.pina.cat -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20211130221344.GA15295%40pina.cat.
how to add an extra field in an admin form (not part of the model)
Hi, Last week I tried to do something in admin but it didn't work as I had guessed. The simplification of what I wanted is to have an extra field in the admin form. What I tried to do is what I do in forms outside admin: - class MyModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['extra_field'] = forms.CharField(max_length=100) def save(self, *args, **kwargs): # here I would like to have some code using the new extra_field pass class Meta: model = MyModel fields = ['amount', 'project'] class MyModelAdmin(admin.ModelAdmin): form = MyModelForm - The "extra_field" is not displayed in the "Add MyModel" form in the admin. After this I tried different approaches too long to explain here (I mean, all failed in different ways). Does any of you expand an admin form with a new field? any idea, references, etc. welcomed! Thank you very much, -- Carles Pina i Estany -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20200517111312.GA23248%40pina.cat.
Re: how to add an extra field in an admin form (not part of the model)
Thanks very much! I've quickly watched the video... sadly the video helps to add fields into the registration form, not in the admin section (the, by default, /admin URL). As a side note and for future reference anyone here: one of my attempts on Friday was following this one: https://gist.github.com/riklomas/511440 This uses exactly my first approach. And it works. But only because the default models.User already has an "email" field (not displayed by default in http://localhost:8000/admin/auth/user/add/ ) And in a "desperate" way I realised also that UserAdmin overrides get_form and this works: https://stackoverflow.com/questions/54262075/difference-between-add-form-and-form I did "MyAdminForm" doing the same as Django in the UserAdmin but this only works if the model has the field to be added (this was sad, I realised too late that models.User has it!) Anyway, if anyone has added a field in a model form that doesn't belong to the model: any pointers, help, ideas are welcomed! Thanks for any ideas! Carles On May/17/2020, Anonymous Patel wrote: > https://youtu.be/lHQI9ydQlSU > > Try this video it might help, it helped me for the same problem. > > Raj Patel > > On Sun, 17 May, 2020, 6:50 pm Carles Pina i Estany, wrote: > > > > > Hi, > > > > Last week I tried to do something in admin but it didn't work as I had > > guessed. > > > > The simplification of what I wanted is to have an extra field in the admin > > form. > > > > What I tried to do is what I do in forms outside admin: > > > > - > > class MyModelForm(forms.ModelForm): > > def __init__(self, *args, **kwargs): > > super().__init__(*args, **kwargs) > > self.fields['extra_field'] = forms.CharField(max_length=100) > > > > def save(self, *args, **kwargs): > > # here I would like to have some code using the new extra_field > >pass > > > > class Meta: > > model = MyModel > > fields = ['amount', 'project'] > > > > class MyModelAdmin(admin.ModelAdmin): > > form = MyModelForm > > - > > > > The "extra_field" is not displayed in the "Add MyModel" form in the admin. > > > > After this I tried different approaches too long to explain here (I mean, > > all > > failed in different ways). > > > > Does any of you expand an admin form with a new field? any idea, > > references, > > etc. welcomed! > > > > Thank you very much, > > > > -- > > Carles Pina i Estany > > > > -- > > You received this message because you are subscribed to the Google Groups > > "Django users" group. > > To unsubscribe from this group and stop receiving emails from it, send an > > email to django-users+unsubscr...@googlegroups.com. > > To view this discussion on the web visit > > https://groups.google.com/d/msgid/django-users/20200517111312.GA23248%40pina.cat > > . > > > > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to django-users+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/django-users/CAF_9Cit_cQ2ErCKsKNe4TgVxF%2BAcjatq0fYgzOyf5P0cDD7Skg%40mail.gmail.com. -- Carles Pina i Estany -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20200517140828.GA30392%40pina.cat.
not possible to delete if calling self.errors in a Form in InlineFormSet
Hi, Yesterday and today I implemented something and I had a surprise. I'm explaining here with questions at the end but also in case that I might save some time to someone working with forms (if someone is going to try the same approach that I did and it doesn't work). What I want to do: the user fills in a form (with Django forms using django-crispy-form). If there is a validation error in a specific field I need to show a new Field (a checkbox) in order to get confirmation before the final submission. Very important: this form is in an InlineFormSet (via inlineformset_factory) My first reaction: in MyForm.__init__(self) I did something along the lines (pseudocode) of: """ if 'amount' in self.errors: self.fields['allow_error'] = forms.BooleanField() divs.append('allow_error') """ This worked... but it has one problem that some people might have already spotted! The deletion was not working. kwargs['data'] contained the 'DELETE' key correctly (with the prefix, etc.). But it was not available in self.clean_fields when it was trying to be used by Django in order to decide if the form was going to be deleted. After some investigation: self.errors is a property and calls BaseForm.errors which does: """ if self._errors is None: self.full_clean() return self._errors """ (https://github.com/django/django/blob/master/django/forms/forms.py#L169) My form is created in BaseFormSet._construct_form method. This does (at the very end): """ form = self.form(**defaults) self.add_fields(form, i) """ (https://github.com/django/django/blob/master/django/forms/formsets.py#L175) The "add_fields" method adds the "DELETE" in self.fields: (https://github.com/django/django/blob/master/django/forms/formsets.py#L390) It needs to be in self.fields when self.clean_data is populated or it is ignored. Since in the MyForm.__init__ method I called self.errors and the result is cached/optimized: 'DELETE' is never added in self.clean_fields (it's not in self.fields when I called self.errors that triggers the validation, full_clean, etc; and when it's added in self.fields it's too late) and then the form never triggers the deletion. I have some questions: a) Does it say somewhere in the documents to avoid calling self.errors from the __init__? I might have missed it. I had some similar problem using the debugger (via self.errors or self.is_valid perhaps, etc.). b) I currently now read data from self.data and get the number that I need and I apply the same logic as the "clean" to decide if I need to show the checkbox or not. I wonder if there is some other way to approach this issue that is a bit cleaner (avoiding self.data, self contained in the form logic, etc.). Do you use any other approach? c) Actually, should Django tried to prevent my error somehow? :-) Thanks very much! -- Carles Pina i Estany -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20200618141534.GA30379%40pina.cat.
Re: project ideas
Hi, On Jul/31/2020, Spring-dot wrote: > I want to do some handsome projects using django. Can anyone suggest some? > Thanks in advance! :) I usually like doing projects for learning for things that can be useful for me. Do you like cooking? perhaps a cooking/ingredients application. Do you have lots of books? A book locator... etc. :-) -- Carles Pina i Estany https://carles.pina.cat -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20200731120531.GA3302%40pina.cat.
Re: I want to store (City, Country) pairs in my models as a field. Is GeoDjango an overkill for my use case?
Hi, On Sep/17/2020, John Reese wrote: > I want to store (City, Country) pairs in my models as a field. I want to do > something like this <https://stackoverflow.com/jobs> (the location field). > > *Is GeoDjango an overkill for my use case? If yes, what do you suggest me > to use?* I've read your question in multiple places I think! I would seriously consider just using: https://django-autocomplete-light.readthedocs.io/en/master/ You would need to have in your Django app the cities and countries, tweak the query from django-autocomplete-light, etc. Cheers, -- Carles Pina i Estany https://carles.pina.cat -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20200917204747.GA3581%40pina.cat.
Re: Want to get informations about bets Django hosting plateform
Hi, On Sep/21/2020, Maksim Mislavskii wrote: > maybe pythonanywhere.com? I just wanted to say: I use pythonanywhere.com and I'm happy with it. It has a free tier that might be enough for the original poster. It feels closer to a standard Linux system so I feel that the deployment is more standard than on Heroku (in case that I want to change it). Other than that I use VPSs with Docker. Cheers, -- Carles Pina i Estany https://carles.pina.cat -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20200923103115.GA23072%40pina.cat.
Re: Get datetime now, not at server initialisation
Hi, On Oct/27/2020, Clive Bruton wrote: > I have a function that uses the current date to set up a file path for > uploaded images: > > > > def upload_path(): [...] > class Image(models.Model): > item = models.ForeignKey(Item, on_delete=models.CASCADE) > #file = ImageField(_('image'), upload_to='images') > file = ImageField(_('image'), upload_to=upload_path()) > The problem is that when the Image class calls 'upload_path' the > datetime portion of this is always the runserver initialisation time, > rather than the time when 'upload_path' is called/used. > > How to fix this? For what I remeber (I use FileField usually but this is noto relevant I hope) you should do: def upload_path(instance, filename): # you have access to the instance (object model Image in your case) # and the filename that the user used to upload it # and this is executed on the upload time return your_new_file_name In the model: file = ImageField(_('image'), upload_to=upload_path) note that upload_path is a callable: it gets called on the upload time. In your code it was called on initialization time. Some time ago I had a similar code that caused a bug: in a ListView the "queryset = " is executed on startup time. For a dynamic one I should have used get_queryset() method. -- Carles Pina i Estany https://carles.pina.cat -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20201028085843.GA20091%40pina.cat.
Re: Get datetime now, not at server initialisation
Hi Clive, On Oct/28/2020, Clive Bruton wrote: > Thanks, that was very helpful. I had another pointer on this and found out > that the easiest way to do this is just to change the ```file``` line in the > class to: > > ``` > file = ImageField(_('image'), upload_to='images/items/%Y/%m/%d/%H/%M/%S') > I haven't used this method. I always pass a callable (passing a function). (I'm deleting a part of your message...) > So, given that ```upload_path``` returns a string, I don't understand why I > also have to concatenate the ```filename```: > > ``` > def upload_path(instance, filename): > dtnow = datetime.now(timezone.utc) > dtstr = '{:%Y/%m/%d}'.format(dtnow) > dtstr = 'images/items/' + dtstr + '/' + filename > return dtstr > ``` > In this case, if I do not concatenate ```filename``` then the uploaded file > gets named with the last element of the date formatting and without a file > extension, ie potentially like this: > > ```images/items/2020/10/28/20/59/55``` > > rather than: > > ```images/items/2020/10/28/20/59/55/image.jpg``` I see... > The other thing I don't understand is how ```instance``` and ```filename``` > are passed to the function ```upload_path```. I would expect to do something > like: > > ``` file = ImageField(_('image'), upload_to=upload_path(instance, > filename))``` > > But if I do that I get: > > ```NameError: name 'instance' is not defined``` > > Sorry for so many more questions! I see... I'll explain two things that put together might help you. What Django is doing (for now believe me, but keep reading to see it yourself :-) ) is similar to this: def print_name(name): print(f'The name is {name}') def print_short_name(name): print(f'Short name: {name[0:2]}') def call_with_upper_parameter(function_to_call, param): param = param.upper() function_to_call(param) for name in ['Clive', 'Jannett']: call_with_upper_parameter(print_name, name) call_with_upper_parameter(print_short_name, name) The output is: The name is CLIVE Short name: CL The name is JANNETT Short name: JA Note that "call_with_upper_parameter" gets two parameters: a callable and a parameter. It converts the parameter to upper case and then calls the function_to_call with this parameter. If you would do "print(function_to_call)" you would see "" There is the Python function "callable" to know if a variable can be called (so if it can be executed: pass parameter -or not- and with () ) Or in another way: -- In [1]: def f(): ...: pass ...: In [2]: name = 'Clive' In [3]: callable(f) Out[3]: True In [4]: callable(name) Out[4]: False In [5]: f() In [6]: name() --- TypeError Traceback (most recent call last) in () > 1 name() TypeError: 'str' object is not callable In [7]: -- In my opinion: it takes a bit of effort the first times to understand them. After this it stays for you for any language. And now the Django part: You are using ImageField. ImageField is a FileField: https://github.com/django/django/blob/master/django/db/models/fields/files.py#L370 FileField in the init saves the upload_to into self.upload_to: https://github.com/django/django/blob/966b5b49b6521483f1c90b4499c4c80e80136de3/django/db/models/fields/files.py#L240 Side note: if self.upload_to is a str at some point forces to be relative: https://github.com/django/django/blob/966b5b49b6521483f1c90b4499c4c80e80136de3/django/db/models/fields/files.py#L265 But here the interesting code: https://github.com/django/django/blob/966b5b49b6521483f1c90b4499c4c80e80136de3/django/db/models/fields/files.py#L308 In "generate_filename" is doing: if it's a callable: it calls self.upload_to with the instance and the filename If it's not a callable (a str in your case): it executes datetime.datetime.now().strftime(str(self.upload_to)) : so it's interpolating the %Y, %m, etc. that you had used and uses it as a base directory and then adds the filename (posixpath.join(dirname, filename)) Does this explain how it works? I think that your questions might be answered with the callable code and the Django code. (I think that you had read the documentation but here it is: https://docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.FileField.upload_to , it doesn't explain how it is implemented internally). It might help you to use a Python debugger and see the steps as they happen, variables, etc. (adding a breakpoint in the Django code and inspect variables). Let
Re: Deploy a finished django application
Hi Eugene, On Dec/03/2020, Eugene TUYIZERE wrote: > I hope you are doing well. I have a question that I need guidance from > you: I have a web application that is currently done and ready to be > used. I want to deploy (make it productive) on the company server. > This company has very strong security on their private network. My > question is: How to deploy this web application on the company server > so that they start to use it? If I was you I would ask the system administrators about how to deploy the application. They will be able to explain how they operate and the steps to deploy it. If the application needs to be packaged in Docker, virtual machine templates, create you a database user so the application can connect to it, etc. -- Carles Pina i Estany https://carles.pina.cat -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20201203121932.GA6262%40pina.cat.
Re: MultipleChoiceField form bug?
Hi, On Dec/22/2020, Benny M wrote: > I’ve ran into some unexpected behavior while testing a ModelForm with > a MultipleChoiceField and am trying to determine if this is a bug, or > if maybe I’m doing something out of the ordinary. I think that I might guess what it is. If I could see the code it might be easier. Are you doing something like: class SomeForm(forms.ModelForm): some_field_options = a_dynamic_expression_that_queries_the_DB def __init__(*args, **kwargs): your code So using a class variable instead of an instance variable? Class variables are initialised on "startup" (I'm simplifying) and only once (and might be used via __new__ on ModelFormMetaclass probably, read and validated). Either way, if it's not what I've guessed and you paste some code it might help me / someone else to understand it better. I had once a bug because of using datetime.now() in a class variable when I wanted it the "now" that the view was used not the "now" when the application was started up. -- Carles Pina i Estany https://carles.pina.cat -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20201222153133.GA31856%40pina.cat.
Re: MultipleChoiceField form bug?
Hi, On Dec/22/2020, Benny M wrote: > That’s correct. I am using a class variable since there doesn’t seem > to be a DRY - or at least not messy - way of manipulating this from > __init__. It's easy to make this mistake. I was bitten by something similar in a class based view generating a queryset... > That said, your explanation makes sense and does answer the “why” of > this. If there’s a way of defining forms inside __init__ I haven’t > found it… which is not to say that it doesn’t exist. Yes, you can > Here’s an example of what I’m referring to: (Pardon my poorly labeled > model/form names) > > ``` > class M2MForm(forms.ModelForm): > “”” Populate/update M2MModel name and m2m references ””" > REF_OPTIONS = ((r.id, r.name) for r in RefModel.objects.all()) > > ref_models = forms.MultipleChoiceField( > widget=forms.SelectMultiple, > choices=REF_OPTIONS, > required=False > ) > > class Meta: > model = M2MModel > fields = ['name'] > ``` Try something like: ``` class M2MForm(forms.ModelForm): def __init__(*args, **kwargs): super().__init__(*args, **kwargs) # At this point self.fields['name'] already exist... # ...if you overwriteself.fields['name'] careful # because you need to save it in save() # # self.fields gets created by the __init__() method of # the parent class (actually grandparent I think :-) ) """ Populate/update M2MModel name and m2m references """ REF_OPTIONS = ((r.id, r.name) for r in RefModel.objects.all()) # this would add the field 'ref_models' in the form, but save() # will not save. You can overwrite save and save it yourself self.fields['ref_models'] = forms.MultipleChoiceField( widget=forms.SelectMultiple, choices=REF_OPTIONS, required=False ) class Meta: model = M2MModel fields = ['name'] ``` I would look at not using forms.MultipleChoiceField and use forms.ModelMultipleChoiceField(): then you should be able to pass queryset (first argument for the ModelMultipleChoiceField) and avoid the REF_OPTIONS=... line Let me know what you find :-) Cheers, > > > On Dec 22, 2020, at 9:31 AM, Carles Pina i Estany wrote: > > > > > > > > Hi, > > > > On Dec/22/2020, Benny M wrote: > > > >> I’ve ran into some unexpected behavior while testing a ModelForm with > >> a MultipleChoiceField and am trying to determine if this is a bug, or > >> if maybe I’m doing something out of the ordinary. > > > > I think that I might guess what it is. If I could see the code it might > > be easier. > > > > Are you doing something like: > > > > class SomeForm(forms.ModelForm): > >some_field_options = a_dynamic_expression_that_queries_the_DB > > > >def __init__(*args, **kwargs): > >your code > > > > So using a class variable instead of an instance variable? > > > > Class variables are initialised on "startup" (I'm simplifying) and only > > once (and might be used via __new__ on ModelFormMetaclass probably, read > > and validated). > > > > Either way, if it's not what I've guessed and you paste some code it > > might help me / someone else to understand it better. > > > > I had once a bug because of using datetime.now() in a class variable > > when I wanted it the "now" that the view was used not the "now" when the > > application was started up. > > > > -- > > Carles Pina i Estany > > https://carles.pina.cat > > > > -- > > You received this message because you are subscribed to the Google Groups > > "Django users" group. > > To unsubscribe from this group and stop receiving emails from it, send an > > email to django-users+unsubscr...@googlegroups.com. > > To view this discussion on the web visit > > https://groups.google.com/d/msgid/django-users/20201222153133.GA31856%40pina.cat. > > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to django-users+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/django-users/CH2PR14MB39136CDA719529325B91F0E3C0DF0%40CH2PR14MB3913.namprd14.prod.outlook.com. -- Carles Pina i Estany https://carles.pina.cat -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20201223000345.GA24427%40pina.cat.
Re: CRUD Generator
Hi, On Jan/08/2021, Noel Simela wrote: > Good day, > > I have explored several crud generator packages. > > I am looking for an opinion on the best package to adopt that has been > maintained for the past few months, > > If you have experience in django crud generators.Please let me know > the one you have used, the pros and cons. I can't remember the details (and I haven't used it at all) but I saw this talk: https://djangoday.dk/talks/introducing-iommi/ And I was very impressed by this package. It might help you. I write the forms using Models, Views, Forms (using django-crispy-forms), update the urls.py. But depends on the project it might make sense to use something that helps on this. Cheers, -- Carles Pina i Estany https://carles.pina.cat -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20210110114418.GB28721%40pina.cat.
Re: To start contribution from initial level
Hi, On Jan/19/2021, Dhruval Gandhi wrote: > Hello, > > Myself Dhruval Gandhi, I want to contribute in django . > But I'm totally new for it. Welcome to Django > I want to setup this on my local machine, want to contribute myself via PR, > But I don't how this all to do it. There is quite a lot of documentation here: https://docs.djangoproject.com/en/dev/internals/contributing/ Cheers! -- Carles Pina i Estany https://carles.pina.cat -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20210120091004.GA14193%40pina.cat.