I have a blog that uses markdown. I am trying to convert it to HTML in views.py with python markdown. For individual posts, this code works:
def detail_view(request, slug):
md = markdown.Markdown()
post = get_object_or_404(Post, slug=slug)
postcontent = md.convert(post.md_text)
context = {...}
return render(request, 'details.html', context)
However, applying the same logic to a view meant to show multiple posts fails:
def home_view(request):
posts = Post.objects.order_by('-id')
md = markdown.Markdown()
for markdown in posts:
postcontent = md.convert(posts.md_text)
context = {...}
return render(request, 'home.html', context)
What would I need to change to convert the text_md field(s) of my Post model in this view? Is .convert() the right method?
Thanks in advance!
Related
I'm building a website, to be used in dental practices, however I'm having trouble with the URL routing. I'm wanting af URL pattern like: Denthelp/kartotek/#nameofclinic#/opretpatient.
My suggestion looks like this:
urls.py:
path('kartotek/<str:kl_id>/', views.kartotek, name="kartotek"),
path('kartotek/<str:kl_id>/opretpatient/', views.opretpatient, name="opret_patient"),
Views. py:
def kartotek(request, kl_id):
kliniknavn = Klinik.objects.get(navn=kl_id)
E_patient = kliniknavn.patient_set.all()
context = { 'kliniknavn':kliniknavn, 'E_patient':E_patient}
return render(request,'DentHelp/kartotek.html', context )
def opretpatient(request, kl_id):
kliniknavn = Klinik.objects.get(navn=kl_id)
form = PatientForm()
if request.method == 'POST':
form = PatientForm(request.POST)
if form.is_valid():
form.save()
return redirect('kartotek/<str:kl_id>/')
context = {'form':form, 'kliniknavn':kliniknavn}
return render(request,'DentHelp/kartotek/<str:kl_id>/opretpatient.html', context)
When running code I get an OSError for the last line of code shown here.
Have you guys have any advise for this to work?
You are mixing up render with redirect. render renders a template dynamically with attributes from context, where redirect redirects the user to a different view. To call render, you need to provide template name and context. For redirect, you need to provide url name and parameters (if required). Here is how you should do in your code:
def opretpatient(request, kl_id):
kliniknavn = Klinik.objects.get(navn=kl_id)
form = PatientForm()
if request.method == 'POST':
form = PatientForm(request.POST)
if form.is_valid():
form.save()
return redirect('kartotek', kl_id) # url name and parameter
context = {'form':form, 'kliniknavn':kliniknavn}
return render(request, 'DentHelp/kartotek/opretpatient.html', context) # template name and context
I am experimenting with Django class based views and for some reason this simple post view does not seem to be working. When looking at my terminal it gets stuck on the GET method / validation of the csrf token. It is either not being validated or not saving to the database and therefore not being redirected to the thank-you page. I am not sure how to solve this issue. It definitely is not being saved to the DB, but as far as I am aware everything is correct here. I also am using a class based form which is why I am simply just calling form.save() The code is as follows:
class ReviewView(View):
def get(self, request):
form = ReviewForm()
return render(request, 'reviews/review.html', {
'form': form
})
def post(self, request):
form = ReviewForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/thank-you')
return render(request, 'reviews/review.html', {
'form': form
})
Any help or ideas is greatly appreciated!
I have found that when passing context and a title into my views it causes the page to only show its html source code instead of the actual frontend graphics. If i remove the title being passed in then it works again but i do want to have the title passed in so is there any way to have this work?
Views
def myPosts(request):
context = {
'products': Post.objects.all()
}
return render(request, 'create/my_posts.html', context, {'title_page': 'My Posts'})
class PostListView(ListView):
model = Post
template_name = 'my_posts.html'
context_object_name = 'products'
when you are passing context yo can do something like this
context = {
'products': Post.objects.all(),
'title_page': 'My Posts'
}
and finally pass
return render(request, 'create/my_posts.html', context)
In the front end, you can use it as context.title_page
Look I have a problem with displaying photos after updating.
I have a function from my views.py
def addHW(request):
if request.user.is_authenticated:
obj = Profile.objects.get(user=request.user.id)
else:
obj = ''
profile = request.user.profile
form = CustomerForm(instance=profile)
template = 'HW/add.html'
context = {'form': form, 'profile': obj}
if request.method == 'POST':
form = CustomerForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
Profile.objects.get(user=request.user.id).photo.delete()
form.save()
return render(request, template, context)
and after deleting previous photo and saving of new photo, page must be reloaded. And page shows visual reloading, but HTML shows src of previous image. And after manual refreshing page displays new src of photo.
How i can resolve it?
In case of a successful post, you need to make a redirect to implement the Post/Redirect/Get pattern. – Willem Van Onsem 32 mins ago
How can I get data from the form using the GET method?
For example, I have this form:
class LoansSearchForm(forms.Form):
balance = forms.IntegerField(label='', required=False)
In my view display in the form template this way:
def search_results(request):
form = LoansSearchForm(request.GET)
cd = form.cleaned_data
word = cd['balance']
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
But i still a error:
'LoansSearchForm' object has no attribute 'cleaned_data'
When trying to get them this way:
word = form['balance']
I receive a field with completed data. How to get the data from my the form correctly?
Is my form written correctly? Should I use something like that?
(sorry if my question is trivial, but I found very little information about GET forms)
if request.method == 'GET':
form = LoansSearchForm(request.GET)
if form.is_valid():
print('Hello World')
else:
form = LoansSearchForm()
Recommended: run form.is_valid() and then you do form.cleaned_data
def search_results(request):
form = LoansSearchForm(request.GET)
if form.is_valid():
cd = form.cleaned_data
word = cd['balance']
else:
word = None
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it anywhere.
more on cleaned data - documentation
def search_results(request):
form = LoansSearchForm(request.GET)
cd = form.cleaned_data # here <------
word = cd['balance']
context = {'form': form,
'test': word,}
return render(request, 'search_results.html', context)
The problem with your code is that forms are not filled on initialization but when you call form.is_valid, if the form is indeed valid, then it populates cleaned_data
You can read more about the related documentation.
I used name=form.data['field_name'], think it answers your answer of obtaining form values on submit.