I there any way to check if any field Null or Empty without checking each and every field. i have seen this Django check to see if field is blank?. But in this case we have to check each and every field.
if i am wrong please correct me. Thanks for the help!
There's no way around checking all the fields, but you could write some helpers.
any_blank_fields = all((field.blank for field in Model._meta.fields))
Oh, you're talking about Falsy values, not blank=True. In that case, you really have no choice but to do some loops, or a list comprehension.
instance = Model.objects.latest('pk')
all_fields_filled = all((getattr(instance, field.name) for field in
instance._meta.fields))
Related
I have an input box that must accept the following parameters:
Empty Value ('')
ZERO (0)
Fail value ('x')
I know that I can create a custom "fail" BooleanField that gets set to True if "x" is typed. However, I would like to know if it is possible add these values inside the DecimalField. Maybe, use CharField with Decimal Validation. However, trying to use it with CharField and Decimal Validation failed. So, I am not sure how else I can achieve this.
Thanks!
Could you do something with validators like:
extended_decimal_field = models.CharField(
max_length=10,
validators=[RegexValidator('^\d{8}[.]{1}\d{2}|['X']{1}$')]
)
I don't think this is exactly right but might be right track?
I have two fields that run throughout a website that I would like to match so that when a user inputs a value either of the fields, it will match the other field. I'm using Sitecore Rocks and am trying to use a query to do this.
select ##h1#, ##Title#
from /sitecore/Content/Home//*[##h1# !="##Title#"];
update set ##h1# = ##Title# from /sitecore/Content/Home//*[##Title# = "<id>"];
What am I missing here?
This article talks about tapping in to the item:saving event which allows you to compare the fields values of the item before and after the changes:
http://www.sitecore.net/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2010/11/Intercepting-Item-Updates-with-Sitecore.aspx
Using this, you can determine which field has been amended, then change the other to match.
I've had to do something similar to this when a new field was added, and we wanted to set the initial value equal to an existing field. It may be a bug in Sitecore Rocks, but I found it would only update a field when a static value was part of the query.
When I ran ##h1# = ##Title#, the query analyzer would return the correct number of items updated, but no values were actually updated. However, ##h1# = '<id>' worked perfectly. After trying a number of things, I found this did what I wanted.
update set ##h1# = '' + ##Title# from /sitecore/Content/Home//*[##Title# = "<id>"];
I hope that helps.
Suppose you have a model Entry, with a field "author" pointing to another model Author. Suppose this field can be null.
If I run the following QuerySet:
Entry.objects.filter(author=X)
Where X is some value. Suppose in MySQL I have setup a compound index on Entry for some other column and author_id, ideally I'd like the SQL to just use "author_id" on the Entry model, so that it can use the compound index.
It turns out that Entry.objects.filter(author=5) would work, no join is done. But, if I say author=None, Django does a join with Author, then add to the Where clause Author.id IS NULL. So in this case, it can't use the compound index.
Is there a way to tell Django to just check the pk, and not follow the link?
The only way I know is to add an additional .extra(where=['author_id IS NULL']) to the QuerySet, but I was hoping some magic in .filter() would work.
Thanks.
(Sorry I was not clearer earlier about this, and thanks for the answers from lazerscience and Josh).
Does this not work as expected?
Entry.objects.filter(author=X.id)
You can either use a model or the model id in a foreign key filter. I can't check right yet if this executes a separate query, though I'd really hope it wouldn't.
If do as you described and do not use select_related() Django will not perform any join at all - no matter if you filter for the primary key of the related object or the related itself (which doesn't make any difference).
You can try:
print Entry.objects.(author=X).query
Assuming that the foreign key to Author has the name author_id, (if you didn't specify the name of the foreign key column for ForeignKey field, it should be NAME_id, if you specified the name, then check the model definition / your database schema),
Entry.objects.filter(author_id=value)
should work.
Second Attempt:
http://docs.djangoproject.com/en/dev/ref/models/querysets/#isnull
Maybe you can have a separate query, depending on whether X is null or not by having author__isnull?
Pretty late, but I just ran into this. I'm using Q objects to build up the query, so in my case this worked fine:
~Q(author_id__gt=0)
This generates sql like
NOT ("author_id" > 0 AND "author_id" IS NOT NULL)
You could probably solve the problem in this question by using
Entry.objects.exclude(author_id__gt=0)
All the answers I've seen to this so far have confused me.
I've made a form that gets built dynamically depending on a parameter passed in, and questions stored in the database. This all works fine (note: it's not a ModelForm, just a Form).
Now I'm trying to save the user's responses. How can I iterate over their submitted data so I can save it?
The MultipleChoiceFields are confusing me especially. I'm defining them as:
self.fields['question_' + str(question.id)] = forms.MultipleChoiceField(
label=mark_safe(required_tag +
question.label + "<br/>Choose any of the following answers"),
help_text=question.description,
required=question.required,
choices=choices,
widget=widgets.CheckboxSelectMultiple())
When I select several options, the actual posted data is something like:
question_1=5&question_1=6
Will django automatically realise that these are both options on the same form and let me access an iterable somewhere? I was going to do something like:
for field in self.cleaned_data:
print field # save the user's response somehow
but this doesn't work since this will only return question_1 once, even though there were two submitted values.
Answer: The for loop now works as expected if I loop through self.fields instead of self.cleaned_data:
for field in self.fields:
print self.cleaned_data[field]
... this doesn't work ...
Are you sure? Have you tested it? Normally the cleaned_data value for a MultipleChoiceField is a list of the values chosen on the form.
So yes, it only returns question_1 once, but that returned value itself contains multiple values.
I have a ModelForm, in which I'm having a CharField, which is declared as unique in the Model.
But I have 2 problems:
If I fill in the form with a field having the same name I don't get an error message.
I'd like this field not to contain white spaces.
Is it possible to do that using a ModelForm?
You can do something close to this:
class MyModelForm(forms.ModelForm):
# your field definitions go here
def clean_myuniquefield(self):
# strip all spaces
data = str(self.cleaned_data['myuniquefield']).replace(' ', '')
model = self._meta.model
# check if entry already exists
try:
obj = model.objects.get(myuniquefield=data)
except model.DoesNotExist:
return data
raise forms.ValidationError("Value already exists!")
To get rid of spaces, make a clean_fieldname function to strip the spaces.
http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation
As for uniqueness, also note about the meta-field unique_together. I don't know if you need it, but I didn't know about it until I dug around.
If you really need to do uniqueness checking before trying to add and failing, you can also do that in the clean_* function. However, it might be better to assume that the database will take care of it and fail in a standard way, and just set up your error messages properly. That way, if you change constraints later, it will flow through more easily. And if others have to maintain your code, it will be more standard.
Hope this helps.