Disable field in Django on condition - django

Hi I want to disable few field in my form depending on whether a certain field has any data entered or not. If yes then I should hide them.
class Dictionary(models.Model)
name = models.CharField(max_length=50, blank=True,
null=True, db_index=True)
phase = models.PositiveSmallIntegerField(db_index=True,
default=0, blank=True, null=True)
warning = models.NullBooleanField(default='Unknown',
null=True, blank=True)
year = models.PositiveSmallIntegerField(db_index=True, default=0,
blank=True, null=True)
date_loaded = models.DateTimeField(auto_now=True, blank=False,
null=False, help_text=u'current date ')
If I have name entered in the field, I should disable the fields phase and warning.
In adminx.py
class DictionaryAdmin(object):
reversion_enable = True
list_display = ('name','phase','warning','year','date_loaded')
list_display_links = ('name')
readonly_fields = ()
Adding the readonly fields would disable them always.
Could I do this with overriding the get_readonly_fields given the conditions in adminx file?
my js file .
(function($) {
$(function() {
var name = $('name'),
phase = $('phase'),
warning = $('warning');
function toggledisabed(value) {
var checkname = /^CH[1-9][0-9+]?$/i;
value = checkname.test(name) ? phase.show(): phase.hide()
}
toggledisabled(name.val());
});
})(django.jQuery);

If I understand well, you want to hide field of form, based on model via condition. So you can just use {% if %} tag. Like this
{% if model.name %}
{{ form.field_for_name }}
{% else %}
{% endif %}
In case, if model has data in field "name", it will show, else it will hide

Related

How can I display something from data base after multiple criteria is satisfied in django

Here i have a Model Recommenders:
class Recommenders(models.Model):
objects = None
Subject = models.ForeignKey(SendApproval, on_delete=models.CASCADE, null=True)
Recommender = models.CharField(max_length=20, null=True)
Status = models.CharField(null=True, max_length=8, default="Pending")
Time = models.DateTimeField(auto_now_add=True)
And another model Approvers:
class Approvers(models.Model):
objects = None
Subject = models.ForeignKey(SendApproval, on_delete=models.CASCADE, null=True)
Approver = models.CharField(max_length=20, null=True)
Status = models.CharField(null=True, max_length=8, default="Pending")
Time = models.DateTimeField(auto_now_add=True)
And my SendApproval model as:
class SendApproval(models.Model):
Subject = models.CharField(max_length=256)
Date = models.DateField(null=True)
Attachment = models.FileField(upload_to=get_file_path)
SentBy = models.CharField(null=True, max_length=100)
Status = models.CharField(null= True, max_length=8, default="Pending")
Now my problem is that I have to display the Subject and Attachment from SendApproval table only when all the recommender's Status in Recommenders table related to that subject is "Approved"
Don't know how can I know that...Thanks in advance...
Actually not have any Idea about the solution but the best answer will be appreciated...By the way, I am new to StackOverflow...So please let me know if there is some ambiguity in my question.
Offer two ways.
1.Here the Recommenders model is filtered by the Status='Approved' field. By the Subject field, which is associated with the primary model, I get access to the SendApproval fields.
Replace bboard with the name of the folder where your templates are placed.
I have this: templates/bboard which are in the application folder.
views.py
def info(request):
recomm = Recommenders.objects.filter(Status='Approved')
return render(request, 'bboard/templ.html', {'context': recomm})
urls.py
urlpatterns = [
path('info/', info, name='info'),
]
templates
{% for a in context %}
<p>{{ 'Subject' }} : {{ a.Subject.Subject }} {{ 'Attachment' }} : Link
{{ 'id SendApproval' }} : {{ a.Subject.id }}</p>
{% endfor %}
2.You can also filter by primary model by fields from a secondary model that is linked to the primary. Here, I passed in the filter the name of the model in lower case and the search field.
In the primary model, by default, a property is created to refer to the secondary model, this is the name of the model in lower case and the _set prefix. In the outer loop, all received rows of the primary model are sorted out, and in the inner loop, through recommenders_set.all(), we get the Status. As you can see it is Approved.
sa = SendApproval.objects.filter(recommenders__Status='Approved')
print(sa)
for i in sa:
for k in i.recommenders_set.all():
print('status', k.Status)

How to query in Django with best efficiency?

