I am having form which creates Ipd and Ipd model is created using patient model with one to many relationship, and I am already having one table with patient list in urls.
I am trying to create the list of all Ipd that are created using form, I am trying to redirect the form page to Idp list after I submit for Ipd form but ending with this error "NoReverseMatch at /1/ipd/",
One thing I want to clear is each Ipd is having unique id and Ipd is created from patient with one to many relationship which also have another unique id , the number which is in the error is patient id
views.py
#login_required
def ipd(request, patient_id):
object = get_object_or_404(Patient,pk=patient_id)
if request.method == "POST":
formtwo = IpdForm(request.POST)
if formtwo.is_valid() :
instance = formtwo.save(commit=False)
instance.save()
return HttpResponseRedirect(reverse('ipd_list', args=[patient_id]))
else:
return HttpResponse(formtwo.errors)
else:
formtwo = IpdForm()
return render(request, 'newipd.html', {'object':object, 'form2': formtwo})
#login_required
def ipd_list(request):
ipdlist = Ipd.objects.all()
return render(request, 'Ipdlist.html', {'ipd': ipdlist })
urls.py
re_path(r'^$', my_patient.index, name='home'), <-- patient list-->
re_path(r'^(?P<patient_id>\d+)/ipd/$', my_patient.ipd, name='ipd'),
path(r'^ipdlist/', my_patient.ipd_list,name='ipdlist' ),
Template
<ul>
<li>Indoor Patient Department</span></li>
</ul>
########
in ipdform
<form class="col s12" role="form" action="{% url 'ipd_list' 'patient_id' %}" method="post" enctype="multipart/form-data"> {% csrf_token %}
You have to remove args=[patiend_id] since you are returning to the ipd_list
return HttpResponseRedirect(reverse('ipd_list'))
You are trying to redirect user to ipdlist url instead with patameters. As this is a list method you shouldn't do that. You need to change:
#login_required
def ipd(request, patient_id):
object = get_object_or_404(Patient,pk=patient_id)
if request.method == "POST":
formtwo = IpdForm(request.POST)
if formtwo.is_valid() :
instance = formtwo.save(commit=False)
instance.save()
return HttpResponseRedirect(reverse('ipd_list'))
else:
return HttpResponse(formtwo.errors)
else:
formtwo = IpdForm()
return render(request, 'newipd.html', {'object':object, 'form2': formtwo})
#login_required
def ipd_list(request):
ipdlist = Ipd.objects.all()
return render(request, 'Ipdlist.html', {'ipd': ipdlist })
Related
I am trying to create a page where I can create a new entry/note to a list and also update an existing list on one HTML page. The problem is create() does not require a primary key. However, update() requires existing primary key. How can do I do this in django? Do I create a new function in views.py? Example:
def new_note(request, note_id=None):
if note_id == None:
notes(request) #function that just uses create()
else:
note_sad(request, note_id) #sad=save and delete using update() and delete()
views.py sample function for entering notes:
def notes(request):
if request.method == 'GET':
notes = Note.objects.all().order_by('note_id')
form = NoteForm()
return render(request=request,
template_name='notes.html',
context={
'notes': notes,
'form': form
})
# when user submits form
if request.method == 'POST':
form = NoteForm(request.POST)
if form.is_valid():
note = form.cleaned_data['note']
Note.objects.create(note=note)
# "redirect" to the todo homepage
return HttpResponseRedirect(reverse('new_note'))
views.py function for creating a new entry/note:
def note_sad(request, note_id):
if request.method == 'GET':
note = Note.objects.get(pk=note_id)
form = NoteForm(initial={'note_text': note.note_text})
return render(request=request,
template_name='notes.html',
context={
'form': form,
'note_id': note_id
})
if request.method == 'POST':
if 'save' in request.POST:
form = NoteForm(request.POST)
if form.is_valid():
note = form.cleaned_data['note']
Note.objects.filter(pk=note_id).update(note_text=note)
elif 'delete' in request.POST:
Note.objects.filter(pk=note_id).delete()
return HttpResponseRedirect(reverse('new_note'))
There are many ways to pass the ID to note_sad for updating the object. One way is when you display the items on your HTML and add Id for each submit button as follows:
{% for note in notes %}
<input type='submit' value='{{note.pk}}' name='pk'>
{% end for %}
Alternatively, you may add the Id to the form as follows:
<form method = "post" action="{% url 'note_sad' note.pk %}">
{% csrf_token %}
</form>
<form action="{% url 'create'%}" method="POST" >
{% csrf_token %}
this in my template file.
def create(request):
return render(request, "auctions/create.html")
if request.method == "POST":
title = request.GET["title"]
des = request.GET["description"]
bid = request.GET["startingBid"]
imageurl= request.GET[ "imageUrl"]
category = request.GET["category"]
image = request.GET["image"]
listing= Auctionlisting(request,title=title,description=des,startingBid=bid,imageUrl=imageurl,category=category)
return render(request, "auctions/index.html",{
"listing":Auctionlisting.objects.all()
})
and this is in my views.py.
still after using csrf token i am getting 403 forbidden error. please some guide me.
Also these title, description and all are my inputs...
Just re-arrange your code like this:
def create(request):
if request.method == "POST":
title = request.GET["title"]
des = request.GET["description"]
bid = request.GET["startingBid"]
imageurl= request.GET[ "imageUrl"]
category = request.GET["category"]
image = request.GET["image"]
listing= Auctionlisting(request,title=title,description=des,startingBid=bid,imageUrl=imageurl,category=category)
listing.save() # save before getting them from database
return render(request, "auctions/index.html",{
"listing":Auctionlisting.objects.all()
})
else:
return render(request, "auctions/create.html")
I want to pass a query string e.g., ?refcode='A1234' to a hidden field called inbound_referral_code in a ModelForm.
My model is as follows:
class User(models.Model):
email = models.EmailField(max_length=255, blank=False, unique=True)
inbound_referral_code = models.CharField(max_length=255)
My ModelForm is currently as follows:
class UserForm(forms.ModelForm):
model = User
fields = ['email', 'inbound_referral_code']
widgets = {'inbound_referral_code': forms.HiddenInput()}
My View is:
def register(request):
if request.method == 'POST':
form = UserForm(request.POST)
[...]
else:
form = UserForm()
return render(request, 'register.html', {'form': form})
And my template is currently:
<form action="{% url 'register' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit"/>
</form>
Two questions:
How do I assign ?refcode parameter to inbound_referral_code field?
What happens if ?refcode isn't provided?
Combining the different answers, the following solution worked:
Set the "initial" value of the form parameter, and ensure the template renders with the bound form if validation fails. The correct view function is:
def register(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
return redirect([...])
else:
refcode = request.GET.get('refcode')
form = UserForm(intial={'inbound_referral_code': refcode)
return render(request, 'register.html', {'form': form})
Note that the bottom return render(...) needed to be moved so that it is also called with the form from the POST request if it contains validation errors...
To assign the refcode, you need to pass it into the form, so you pass in something other than request.POST that contains it, change it before
dict = request.POST.copy()
dict["inbound_referral_code"] = request.POST.get("refcode")
form = UserForm(dict)
# ...
or after validating:
if form.is_valid():
form.cleaned_data["inbound_referral_code"] = request.POST.get("refcode")
If it isn't provided, you can check for that and pass a custom value, or set a default when defining the form/model.
To set it in the template, you can pass an initial value
else:
form = UserForm(initial={"inbound_referral_code": "ref-value-here"})
return render(request, 'register.html', {'form': form})
I am trying to create a frontend form in my Django site that will allow users to add entries to my SQL database.
But when I use the form nothing happens in my database. What am I doing wrong?
I thought the right way would be to use the ModelForm technique.
My models looks like this:
class Actor(models.Model):
name = models.CharField(max_length=200)
wage = models.IntegerField(default=3100)
def __str__(self):
return self.name
So I wrote this in my forms.py:
from django import forms
from .models import Actor
class ActorForm(forms.ModelForm):
class Meta:
model = Actor
fields = ['name', 'wage']
form = ActorForm()
I then added this to my views.py:
def get_actor(request):
if request.method == 'POST':
form = ActorForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/scenes/thanks/')
else:
form = ActorForm()
return render(request, 'scenes/actor.html', {'form': form})
def thanks(request):
return render(request, 'scenes/thanks.html',)
And this in a template called actors.html
<form action="/scenes/actor/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
You have to call the model form's save() method after checking that it's valid:
def get_actor(request):
if request.method == 'POST':
form = ActorForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/scenes/thanks/')
else:
form = ActorForm()
return render(request, 'scenes/actor.html', {'form': form})
I have a view called "search" which stores POST input as "search_id" but "search_id" is only available in the scope of the view "search". I want to be able to access the variable "search_id" in my view "dispTable".
Disclaimer- if this part of my question makes no sense, plz ignore: I understand that I could add an additional parameter to dispTable which would allow me to pass the search_id into dispTable in a return statement but what if I wanted to be able to access search_id in multiple views.
def search(request):
if request.method == 'POST' :
search_id = request.POST.get('textfield', None)
try:
return dispTable(request)
except Person.DoesNotExist:
return HttpResponse("no such user")
except Person.MultipleObjectsReturned :
#return dispTable(request, search_id)
return showResults(request)
else :
return render(request, 'People/search.html')
def dispTable(request) :
table = authTable(Person.objects.filter(MAIN_AUTHOR = 'search_id'))
RequestConfig(request).configure(table)
#return render(request, 'People/tableTemp.html', {'table':table})
return render(request, 'People/tableTemp.html', {"table" : Person.objects.filter(MAIN_AUTHOR = search_id)})
I also tried using a form, but I still did not know how to access the input variable in additional views, like dispTable
from django import forms
class SearchForm(forms.Form) :
search_id = forms.CharField(max_length=100)
def process(self) :
search_id = self.cleaned_data['search_id']
def search(request) :
if request.method == 'POST' :
form = SearchForm(request.POST)
if form.is_valid() :
form.process()
return dispTable(request)
else :
form = SearchForm()
return render (request, 'People/search.html')
And here is my html file:
<form method="POST" action="send/">
{% csrf_token %}
<input type="text" name="textfield">
<button type="submit">Upload text</button>
</form>