I am having difficulty reverse matching a url, getting the error:
NoReverseMatch at /patient/46cb4bd5-ef39-4697-84ff-9aa2b6e85e6b/
Reverse for 'treatment_detail' with no arguments not found. 1 pattern(s) tried: ['patient/(?P<patient_id>[^/]+)/$']
The url is:
/patient/46cb4bd5-ef39-4697-84ff-9aa2b6e85e6b/
(the string is the 'apatient_id' and changes each time the user submits the 'add' page)
urls.py is
app_name = "patient"
urlpatterns = [
path(
route='add/',
view=views.PatientAddView.as_view(),
name="patient_add"),
path(
route='<patient_id>/',
view=views.TreatmentTemplateView.as_view(),
name='treatment_detail'),
]
html
<form action="{% url 'patient:treatment_detail' %}" method="get">
<input type="submit" class="btn btn-primary" value="get_doc" name="get_doc">
</form>
views.py
class TreatmentTemplateView(TemplateView):
template_name = "../templates/patient/treatment_detail.html"
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context["patient_id"] = self.kwargs["patient_id"]
result = find_treatment(context["patient_id"])
context = result[0]
context["patient"] = result[1]
return context
class PatientAddView(LoginRequiredMixin, TemplateView):
model = Patient
template_name = "../templates/patient/add.html"
def get(self, *args, **kwargs):
patient_form = PatientForm
currentmed_formset = CurrentmedFormSet(queryset=CurrentMed.objects.none())
pastmed_formset = PastmedFormSet(queryset=PastMed.objects.none())
diagnosis_formset = DiagnosisFormSet(queryset=Diagnosis.objects.none())
problem_formset = ProblemFormSet(queryset=Problem.objects.none())
sideeffect_formset = SideeffectFormSet(queryset=SideEffect.objects.none())
return self.render_to_response(
{
"diagnosis_formset": diagnosis_formset,
"problem_formset": problem_formset,
"sideeffect_formset": sideeffect_formset,
"currentmed_formset": currentmed_formset,
"pastmed_formset": pastmed_formset,
"patient_form": patient_form,
"med_formsethelper": MedFormSetHelper,
"problem_formsethelper": ProblemFormSetHelper,
"diagnosis_formsethelper": DiagnosisFormSetHelper,
"sideeffect_formsethelper": SideEffectFormSetHelper,
}
)
def post(self, *args, **kwargs):
form = PatientForm(data=self.request.POST)
currentmed_formset = CurrentmedFormSet(data=self.request.POST)
pastmed_formset = PastmedFormSet(data=self.request.POST)
diagnosis_formset = DiagnosisFormSet(data=self.request.POST)
problem_formset = ProblemFormSet(data=self.request.POST)
sideeffect_formset = SideeffectFormSet(data=self.request.POST)
if form.is_valid():
print("pt_valid")
patient_instance = form.save()
patient_instance.user = self.request.user
patient_instance.save()
if diagnosis_formset.is_valid():
print("diag_valid")
diag_name = diagnosis_formset.save(commit=False)
for diag in diag_name:
diag.patient = patient_instance
diag.save()
if problem_formset.is_valid():
prob_name = problem_formset.save(commit=False)
for prob in prob_name:
prob.patient = patient_instance
prob.save()
if sideeffect_formset.is_valid():
se_name = sideeffect_formset.save(commit=False)
for se in se_name:
se.patient = patient_instance
se.save()
if currentmed_formset.is_valid():
med_name = currentmed_formset.save(commit=False)
for med in med_name:
med.patient = patient_instance
med.save()
if pastmed_formset.is_valid():
med_name = pastmed_formset.save(commit=False)
for med in med_name:
med.patient = patient_instance
med.save()
return redirect(
reverse(
"patient:treatment_detail",
kwargs={"patient_id": patient_instance.patient_id},
)
)
If I have 'patient:patient_add' instead of 'patient:treatment_detail' it works fine so the issue seems to be about the
route="<patient_id>"/
In urls.py
Your url route should include patient_id such that:
path(
route='<uuid:patient_id>/',
view=views.TreatmentTemplateView.as_view(),
name='treatment_detail'),
I assume you're using uuid field in your model.
You can take a look at the docs for more detail.
In your template, you should also pass uuid field to the template tag:
"{% url 'patient:treatment_detail' patient.patient_id %}"
Related
When I try to submit my form I get this message:
The view views.save_flow_data didn't return an HttpResponse object. It returned None instead.
Views.py
def save_flow_data(request):
if request.method == 'POST':
if request.POST.get('upload_flow') \
and request.POST.get('water_flow_rate')\
and request.POST.get('water_flow_rate_unit')\
data=CalcData()
data.water_flow_rate = request.POST.get('water_flow_rate')
data.water_flow_rate_unit = request.POST.get('water_flow_rate_unit')
data.save()
return render(request, 'io/flow.html')
else:
return render(request,'io/flow.html')
models.py
class CalcData(models.Model):
upload_flow = models.BooleanField(default=False)
water_flow_rate = models.DecimalField(max_digits=100, decimal_places=5)
water_flow_rate_unit = models.TextChoices('wfr_unit', 'm3/day m3/month')
datetime = models.DateTimeField(default=timezone.now)
submit button in form
<div>
<button action="{% url 'MyProject:save_flow_data' %}" type="submit" class="btn btn-light" style="width: 517.5px;" >Calculate</button>
</div>
urls.py
urlpatterns = [
path('', views.home, name='MyProject-home'),
path('io/flow/', views.io_flow, name='MyProject-io-flow'),
path('io/flow/save_flow_data', views.save_flow_data, name='save_flow_data')
]
I'm really not sure where to go from here. I had a perfectly working form but as soon as I scaled it up it flopped.
The case
if request.POST.get('upload_flow') \
and request.POST.get('water_flow_rate')\
and request.POST.get('water_flow_rate_unit')\
is False is not covered.
You need to either remove the last else :
def save_flow_data(request):
if request.method == 'POST':
if request.POST.get('upload_flow') \
and request.POST.get('water_flow_rate')\
and request.POST.get('water_flow_rate_unit')\
data=CalcData()
data.water_flow_rate = request.POST.get('water_flow_rate')
data.water_flow_rate_unit = request.POST.get('water_flow_rate_unit')
data.save()
return render(request, 'io/flow.html')
return render(request,'io/flow.html')
Or add a return to the uncovered path:
def save_flow_data(request):
if request.method == 'POST':
if request.POST.get('upload_flow') \
and request.POST.get('water_flow_rate')\
and request.POST.get('water_flow_rate_unit')\
data=CalcData()
data.water_flow_rate = request.POST.get('water_flow_rate')
data.water_flow_rate_unit = request.POST.get('water_flow_rate_unit')
data.save()
return render(request, 'io/flow.html')
return render(request, 'io/flow.html') # Or return something else
else:
return render(request,'io/flow.html')
Remove else statement and keep indentation of:
return render(request,'io/flow.html')
At function level.
I want to use django-import-export's forms to implement the import feature for regular users, so it needs to be outside the admin section.
So far, all the implementations I have found are about
a) extending the feature inside the admin or
b) reimplementing the default views outside the admin.
But since the default forms work perfectly (specially the ConfirmImportForm that shows a diff between old records and new records attempting to be imported) I would like to subclass them as part of my project (outside admin) without reimplementing the whole view's logic, if such thing is even possible.
So far I tried (foolishly, I'm afraid) to subclass the import_export.admin.ImportMixin as two separated class views to import a model Period with resource PeriodResource. The methods import_action and process_import were reimplemented (basically copy and paste the same code and eliminating any code using self.site_admin) as View.get() and View.post():
# staging/views.py
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.views import generic
from django.template.response import TemplateResponse
from django.utils.translation import gettext_lazy as _
from django.utils.encoding import force_text
from import_export.forms import ConfirmImportForm
from import_export.signals import post_import
import import_export.admin
from .models import Period
from .resources import PeriodResource
class PeriodImportView(import_export.admin.ImportMixin, generic.View):
"""
Subclassing of ImportMixin as a generic View implementing ImportForm
"""
#: template for import view
import_template_name = 'period/import.html'
#: resource class
resource_class = PeriodResource
#: model to be imported
model = Period
def get_confirm_import_form(self):
'''
Get the form type used to display the results and confirm the upload.
'''
return ConfirmImportForm
def get(self, request, *args, **kwargs):
"""
Overriding the GET part of ImportMixin.import_action method to be used without site_admin
"""
resource = self.get_import_resource_class()(**self.get_import_resource_kwargs(request, *args, **kwargs))
context = self.get_import_context_data()
import_formats = self.get_import_formats()
form_type = self.get_import_form()
form = form_type(import_formats,
request.POST or None,
request.FILES or None)
# context.update(self.admin_site.each_context(request))
context['title'] = _("Import")
context['form'] = form
context['opts'] = self.model._meta
context['fields'] = [f.column_name for f in resource.get_user_visible_fields()]
# request.current_app = self.admin_site.name
return TemplateResponse(request, [self.import_template_name],
context)
def post(self, request, *args, **kwargs):
"""
Overriding the POST part of ImportMixin.import_action method to be used without site_admin
"""
resource = self.get_import_resource_class()(**self.get_import_resource_kwargs(request, *args, **kwargs))
context = self.get_import_context_data()
import_formats = self.get_import_formats()
form_type = self.get_import_form()
form = form_type(import_formats,
request.POST or None,
request.FILES or None)
if request.POST and form.is_valid():
input_format = import_formats[
int(form.cleaned_data['input_format'])
]()
import_file = form.cleaned_data['import_file']
# first always write the uploaded file to disk as it may be a
# memory file or else based on settings upload handlers
tmp_storage = self.write_to_tmp_storage(import_file, input_format)
# then read the file, using the proper format-specific mode
# warning, big files may exceed memory
try:
data = tmp_storage.read(input_format.get_read_mode())
if not input_format.is_binary() and self.from_encoding:
data = force_text(data, self.from_encoding)
dataset = input_format.create_dataset(data)
except UnicodeDecodeError as ex1:
return HttpResponse(_(u"<h1>Imported file has a wrong encoding: %s</h1>" % ex1))
except Exception as ex2:
return HttpResponse(_(u"<h1>%s encountered while trying to read file: %s</h1>" % (type(ex2).__name__, import_file.name)))
result = resource.import_data(dataset, dry_run=True,
raise_errors=False,
file_name=import_file.name,
user=request.user)
context['result'] = result
if not result.has_errors() and not result.has_validation_errors():
context['confirm_form'] = self.get_confirm_import_form()(initial={
'import_file_name': tmp_storage.name,
'original_file_name': import_file.name,
'input_format': form.cleaned_data['input_format'],
})
# context.update(self.admin_site.each_context(request))
context['title'] = _("Import")
context['form'] = form
context['opts'] = self.model._meta
context['fields'] = [f.column_name for f in resource.get_user_visible_fields()]
# request.current_app = self.admin_site.name
return TemplateResponse(request, [self.import_template_name],
context)
class PeriodConfirmImportView(import_export.admin.ImportMixin, generic.View):
"""
Subclassing of ImportMixin as a generic View implementing ConfirmImportForm
"""
#: template for import view
import_template_name = 'period/import.html'
#: resource class
resource_class = PeriodResource
#: model to be imported
model = Period
def post(self, request, *args, **kwargs):
"""
Perform the actual import action (after the user has confirmed the import)
"""
# if not self.has_import_permission(request):
# raise PermissionDenied
confirm_form = ConfirmImportForm(request.POST)
if confirm_form.is_valid():
import_formats = self.get_import_formats()
input_format = import_formats[
int(confirm_form.cleaned_data['input_format'])
]()
tmp_storage = self.get_tmp_storage_class()(name=confirm_form.cleaned_data['import_file_name'])
data = tmp_storage.read(input_format.get_read_mode())
if not input_format.is_binary() and self.from_encoding:
data = force_text(data, self.from_encoding)
dataset = input_format.create_dataset(data)
result = self.process_dataset(dataset, confirm_form, request, *args, **kwargs)
tmp_storage.remove()
self.generate_log_entries(result, request)
self.add_success_message(result, request)
post_import.send(sender=None, model=self.model)
url = reverse('staging:index')
return HttpResponseRedirect(url)
and then just show the forms in the template:
# staging/templates/period/import.html
{% if confirm_form %}
<form action="{% url 'staging:confirm_import_period' %}" method="POST">
{% csrf_token %}
{{ confirm_form.as_p }}
<p>
{% trans "Below is a preview of data to be imported. If you are satisfied with the results, click 'Confirm import'" %}
</p>
<div class="submit-row">
<input type="submit" class="default" name="confirm" value="{% trans "Confirm import" %}">
</div>
</form>
{% else %}
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>
{% trans "This importer will import the following fields: " %}
<code>{{ fields|join:", " }}</code>
</p>
<fieldset class="module aligned">
{% for field in form %}
<div class="form-row">
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
{% if field.field.help_text %}
<p class="help">{{ field.field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
</fieldset>
<div class="submit-row">
<input type="submit" class="default" value="{% trans "Submit" %}">
</div>
</form>
{% endif %}
and my urls.py looks like this:
# staging/urls.py
from django.urls import path
from .views import PeriodIndexView, PeriodImportView, PeriodConfirmImportView
app_name = 'staging'
urlpatterns = [
path('period/', PeriodIndexView.as_view(), name='index'),
path('period/import/', PeriodImportView.as_view(), name='import_period'),
path('period/confirm_import/', PeriodConfirmImportView.as_view(), name='confirm_import_period'),
]
So far it works as intended, but this approach is so tightly coupled to the internal implementation of ImportMixin that I am afraid it will not survive any version upgrade of django-import-export.
Is there any way to achieve that without reimplementing the whole import_action and process_import methods?
After a lot of try and error I gave up on avoiding the re-implementation of methods import_action and process_import from import_export.admin.ImportMixin. Instead, I created my own mixins subclassing import_export.admin.ImportMixin and django.views.generic.View and removing all references to self.site_admin from methods import_action and process_import into equivalent methods get() and post().
# staging/views.py
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.views import generic
from django.template.response import TemplateResponse
from django.utils.translation import gettext_lazy as _
from django.utils.encoding import force_text
from import_export.forms import ConfirmImportForm
from import_export.signals import post_import
import import_export.admin
from .models import Period
from .resources import PeriodResource
class ImportView(import_export.admin.ImportMixin, generic.View):
"""
Subclassing of ImportMixin as a generic View implementing ImportForm
"""
#: template for import view
import_template_name = 'import.html'
#: resource class
resource_class = None
#: model to be imported
model = None
def get_confirm_import_form(self):
'''
Get the form type used to display the results and confirm the upload.
'''
return ConfirmImportForm
def get(self, request, *args, **kwargs):
"""
Overriding the GET part of ImportMixin.import_action method to be used without site_admin
"""
return self.post(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
"""
Overriding the POST part of ImportMixin.import_action method to be used without site_admin
"""
resource = self.get_import_resource_class()(**self.get_import_resource_kwargs(request,
*args,
**kwargs))
context = self.get_import_context_data()
import_formats = self.get_import_formats()
form = self.get_import_form()(import_formats, request.POST or None, request.FILES or None)
if request.POST and form.is_valid():
input_format = import_formats[
int(form.cleaned_data['input_format'])
]()
import_file = form.cleaned_data['import_file']
# first always write the uploaded file to disk as it may be a
# memory file or else based on settings upload handlers
tmp_storage = self.write_to_tmp_storage(import_file, input_format)
# then read the file, using the proper format-specific mode
# warning, big files may exceed memory
try:
data = tmp_storage.read(input_format.get_read_mode())
if not input_format.is_binary() and self.from_encoding:
data = force_text(data, self.from_encoding)
dataset = input_format.create_dataset(data)
except UnicodeDecodeError as ex1:
return HttpResponse(_(u"<h1>Imported file has a wrong encoding: %s</h1>" % ex1))
except Exception as ex2:
return HttpResponse(_(u"<h1>%s encountered while trying to read file: %s</h1>" % (type(ex2).__name__, import_file.name)))
result = resource.import_data(dataset, dry_run=True,
raise_errors=False,
file_name=import_file.name,
user=request.user)
context['result'] = result
if not result.has_errors() and not result.has_validation_errors():
context['confirm_form'] = self.get_confirm_import_form()(initial={
'import_file_name': tmp_storage.name,
'original_file_name': import_file.name,
'input_format': form.cleaned_data['input_format'],
})
# context.update(self.admin_site.each_context(request))
context['title'] = _("Import " + self.get_model_info()[1])
context['form'] = form
context['opts'] = self.model._meta
context['fields'] = [f.column_name for f in resource.get_user_visible_fields()]
# request.current_app = self.admin_site.name
return TemplateResponse(request, [self.import_template_name],
context)
class ConfirmImportView(import_export.admin.ImportMixin, generic.View):
"""
Subclassing of ImportMixin as a generic View implementing ConfirmImportForm
"""
#: template for import view
import_template_name = 'import.html'
#: resource class
resource_class = None
#: model to be imported
model = None
def get_confirm_import_form(self):
'''
Get the form type used to display the results and confirm the upload.
'''
return ConfirmImportForm
def post(self, request, *args, **kwargs):
"""
Perform the actual import action (after the user has confirmed the import)
"""
confirm_form = self.get_confirm_import_form()(request.POST)
if confirm_form.is_valid():
import_formats = self.get_import_formats()
input_format = import_formats[
int(confirm_form.cleaned_data['input_format'])
]()
tmp_storage = self.get_tmp_storage_class()(name=confirm_form.cleaned_data['import_file_name'])
data = tmp_storage.read(input_format.get_read_mode())
if not input_format.is_binary() and self.from_encoding:
data = force_text(data, self.from_encoding)
dataset = input_format.create_dataset(data)
result = self.process_dataset(dataset, confirm_form, request, *args, **kwargs)
tmp_storage.remove()
self.generate_log_entries(result, request)
self.add_success_message(result, request)
post_import.send(sender=None, model=self.model)
url = reverse('{}:{}_index'.format(self.get_model_info()[0], self.get_model_info()[1]))
return HttpResponseRedirect(url)
So now from my custom mixins ImportView and ConfirmImportView y can subclass the specific classes to import my specific models just setting the model and resource_class attributes, which was sort of what I was looking for.
class PeriodImportView(ImportView):
"""
ImportView specific for model Period and resource PeriodResource
"""
#: resource class
resource_class = PeriodResource
#: model to be imported
model = Period
class PeriodConfirmImportView(ConfirmImportView):
"""
ConfirmImportView specific for model Period and resource PeriodResource
"""
#: resource class
resource_class = PeriodResource
#: model to be imported
model = Period
I am trying to get it so anytime my function delete_curricula_info is activated it then redirects to CurriculumClasses url
class CurriculumClasses(TemplateView):
template_name = 'architect/assignclasses.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form'] = AssignClassForm(self.request.GET or None)
context['classes'] = Classes.objects.all()
context['curricula_infos'] = CurriculaInfo.objects.all()
context['course_abbr'] = self.kwargs.get('course_abbr')
context['year'] = self.kwargs.get('year')
context['semester'] = self.kwargs.get('semester')
context['module_abbr'] = self.kwargs.get('module_abbr')
context['curricula'] = Curricula.objects.get(
course_period__course__course_abbreviation=self.kwargs.get('course_abbr'),
module_period__module__module_abbreviation=self.kwargs.get('module_abbr'),
course_period__period__academic_year=self.kwargs.get('year'),
course_period__period__semester=self.kwargs.get('semester')).pk
return context
def delete_curricula_info(request, pk):
curricula_info = get_object_or_404(CurriculaInfo, pk=pk)
curricula_info.delete()
return redirect('curriculum_classes')
Heres my urls.py
path('courses/<str:course_abbr>/<str:module_abbr>/<int:year>/<int:semester>/classes/',
views.CurriculumClasses.as_view(), name='curriculum_classes'),
path('delete-curricula-info/<int:pk>/', views.delete_curricula_info, name='delete_curricula_info')
The url for my CurriculumClasses is using a dynamic one so i could not hardcode the url to the return redirect of my function. So how do i redirect as my current method does not work. Thanks.
You can redirect it like this:
from django.urls import reverse
def delete_curricula_info(request, pk):
curricula_info = get_object_or_404(CurriculaInfo, pk=pk)
curricula_info.delete()
course_abbr = 'xxx'
module_abbr = 'xxx'
year = 2018
semester = 1
args = (course_abbr, module_abbr, year, semester)
return redirect(reverse('curriculum_classes', args=args))
I am using Django forms in in forms I need a variable from views.py named 'layer_id'. So I get it like
self.form = labelModelForm(layer_id=self.layer.id)
and used in forms.py like
class labelModelForm(forms.ModelForm):
model = Labels_tool_
def __init__(self, *args , **kwargs):
layer_id = kwargs['layer_id']
apn= forms.ModelChoiceField(queryset=Field.objects.filter(layer=layer_id).values_list('name', flat=True) ,empty_label="(Choose field)")
So now when I run program no dropdown list appear. Where I am wrong ? As layer_id I am getting is correct in form in view.py
My View.py file is
def ImportLabelView(self):
urlItems =self.request.path.split('/')
i = urlItems.index('layers')
self.form = labelModelForm(layer_id=self.layer.id)
if self.request.method == 'POST':
self.layer = Layer.objects.filter(id=urlItems[i + 1],map=self.map.id).first()
layerid= self.layer.id
labmapid=self.map.id
OwnerName = self.request.POST.get('owner_name')
MailingAddrOne = self.request.POST.get('mailing_addr_One')
mailingaddrTwo = self.request.POST.get('mailing_addr_Two')
ApN = self.request.POST.get('apn')
situsaddrTwo = self.request.POST.get('situs_addr_Two')
situsaddrOne = self.request.POST.get('situs_addr_One')
if Labels_tool_.objects.filter(map_id_labels=labmapid ,layer_id_labels=layerid).exists():
Labels_tool_.apn = Labels_tool_.objects.filter(map_id_labels = labmapid , layer_id_labels = layerid).update(apn=ApN)
Labels_tool_.owner_name = Labels_tool_.objects.filter(map_id_labels=labmapid, layer_id_labels=layerid).update(owner_name=OwnerName)
Labels_tool_.mailing_addr_One = Labels_tool_.objects.filter(map_id_labels=labmapid,
layer_id_labels=layerid).update(mailing_addr_One=MailingAddrOne)
Labels_tool_.mailing_addr_Two = Labels_tool_.objects.filter(map_id_labels=labmapid,
layer_id_labels=layerid).update(mailing_addr_Two=mailingaddrTwo)
Labels_tool_.situs_addr_One = Labels_tool_.objects.filter(map_id_labels=labmapid, layer_id_labels=layerid).update(situs_addr_One=situsaddrOne)
Labels_tool_.situs_addr_Two = Labels_tool_.objects.filter(map_id_labels=labmapid, layer_id_labels=layerid).update(situs_addr_Two=situsaddrTwo)
else:
labels_tool = Labels_tool_()
labels_tool.apn = self.request.POST.get('apn')
labels_tool.owner_name = self.request.POST.get('owner_name')
labels_tool.mailing_addr_One= self.request.POST.get('mailing_addr_One')
labels_tool.mailing_addr_Two= self.request.POST.get('mailing_addr_Two')
labels_tool.situs_addr_One = self.request.POST.get('situs_addr_One')
labels_tool.situs_addr_Two = self.request.POST.get('situs_addr_Two')
labels_tool.map_id_labels = self.map.id
labels_tool.layer_id_labels = self.layer.id
labels_tool.save()
# self.form = self.layer.form(self.request.POST)
return self.redirect('mapport.maps.layers.importlabel', self.map.id, self.layer.id)
return self.render('mapport/maps/layers/Labels_detail.html')
And template file is
<form action="" method="post" id="label_form">{% csrf_token %}
<div id="field1"><p id="apn_text">APN: </p> {{ form.apn}}</div>
Models are like
class pdftabel_tool_(models.Model):
apn = models.CharField(null=True, blank=False, max_length=255)
Now where I am making mistake that value from view.py is correct but not dropdown showing ?
You need to set self.fields, not self.initial.
You should define the field in the normal way at class level, then modify the queryset in the init method.
class labelModelForm(forms.ModelForm):
apn = forms.ModelChoiceField(queryset=Field.objects.none())
def __init__(self, *args, **kwargs):
layer_id = kwargs.pop('layer_id', None)
super(labelModelForm, self).__init__(*args, **kwargs)
self.fields['apn'].queryset = Field.objects.filter(layer=layer_id)
Here is my html:
{% block my_dashboard_main %}
<form action="status/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
My urls.py:
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'status/$', views.status),
url(r'thanks/$', views.thanks),
)
Here is my views.py:
STATUS_CHOICES = (
("GOOD", "Good"),
("BAD", "Bad"),
("COMPROMISED", "Compromised")
)
def thanks(request):
return render(request, "my_dashboard/ssa_panel/sent.html')
class SsaForm(forms.Form):
status = forms.ChoiceField(choices = STATUS_CHOICES, label="Status:")
def status(request):
print("STATUS CALLED method=",request.method)
if request.method == 'POST': # If the form has been submitted...
form = SsaForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
print("redirect to THANKS!")
return HttpResponseRedirect('thanks/') # Redirect after POST
else:
print("Requesting form\n")
form = SsaForm(initial = {"status", "Good"}) # An unbound form
return render(request, 'my_dashboard/ssa_panel/index.html', {
'form': form,
})
class IndexView(views.APIView):
# A very simple class-based view...
template_name = 'my_dashboard/ssa_panel/index.html'
def get_data(self, request, context, *args, **kwargs):
print("GET_DATA Called", context)
# Add data to the context here...
return context
The first time my page renders the I want the status to show up. It doesn't. Just the Submit button. After I submit once the "Status: [Good] <- combo box" is there. I want to go get the data for the for status in get_data and set it but I don't know how. do I set context['status']="Good" or something like that?
I'm obviously new to DJango and REST stuff.
You are trying to construct your initial value dictionary incorrectly using a comma (,) instead of a colon and also using the wrong choice key. Instead of
form = SsaForm(initial = {"status", "Good"})
try
form = SsaForm(initial = {"status": "GOOD"})