I recently found that too much SQL query optimization issue. django-debug-tool reported hundreds of similar and duplicate queries. So, I'm trying to figure out the best efficiency of Django ORM to avoid unnecessary Queryset evaluation.
As you see the below Store model, a Store model has many Foreign key and ManyToManyFields. Due to that structure, there are many code snippets doing the blow on HTML template files such as store.image_set.all or store.top_keywords.all. Everything starts with store. In each store detail page, I simply pass a cached store object with prefetch_related or select_related. Is this a bad approach? Should I cache and prefetch_related or select_related each Foreign key or ManyToManyField separately on views.py?
HTML templates
{% for img in store.image_set.all %}
{{ img }}
{% endfor %}
{% for top_keyword in store.top_keywords.all %}
{{ top_keyword }}
{% endfor %}
{% for sub_keyword in store.sub_keywords.all %}
{{ sub_keyword }}
{% endfor %}
views.py
class StoreDetailView(View):
def get(self, request, *args, **kwargs):
cache_name_store = 'store-{0}'.format(store_domainKey)
store = cache.get(cache_name_store, None)
if not store:
# query = get_object_or_404(Store, domainKey=store_domainKey)
query = Store.objects.all().prefetch_related('image_set').get(domainKey=store_domainKey)
cache.set(cache_name_store, query)
store = cache.get(cache_name_store)
context = {
'store': store,
}
return render(request, template, context)
models.py
class Store(TimeStampedModel):
categories = models.ManyToManyField(Category, blank=True)
price_range = models.ManyToManyField(Price, blank=True)
businessName = models.CharField(unique=True, max_length=40,
verbose_name='Business Name')
origin = models.ForeignKey(Origin, null=True, on_delete=models.CASCADE, blank=True)
ship_to = models.ManyToManyField(ShipTo, blank=True)
top_keywords = models.ManyToManyField(Keyword, blank=True, related_name='store_top_keywords')
sub_keywords = models.ManyToManyField(SubKeyword, blank=True, related_name='store_sub_keywords')
sponsored_stores = models.ManyToManyField(
'self', through='Sponsorship', symmetrical=False, related_name='sponsored_store_of_store')
similar_stores = models.ManyToManyField(
'self', through='Similarity', symmetrical=False, related_name='similar_store_of_store')
shortDesc = models.TextField(blank=True, verbose_name='Short Description')
longDesc = models.TextField(blank=True, verbose_name='Long Description')
returnPol = models.TextField(verbose_name='Return Policy', blank=True)
returnUrl = models.CharField(max_length=255, null=True, blank=True, verbose_name='Return Policy URL')
likes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, editable=False)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, editable=False, on_delete=models.CASCADE,
related_name='stores_of_created_by', null=True, blank=True)
updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, editable=False, on_delete=models.CASCADE,
related_name='stores_of_updated_by', null=True, blank=True)
I really wouldn't advise custom caching/performance optimisation, unless it's a very last resort. Django has great docs on querysets and optimisation - if you follow those, it should be rare for you to experience major performance issues that require custom workarounds.
I think the issue here is that you're printing your objects in a template and hence calling their str() method. There's nothing wrong with this, but I'd check what variables you're using in your str() methods. I suspect you're referencing other models? I.e. the str() method in your image model (or whatever) is doing something like image.field.other_field. In this case, your query should look like:
queryset = Store.objects.prefetch_related('image_set__field')
Your final queryset may look like:
queryset = Store.objects.prefetch_related('image_set__field1', 'image_set__field2', 'top_keywords__field3', ...)
Note that you can still pass this into get_object_or_404 like so:
get_object_or_404(queryset, pk=<your_stores_id>)
Hope this helps.

Django output 1 field from a model within another table

