Django forms breaking in IE7 - django

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.

Related

Getting top 3 most enrolled course by students

I am building a website where an instructor can create courses and students can enroll the courses. Is there any way to display top 3 most enrolled courses by students that an instructor has created?
I have tried using .values().annotate().order_by()[] but it seems that i cant display it on template.
models.py
class Enrollment(models.Model):
student = models.ForeignKey(User, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
enrollment_date = models.DateField(auto_now_add=True, null = True)
class Course(models.Model):
user = models.ForeignKey(Users, on_delete = models.CASCADE)
media = models.ImageField(upload_to = 'media/course')
title = models.CharField(max_length=300, null = False)
subtitle = models.CharField(max_length=500, null = False)
description = models.TextField(max_length=5000, null = False)
language = models.CharField(max_length=20, null = False, choices=LANGUAGE)
level = models.CharField(max_length=20, null = False, choices=LEVEL)
category = models.CharField(max_length=30, null = False, choices=CATEGORY)
subcategory = models.CharField(max_length=20, null = False)
price = models.FloatField(null = True)
roles_responsibilities = models.TextField(max_length=2500, null = False)
timeline_budget = models.TextField(max_length=250, null = False)
req_prerequisite = models.TextField(max_length=2500, null = False)
certificate = models.CharField(max_length=5, null = False, choices=CERTIFICATE)
slug = AutoSlugField(populate_from='title', max_length=500, unique=True, null=True)
views.py
def instructorDashboard(request):
student = Enrollment.objects.filter(course__in=course)
popular_courses= student.values('course__title').annotate(count=Count('course__title')).order_by('-count')[:3]
print(popular_courses)
context = {
'popular_courses': popular_courses,
}
return render(request, 'instructor_dashboard/index.html', context)
index.html
<!-- Popular Courses -->
<div class="col-xl-4 col-lg-5">
<div class="card shadow mb-4">
<!-- Card Header - Dropdown -->
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-primary">Popular Courses</h6>
</div>
{% for popular_course in popular_courses %}
<div class="card-body">
{{ course.title }}
</div>
{% endfor %}
</div>
</div>
Expected: Get the list of courses having more enrollments.
In Django, if we are using ForeignKey, you can easily get all the rows(Enrollment) that are in a relationship with a single row(Course) using the 'realted_name' parameter.
models.py
class Enrollment(models.Model):
student = models.ForeignKey(User, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='enrollment')
enrollment_date = models.DateField(auto_now_add=True, null = True)
views.py
# Get the user object and filter the course that are created by user.
# Retrieve all the enrollments for every course created by user and sort in descending order.
# courses_list will be having all the courses that are created by the user.
courses_ranking = []
for course in courses_list:
courses_ranking.append({'course_id': course.id, 'count':course.enrollment.count()})
# After this, courses_ranking will be having list of dict objects that contains courses_id and specific enrollment count. If you sort that dictionary based on the "count" key, you will get the required sorted list.
result = sorted(courses_ranking, key=lambda x: x[1], reverse=True)
# result will have list of courses with highest to lowest enrollments(descending order).

Django Upload Folder is always Empty (This field is required issue)

I would like to upload a folder to my application but on the server side the request.FILES collection is always empty.
Also form.is_valid evaluates to false
The solution for this problem seems to be to add enctype="multipart/form-data" but I have already added it an it doesn't work.
As described here SO TOPIC ABOUT THIS
Inside the browser I also get "This field is required" after pressing submit and yes I have choosen a directory.
Here my relevant code
model.py
# Create your models here.
class Datasets(models.Model):
dataset_name = models.CharField(max_length=100, blank=True, null=True)
description = models.CharField(max_length=1000, blank=True, null=True)
share_with = models.ManyToManyField(User)
uploaded_by = models.CharField(max_length=1000, blank=True, null=True)
upvotes = models.IntegerField(null=False, default=0)
downvotes = models.IntegerField(null=False, default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
datafiles = models.FileField(blank=True, null=True)
form.py
class UploadDatasetForm(forms.Form):
dataset_name = forms.CharField(
max_length=1000,
widget=forms.TextInput(attrs={'class': 'form-control'}))
description = forms.CharField(
max_length=1000,
widget=forms.TextInput(attrs={'class': 'form-control'}))
share_with = forms.MultipleChoiceField(
choices=tuple(UserProfile.objects.values_list('id', 'full_name')),
widget=forms.CheckboxSelectMultiple,
)
datafiles = forms.FileField(widget=forms.ClearableFileInput(
attrs={
'multiple': True,
'webkitdirectory': True,
'directory': True,
}))
the template
{% block content %}
<h2>Register Here</h2>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
view.py
#login_required
def upload_dataset(request):
print(request.user)
form = UploadDatasetForm()
if request.method == "POST":
print('Receiving a post request')
form = UploadDatasetForm(request.POST, request.FILES)
print(request.FILES)
if form.is_valid():
print("The form is valid")
print(form.cleaned_data)
dataset_name = form.cleaned_data['dataset_name']
description = form.cleaned_data['description']
datafiles = form.cleaned_data['datafiles']
share_with = form.cleaned_data['share_with']
users_to_share_with = set()
print(datafiles)
instance = Datasets.objects.create(
uploaded_by=request.user,
dataset_name=dataset_name,
description=description,
datafiles = datafiles,
upvotes=0,
downvotes=0,
)
for i in share_with:
instance.share_with.add(i)
return redirect("public:data")
print("The Dataset has been uploaded")
context = {"form": form}
return render(request, "upload_dataset.html", context)
{% endblock %}
I receive the message Receiving a post request but it will not go inside the form.is_valid
The output after pressing the submit button is
System check identified no issues (0 silenced).
July 25, 2021 - 11:42:53
Django version 3.2.3, using settings 'platform_oliveoils.settings'
Starting development server at http://0.0.0.0:40/
Quit the server with CONTROL-C.
Max
Receiving a post request
<MultiValueDict: {}>

Every field in Django modelform shows "Select a valid choice. That choice is not one of the available choices."

I've already read many other threads complaining about this error message but I still can't figure this out. I try removing the fields that give the error, and the error message just moves to another field the next time I try to submit. They are CharField, Foreign Key, and other types.
forms.py
class TemporaryresponseForm(forms.ModelForm):
gender_custom = forms.CharField(
required=False,
label="",
)
ethnicity = forms.ModelChoiceField(
queryset=Ethnicity.objects.all(),
widget=forms.RadioSelect(),
empty_label=None,
required=True,
label="Which of the following best describes your ethnicity?"
)
...
class Meta:
model = Temporaryresponse
fields = [...'gender_custom', 'ethnicity',...]
views.py
def tr(request):
if request.method == "POST":
form = TemporaryresponseForm(request.POST)
if form.is_valid():
tempresponse = form.save(commit=False)
tempresponse.ip = "123456"
tempresponse.save()
return redirect('politicalpollingapp/index.html')
else:
form = TemporaryresponseForm()
return render(request, 'politicalexperimentpollapp/tr.html', {'form': form})
def nr(request, pk):
return render(request, 'politicalexperimentpollapp/nr.html', {'tempresponse': tempresponse})
tr.html template
{% extends 'politicalexperimentpollapp/base.html' %}
{% block extrahead %}
{% load crispy_forms_tags %}
{{ form.media }}
{% endblock extrahead%}
...
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<div><br></div>
<div class="text-center"><button type="submit" class="save btn btn-primary">CONTINUE</button></div>
</form>
..
models.py
class Ethnicity(models.Model):
ethnicity = models.CharField(max_length=200)
def __str__(self):
return '%s' % (self.ethnicity)
...
class Temporaryresponse(models.Model):
birth_year = models.PositiveIntegerField()
voting_registration = models.ForeignKey(Voting_registration, models.SET_NULL, null=True)
party_identification = models.ForeignKey(Party_identification, models.SET_NULL, null=True)
gender = models.ForeignKey(Gender, models.SET_NULL, null=True)
gender_custom = models.CharField(max_length=200, blank=True)
ethnicity = models.ForeignKey(Ethnicity, models.SET_NULL, null=True)
race = models.ManyToManyField(Race)
zip_code = models.IntegerField()
ip = models.CharField(max_length=200, blank=True)
policy_areas_of_importance = models.ManyToManyField(Policy_category, blank=True)
likelihood_of_voting = models.PositiveIntegerField(models.SET_NULL, null=True, blank=True)
Oddly no error shows up in my Chrome console - it's only because I am showing errors on the actual page. I'm not sure if that's normal. Thanks in advance for any help, I'm ripping my hair out at this point.
I discovered that I was using the wrong language for the "race" form field. I had used ModelChoiceField but it should be ModelMultipleChoiceField as follows:
race = forms.ModelMultipleChoiceField(queryset=Race.objects.all(), widget=forms.CheckboxSelectMultiple, label="5. Which of the following best describes your race? Please select all that apply.")

Disable field in Django on condition

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

Only show object once and count it

after searching for a long time without getting an answer i'm gonna try here.
I'm working on django. My project is a mailling system, each time a recipient open a mail i know what mail get opened who opened it and when it get opened.
Here is the table where i display the stats. It shows me every recipient and the datetime, but my problem is that i want to see every recipient once, and then to show how many times it get opened.
<tbody>
{% for stat_mail in stat_mail %}
{% ifchanged stat_mail.recipient %}
<tr>
<td>{{ stat_mail.recipient }}</td>
<td>{{ stat_mail.datetime }}</td>
<td>{{ stat_mail.recipient_set.all|length }}</td>
</tr>
{% endifchanged %}
{% endfor %}
</tbody>
For example :
Test 1 opened the mail at 5PM and at 8PM, so the table should display
Test 1 / 5PM, 8PM / 2
The name of the recipient, the date of the oppening, and the number of oppening.
Sorry for the bad english but i'm french :)
Hope someone can help me, if u have other question or need more code just ask.
Thanks a lot !
EDIT : My models.py
class Recipient(models.Model):
name = models.CharField(max_length=255, verbose_name= ('Nom'), null=True, blank=True)
first_name = models.CharField(max_length=255, verbose_name= ('Prénom'), null=True, blank=True)
mail = models.EmailField(verbose_name= ('Adresse du destinataire'))
def __unicode__(self):
return u'%s %s' % (self.name, self.first_name)
class Tag(models.Model):
name = models.CharField(max_length=255, blank=False)
recipients = models.ManyToManyField(Recipient, verbose_name='Destinataires', null=False, blank=False, related_name="tags")
def __unicode__(self):
return self.name
class Mail(models.Model):
subject = models.CharField(max_length=255, verbose_name= ('Sujet'), blank=False, null=False)
content = HTMLField(verbose_name= ('Contenu'), blank=False, null=False, default=' ')
tags = models.ManyToManyField(Tag, verbose_name= ('Destinataires'), null=True, blank=True, related_name='mails')
recipients = models.ManyToManyField(Recipient, verbose_name='Destinataires', null=True, blank=True, related_name='mails')
date_create = models.DateTimeField(verbose_name= ('Date de création'), default=datetime.now, blank=False, editable = False)
writer = models.ForeignKey(Intervenant, verbose_name= ('Personne écrivant la compagne'), null=True, blank=True)
holding = models.ForeignKey(Holding, verbose_name= ('Organisation'),related_name= ('Questionnaire_mail'), null=False, blank=False, default=1, editable = False)
sended = models.BooleanField(verbose_name = ('Compagne envoyée ?'), default=False, editable=False)
opened = models.IntegerField(verbose_name=("Nombre totale d'ouverture"), default=0, editable=False)
email = models.EmailField(verbose_name='Destinataire de Test', blank=True, null=True)
date_create = models.DateTimeField(verbose_name= ('Date de création'), default=datetime.now, blank=False, editable = False)
date_sent = models.DateTimeField(verbose_name= ('Date de création'), blank=True, null=True, editable = False)
def __unicode__(self):
return self.subject
class Mail_Stats(models.Model):
mail = models.ForeignKey(Mail, verbose_name= ('Compagne'), related_name='mails_stats')
recipient = models.ForeignKey(Recipient, verbose_name= ('Destinataires'), null=True, blank=True, related_name='mails_stats')
datetime = models.DateTimeField(verbose_name= ('Date et Heure'), auto_now_add=True)
You should prepare your data in the view and then pass it to the template. Something like this (untested):
from django.shortcuts import render
from .models import Mail_Stats
def stats_view(request):
recipient_list = [] # this will be put in the template context
current_recipient = None
cnt_read = 0
read_datetime_list = []
for stat in Mail_Stats.objects.all().order_by('mail', 'recipient'):
if stat.recipient != current_recipient:
if cnt_read > 0:
recipient_list.append({
'recipient': current_recipient,
'read_datetime_list': read_datetime_list,
'cnt_read': cnt_read
})
current_recipient = stat.recipient
cnt_read = 0
read_datetime_list = []
cnt_read += 1
read_datetime_list.append(stat.datetime)
# add last recipient to the list, if not None
if current_recipient is not None:
recipient_list.append({
'recipient': current_recipient,
'read_datetime_list': read_datetime_list,
'cnt_read': cnt_read
})
render(request, 'mail_stats.html', { 'recipient_list': recipient_list })
Then in your template you could simply do something like this:
<tbody>
{% for r in recipient_list %}
<tr>
<td>{{ r.recipient }}</td>
<td>
<ul>
{% for dt in r.read_datetime_list %}
<li>{{ dt }}</li>
{% endfor %}
</ul>
</td>
<td>{{ r.cnt_read }}</td>
</tr>
{% endfor %}
</tbody>
The important thing is: do not struggle doing complex stuff in templates, keep them only for presentation purposes. Move all logic in the view (or models, or utility modules), there you can leverage all the power of Python.