I have 2 models -
class InsName(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30, verbose_name = "Insurer/Broker")
alias = models.TextField(max_length=80, blank=True)
def __str__(self):
return f'{self.name}, {self.alias}'
def get_absolute_url(self):
return reverse('insurer-detail', args=[str(self.id)])
class Development(models.Model):
id = models.AutoField(primary_key=True)
logno = models.CharField(validators=[RegexValidator(regex='^(SCTASK|CDLI)[0-9]{7}', message='Please enter a valid log number', code='nomatch')], max_length=13)
insurer = models.ForeignKey(InsName, on_delete=models.SET_NULL, null=True, blank=False, verbose_name="Client")
policy = models.ManyToManyField(Policy, blank=True)
on my template I am outputting a list of Developments but where insurer is output I just want the name part to output. I need to retain the alias as it is used in other templates that also calls in InsName.
I thought I could use a substring before comma method in the template but I cant see that such a thing exists. Is this possible? If not any tips on how I can achieve this is greatly appreciated!
Maybe you can do it like this using F (apart from comment of #dirkgroten):
queryset = Development.objects.all().annotate(insurer_name=F('insurer__name'))
And use it in template:
{% for item in queryset %}
{{ item.insurer_name }}
{% endfor %}

Django trying to add up values in the django template

Hi Guys I am trying to figure this out but not having any luck.
So I am showing my events in the homepage which shows how many seats are available, once the user has made a booking I would like to minus that from the amount showing on the homepage.
But I am already stuck at adding all the values up for that event in the booking model to minus from that amount.
So this is what I have
model for events
class Events(models.Model):
ACTIVE = (('d', "Deactivated"), ('e', "Expired"), ('a', "Active"), ('b', "Drafts"),)
ALCOHOL = (('0','No bring own alcohol'),('1','There will be complimentary wine pairing'))
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=50, blank=True, default='')
date = models.DateField()
time = models.TimeField()
price = models.CharField(max_length=240, blank=True, default='')
seats = models.IntegerField()
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
model for bookings
class Bookings(models.Model):
OPTIONS_STATUS = (('y', "Yes"), ('n', "No"), ('p', "Pending"),)
user = models.ForeignKey(User, on_delete=models.CASCADE)
event = models.ForeignKey(Events, on_delete=models.CASCADE)
eventdate = models.DateField()
event_amount = models.CharField(max_length=50, blank=True, default='')
guests = models.IntegerField()
bookingstatus = models.CharField(max_length=50, default='p', blank=True, choices=OPTIONS_STATUS)
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
my homepage how I get my data into a loop form the view
today = datetime.now().strftime('%Y-%m-%d')
events_list_data = Events.objects.filter(active='a').filter(Q(date__gte=today)|Q(date=today)).order_by('date')
How I am trying to show this in my template
{% for event_list in events_list_data %}
SHOW WHAT EVER DATA I AM SHOWING NOT NEEDED FOR HELP ON
{% for bookingguests in
event_list.bookings_set.all %}
{{ bookingguests.guests }}
{% endfor %}
Seats Left
{% endif %}
Generally, purpose of templates is not to implement logic. All the logic should go into your views. I would recommend you to do that in your views and either store it in a dict or a list and send it to front-end.
Once the user made a booking, if you want to modify the value on the HTML without reloading, you may need to use jQuery/javascript. Otherwise, if you are fine with reloading the page by rendering it again with calculations from the backend.
By using jQuery:
$("#balance-id").html(logic to get the balance)
By Calculating in views:
from django.db.models import Sum
user_balance = user.balance - events_data.aggregate(Sum('price'))
return render('path/to/template', {'events_list': events_list_object, 'user_balance':user_balance})
In the template:
{{user_balance}} seats left
Let me know in case of any questions.
Note: If you want to write some logic into your templates, use template tags. It can help you with whatever it can with its limited functionality.

Django forms breaking in IE7

I've got a dJango webform from a model with some error checking (valid email field,etc).
Everything works fine in various browsers Opera,Camino,Netscape,Safari and IE (except IE7).
All I get in IE7 is the 'Internet Explorer cannot display the webpage' message. If the forms valid the data gets written to the database so I think its something to do with the redirect stage.
I've tried various things method=get and javascript form submission but nothing seems to stop IE7 giving me this error.
Any help would be appreciated.
forms.py
class NewElectiveForm(ModelForm):
host_country = forms.CharField(widget=forms.widgets.Select(choices=COUNTRIES) , label="Destination")
host_type = forms.CharField(widget=forms.widgets.Select(choices=HOST_TYPE) , label="Location type")
host_name = forms.CharField(max_length=256, label="Name of host institution")
host_street = forms.CharField(required = False, max_length=100, label="Street")
host_city = forms.CharField(required = False, max_length=100, label="City")
host_district = forms.CharField(required = False, max_length=100, label="District")
host_zipcode = forms.CharField(required = False, max_length=100, label="Zipcode")
host_supervisor = forms.CharField(required = False, max_length=256, label="Name of supervisor")
host_email = forms.EmailField(required = False, max_length=100, label="Email")
host_fax = forms.CharField(required = False, max_length=100, label="Fax.No.")
host_tel = forms.CharField(required = False, max_length=100, label="Tel.No.")
start_date = forms.DateField(widget=SelectDateWidget(),label="Elective start date")
end_date = forms.DateField(widget=SelectDateWidget(),label="Elective end date")
subject = forms.CharField(required = False, max_length=256,label="Subject")
reasons = forms.CharField(required = False, widget=forms.widgets.Textarea(attrs={'class':'question'}), label="Please state briefly the reasons for this choice's location and subject")
outcomes = forms.CharField(required = False, widget=forms.widgets.Textarea(attrs={'class':'question'}), label="Please give upto to 4 outcomes that you hope to achieve during this elective")
your_mobile = forms.CharField(required = False, max_length=100, label="Please provide your mobile number if you are taking it with you")
insurance = forms.BooleanField(required = False, label="Please confirm that you have arranged holiday insurance")
malpractice = forms.BooleanField(required = False, label="Please confirm that you have medical malpractice cover")
groupinfo = forms.CharField(required = False, label="If you planning your Elective in a group, please list your fellow students")
#risk_upload = forms.FileField(widget=AdminFileWidget, required = False, label='Upload a completed risk assesment form')
#evidence_upload = forms.FileField(widget=AdminFileWidget, required = False, label='Upload an evidence document')
class Meta:
model = ElectiveRecord
exclude = ('id', 'review','elective', 'status', 'edit_userid','modified')
html template:
<form enctype="multipart/form-data" method="post" class="uniForm" id="newform" >
{% for i in form %}
<div class="fieldwrapper {% for error in i.errors %} error {% endfor %}">
{% for error in i.errors %}
<b>{{error|escape}}</b><br/>
{% endfor %}
{{ i.label_tag }} :
{% if i.html_name == "reasons" or i.html_name == "outcomes" %} <br/> {% endif %}
{{ i }}
{% if i.html_name == "evidence_upload" %} <br/>latest file= xxx {% endif %}
{% if i.html_name == "risk_upload" %} <br/>latest file= xxx {% endif %}
</div>
{%endfor%}
<div class="fieldWrapper"> <input type="submit" value="Save" NAME='save' > </div>
</form>
models.py
class ElectiveRecord(models.Model):
elective = models.ForeignKey(Elective, null=True, blank=True)
status = models.CharField(choices=ELECTIVE_STATUS_FLAGS, max_length=40)
edit_date = models.DateTimeField(auto_now_add=True)
edit_userid = models.CharField(max_length=12)
host_country = models.CharField(max_length=100, help_text="Destination")
host_type = models.CharField(choices=HOST_TYPE, max_length=10, help_text="Location type")
host_name = models.CharField(max_length=256, help_text="Name of host institution")
host_street = models.CharField(max_length=100, help_text="Street")
host_city = models.CharField(max_length=100, help_text="City")
host_district = models.CharField(max_length=100, help_text="District")
host_zipcode = models.CharField(max_length=100, help_text="Zipcode")
host_supervisor = models.CharField(max_length=256, help_text="Name of supervisor")
host_email = models.CharField(max_length=100, help_text="Email")
host_fax = models.CharField(max_length=100, blank=True, help_text="Fax.No.")
host_tel = models.CharField(max_length=100, help_text="Tel.No.")
start_date = models.DateField(help_text="Elective start date")
end_date = models.DateField(help_text="Elective end date")
subject = models.CharField(max_length=256,help_text="Tel.No.")
reasons = models.TextField(help_text="Please state briefly the reasons for this choice's location and subject")
outcomes = models.TextField(help_text="Please give upto to 4 outcomes that you hope to achieve during this elective")
your_mobile = models.CharField(max_length=100, blank=True, help_text="Please provide your mobile number if you are taking it with you")
insurance = models.BooleanField(default=False, help_text="Please confirm that you have arranged holiday insurance")
malpractice = models.BooleanField(default=False, help_text="Please confirm that you have medical malpractice cover")
groupinfo = models.CharField(max_length=256, blank=True, help_text="If you planning your Elective in a group, please list your fellow students")
modified = models.DateTimeField(auto_now_add=True)
class Meta:
get_latest_by = 'modified'
def __unicode__(self):
return u"[%s] %s, %s " % (self.id,self.host_name,self.subject)
Confirm that it's the redirect stage that's causing the problem by replacing
HttpResponseRedirect(url)
with
HttpResponse('<!DOCTYPE html><html><head><title>title</title></head><body>%(url)s</body></html>' % {'url':url})
If this doesn't render, then the problem is happening before the redirect. If it does render, then the problem may be the redirect, or it may be the redirected page. Click on the link. If the next page displays correctly, the problem is almost certainly the redirect itself. Otherwise, the problem is in the redirected page.