I have a text field in models.py where I can input text content for a blog using the admin.
I want to be able to write the content for this text field in markdown format, but I'm using Django 1.6 and django.contrib.markup is not supported anymore.
I can't find anywhere that has a tutorial and runs through adding markdown to a text field in Django 1.6. Can someone look at my .py files and help me implement markdown to my app.
models.py
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=200)
pub_date = models.DateTimeField()
text = models.TextField()
tags = models.CharField(max_length=80, blank=True)
published = models.BooleanField(default=True)
admin.py
from django.contrib import admin
from blogengine.models import Post
class PostAdmin(admin.ModelAdmin):
# fields display on change list
list_display = ['title', 'text']
# fields to filter the change list with
save_on_top = True
# fields to search in change list
search_fields = ['title', 'text']
# enable the date drill down on change list
date_hierarchy = 'pub_date'
admin.site.register(Post, PostAdmin)
index.html
<html>
<head>
<title>My Django Blog</title>
</head>
<body>
{% for post in post %}
<h1>{{ post.title }}</h1>
<h3>{{ post.pub_date }}</h3>
{{ post.text }}
{{ post.tags }}
{% endfor %}
</body>
</html>
Thank you for your answers and suggestions, but I've decided to use markdown-deux.
Here's how I did it:
pip install django-markdown-deux
Then I did pip freeze > requirements.txt to make sure that my requirements file was updated.
Then I added 'markdown_deux' to the list of INSTALLED_APPS:
INSTALLED_APPS = (
...
'markdown_deux',
...
)
Then I changed my template index.html to:
{% load markdown_deux_tags %}
<html>
<head>
<title>My Django Blog</title>
</head>
<body>
{% for post in post %}
<h1>{{ post.title }}</h1>
<h3>{{ post.pub_date }}</h3>
{{ post.text|markdown }}
{{ post.tags }}
{% endfor %}
</body>
</html>
Ah, I met with the same problem several months ago, and I found the easiest and most robust solution is to use Github Markdown API.
Here is the code I use for my blog, which I believe will help you more or less. btw I use Python 3 so the encoding part may be different from Python 2.
# generate rendered html file with same name as md
headers = {'Content-Type': 'text/plain'}
if type(self.body) == bytes: # sometimes body is str sometimes bytes...
data = self.body
elif type(self.body) == str:
data = self.body.encode('utf-8')
else:
print("somthing is wrong")
r = requests.post('https://api.github.com/markdown/raw', headers=headers, data=data)
# avoid recursive invoke
self.html_file.save(self.title+'.html', ContentFile(r.text.encode('utf-8')), save=False)
self.html_file.close()
My code is hosted on github, you can find it here
And My blog is http://laike9m.com.
You may use substitution of old markup implemented here - https://github.com/jamesturk/django-markupfield
Related
I'm having quite some troubles understanding how variables are passed to templates in Django, I'm new so keep this in mind.
My problem is that, when the URL is loaded data from databases can't be rendered except for the user(request.user.username) which is strangely loaded.
I even tried to declare variables inside the view's def but even them are not rendered
The model is imported inside the views.py.
My idea is that, since the user from request.user is loaded, there must be some problem with loading the database model, but this doesn't explain why even freshly declared variables inside the view's def are not passed.
In the /admin page all the models work fine.
Below are the fragments of my code, they should be enough to understand the problem, if not I can upload other parts.
Thank you in advance.
views.py:
def load_main(request):
diet_list = DietTable.objects.all()
return render(request, 'main/main.html',
{
'diet_list': diet_list,
'user': request.user.username,
})
part in the main.html:
<body>
...
<header>
...
</header>
...
{% block content %}
<strong>
{{ user }}
{% for element in diet_list %}
{{ element }}
{% endfor %}
</strong>
{% endblock %}
...
</body>
urls.py:
from django.urls import path, include
from main import views
urlpatterns = [
path('', views.load_main, name='main_view'),
]
models.py
...
class DietTable(models.Model):
diet_id = models.AutoField(primary_key=True) # to not use the default 'id; given by django
dietName = models.CharField(max_length=50)
dietType = models.ForeignKey(DietTypes, on_delete=models.PROTECT)
startDate = models.DateTimeField()
dayLength = models.IntegerField()
def __str__(self):
return str(str(self.dietName) + "(" + str(self.dayLength) + ")")
...
Still needs working answer.
I have added three apps to my django website: application, blog, and feedback. All three have the same problem: when I click a link, or enter a URL, to any of them, I get a 404 error.
I'm attaching code and other documentation below for one of the problem addons. For further context, if necessary, my full code can be found at https://github.com/kkerwin1/pensdnd.
Directory structure
(venv) kris#adjutant:~/venv/pensdnd$ tree -if
.
./application
./application/admin.py
./application/apps.py
./application/forms.py
./application/__init__.py
./application/migrations
./application/models.py
./application/templates
./application/templates/application.html
./application/templates/application_thanks.html
./application/tests.py
./application/urls.py
./application/views.py
./blog
./blog/admin.py
./blog/apps.py
./blog/models.py
./blog/templates
./blog/templates/blog_list.html
./blog/templates/blog_post.html
./blog/tests.py
./blog/urls.py
./blog/views.py
./feedback
./feedback/admin.py
./feedback/apps.py
./feedback/forms.py
./feedback/models.py
./feedback/templates
./feedback/templates/feedback.html
./feedback/templates/feedback_thanks.html
./feedback/tests.py
./feedback/urls.py
./feedback/views.py
./manage.py
./pensdnd
./pensdnd/settings.py
./pensdnd/static
./pensdnd/static/css
./pensdnd/static/css/main.css
./pensdnd/static/html
./pensdnd/static/html/arvon_rules.html
./pensdnd/static/html/be_a_dm.html
./pensdnd/static/html/community_rules.html
./pensdnd/static/html/guild_rules.html
./pensdnd/static/html/index.html
./pensdnd/static/html/volunteer.html
./pensdnd/static/img
./pensdnd/static/img/carbon_fibre.png
./pensdnd/static/img/github_icon.png
./pensdnd/static/js
./pensdnd/static/misc
./pensdnd/static/templates
./pensdnd/static/templates/base.html
./pensdnd/static/templates/partials
./pensdnd/static/templates/partials/blogbar.html
./pensdnd/static/templates/partials/feedback.html
./pensdnd/static/templates/partials/footer.html
./pensdnd/static/templates/partials/navbar.html
./pensdnd/static/templates/partials/newsbar.html
./pensdnd/static/vid
./pensdnd/urls.py
./pensdnd/views.py
./pensdnd/wsgi.py
./requirements.txt
./pensdnd/urls.py
from django.contrib import admin
from django.urls import path, include
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.HomePageView.as_view()),
path('admin/', admin.site.urls),
path('be_a_dm/', views.BeADM.as_view()),
path('blog/', include('blog.urls')),
path('feedback/', include('feedback.urls')),
path('application/', include('application.urls')),
path('guild_rules/', views.GuildRules.as_view()),
path('community_rules/', views.CommunityRules.as_view()),
path('arvon_rules/', views.ArvonRules.as_view()),
path('volunteer/', views.Volunteer.as_view()),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
./blog/urls.py
from . import views
from django.urls import path
urlpatterns = [
path('blog/', views.PostList.as_view()),
path('blog/<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
]
./blog/views.py
from django.shortcuts import render
from .models import Post
from django.views import generic
# Create your views here.
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'templates/blog_list.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'templates/blog_post.html'
./blog/models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
./blogs/templates/blog_list.html
{% extends 'static/templates/base.html' %}
<!doctype html>
<html lang="en">
<head>
<title>
{% block title %}
PensiveDND :: Blog Posts
{% endblock %}
</title>
</head>
<body>
{% block pagecontent %}
<section>
{% for post in post_list %}
<article>
<h3>{{ post.title }}</h3>
<p>{{ post.author }} | {{ post.created_on }}</p>
<p>{{ post.content|slice:":200" }}
Read More
</article>
</section>
{% endblock %}
</body>
</html>
./blogs/templates/blog_post.html
{% extends 'static/templates/base.html' %}
<!doctype html>
<html lang="en">
<head>
<title>
{% block title %}
PensiveDND :: Blog :: {{ post.title }}
{% endblock %}
</title>
</head>
<body>
{% block pagecontent %}
<section>
<h2>{{ post.title }}</h2>
<p>{{ post.author }} | {{ post.created_on }}</p>
<p>{{ post.content | safe }}</p>
</section>
{% endblock %}
</body>
</html>
In "pensdnd/urls.py", you are missing the trailing slashes after your app name
for example
path('feedback', include('feedback.urls')),
should be
path('feedback/', include('feedback.urls')),
Unable to access html files. There are no errors in your urls.py file. At least for the blog app. When I run the code, I don't get a 404 error with different edits. According to the Github codes, I changed the DIRS section in the templates field under settings.py to 'templates' and moved the html files you used in your blog application here. There was no problem. Editing all your code can be difficult, but that's where the problem lies.(Note that I only control the blog app.)
also, you will get an error because you don't use {% endfor %}.
{% for post in post_list %}
<article>
<h3>{{ post.title }}</h3>
<p>{{ post.author }} | {{ post.created_on }}</p>
<p>{{ post.content|slice:":200" }}
Read More
</article>
If you have set templates location, you should just use template_name = 'blog_list.html instead of template_name = 'templates/blog_list.html'.
Please check these things again. As I said, the problem is caused by the use of static and templates. not urls.
Hey I have had a look at similar questions but none really relate to what I am trying to do, they either explain how to order things in the admin panel or simply iterating over object dictionaries.
I have created a basic photo model that contains a value gallery_order so I can edit them in Admin.
I wish to populate my template with the pictures according to the gallery_order values in order from 1 upward.
I guess the best way to handle it is with a dictionary but I do not know where to initialize it, if I put it in the picture model then each picture holds a dict with all the pictures order number and url in it which seems mental.
My current model:
class Picture(models.Model):
title = models.CharField(max_length=36, blank=False, unique=True)
gallery_order = models.IntegerField(default=0)
image = models.ImageField(upload_to='photos/', blank=False)
def __str__(self):
return self.title
My template code:
<head>
<meta charset="utf-8">
{% block content %}
<div class="row">
{% if pictures %}
{% for picture in pictures %}
<div class="col-md-12">
<div class="card mb-0">
<img class="card-img-top" src="{{ picture.image.url }}">
</div>
</div>
{% endfor %}
{% endif %}
</div>
{% endblock content %}
</head>
my admin code:
#admin.register(Picture)
class PictureAdmin(admin.ModelAdmin):
list_display = ('gallery_order', 'title', 'image')
list_display_links = ['gallery_order']
search_fields = ['title']
def get_queryset(self, request):
queryset = super(PictureAdmin, self).get_queryset(request)
queryset = queryset.order_by('gallery_order')
return queryset
I tried to figure out how django was displaying them by looking at the PK in psotgres db but it seems to simply display them according to last edited.
Thank You :)
You could also do this at the model level by adding the following at the end of your model.
class Meta:
ordering = ['gallery_order']
I am so silly sometimes I forgot about my views!
all I had to do was specify order_by for goodness sake...
class Home(View):
pictures = Picture.objects.all().order_by('gallery_order')
def get(self, request):
return render(request, 'home.html', {'pictures': self.pictures})
I am working on a Django Project, where a student will write his/her course name in a form and click on Calculate button and the system will use the Fuzzy Logic to calculate the performance of students based on the details of that specific course and then show the result of that calculation below the Calculate Button.
What I have done so far are below.
views.py:
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import PerformanceCalculatorForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .models import Subject, Detail
from .fuzzy_logic_algo import fuzz_algo
def performanceCalculator(request):
if request.method == 'POST':
performance_form = PerformanceCalculatorForm(request.POST)
if performance_form.is_valid():
sub = performance_form.cleaned_data.get('subject')
skype = Details.objects.filter(subject__subject=sub, user__username=User.username).get('skype_session_attendance')
internal_course = Details.objects.filter(subject__subject=sub, user__username=User.username).get('internal_course_marks')
prg_lab = Details.objects.filter(subject__subject=sub, user__username=User.username).get('programming_lab_activity')
mid_marks = Details.objects.filter(subject__subject=sub, user__username=User.username).get('mid_term_marks')
final_marks = Details.objects.filter(subject__subject=sub, user__username=User.username).get('final_term_marks')
result = fuzz_algo(skype, internal_course, prg_lab, mid_marks, final_marks)
context = {
'result': result,
}
return render(request, 'users/performance_calculator.html', context)
else:
performance_form = PerformanceCalculatorForm()
return render(request, 'users/performance_calculator.html', {'performance_form': performance_form})
models.py:
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class Subject(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.CharField(max_length=100)
def __str__(self):
return '{} ({})'.format(self.subject, self.user.username)
class Detail(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.OneToOneField(Subject, on_delete=models.CASCADE)
skype_session_attendance = models.FloatField()
internal_course_marks = models.FloatField()
programming_lab_activity = models.FloatField()
mid_term_marks = models.FloatField()
final_term_marks = models.FloatField()
def __str__(self):
return f'{self.subject, (self.user.username)} Details'
forms.py:
from django import forms
class PerformanceCalculatorForm(forms.Form):
class Meta:
fields = ['subject']
performance_calculator.html:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{% static 'esacp/main.css' %}">
<title>Expert System for Assessing Programming Course Performance</title>
</head>
<body>
<main role="main" class="container">
<div class="row">
<div class="col-md-8">
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% if not request.user.is_superuser and not request.user.is_staff %}
<div class="account-heading">
<h2>
Performance Calculator
</h2>
</div>
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Profile</legend>
{{ performance_form|crispy }}
{{ result }}
</fieldset>
</form>
</div>
{% endif %}
</div>
</div>
</main>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
Can anyone tell me that how would I accomplish it that a user (student) enters the course name in the form when he/she is on .../performance_calculator.html, his record is saved, and matched with the courses assigned to him, after the matched, the activity details of student that course is taken and those are assigned to separate variables, the those variables are passed to fuzz_algo() function, then the result of that function is printed on the Front End?
I have been working on it since 2 days and not getting it. Any help will be surely appreciated.
Let me go with some really problematic things first. Your PerformanceCalculator view, in the POST conditional, you never save() the form, and therefore your next queries will return empty objects, which I believe the fuzz_algo will return None (Assumption) and displays nothing on the render.
Actually best practice is: on the last line of your POST conditional, use redirect instead of render as it will load you again the page without the POST data.
And I think that all the above thing you have tried already (because you said you tried 2 days), but wonder why it still renders nothing, because by redirect it will ask again with a GET request and will lose the data in the variable result.
Now with the "not so important" thing, as I see in your code and you don't have intention of saving your form in database, this is probably a better approach on the Client Side instead of Server Side. To do it on the server side please check https://docs.djangoproject.com/en/3.0/topics/http/sessions/ to use sessions variables to keep it alive and not lose after redirect, also there is EASY work around (but doesn't work in all the cases) is to .. let's say "abuse" the messages library of django, it will pass a message to the client side on your next LOAD.
So on your views.py import the messages library and add this before redirect
messages.success(request, result)
Now in your template add this
{% if messages %}
{% for message in messages %}
{{ message }}
{% endfor %}
{% endif %}
I'm new to Django, but I think I did something similar to what you are trying to do.
1. With a model similar to yours - had the user fill out the form and then made sure the model was populated with the data from the form. I didn't realize at first that I needed to make sure every field in the form was filled out or nothing would be saved to the model. (It is in the docs, I just didn't pick up on it).
2. Then when I wanted to use the data in the model, I just made sure that the model was imported.I also imported a separate python file to perform the computation on the parameters.
Then in the view I assigned a variable = to the model object for example for the Model Search_Profile in my case I had
params=Search_Profile.objects.last()
since in my case I just wanted the last profile, but you could make it any object you wanted.
With that information I could then import the function from a .py file In my case
C=calculate(params.keyword_string,params.other_string)
At that point I could then render the template with both the parameters and whatever I needed from the calculation function in the .py file by using
return render(request,'mainapp/show_calculation.html',{'params':params,'new_entries':new_entries,'C':C})
It took me a while to figure that this worked, and maybe there are better ways, but it at least worked for what I was trying to do.
Looking at your code, I suspect you're a better coder than I am, but maybe the above might help. In your form you only have the subject field and don't have the user field. In my situation I think that led to my model not being filled.
The other thing I had to do to figure it out for my case was to get away from crispy forms or widget-tweeks, but I don't think that matters much.
I am attempting to build a basic database of song information, regarding artists, songs and albums. On my page for any given album I am attempting to display the album art for a given album. I am using the built-in image upload feature within Django Admin to upload the images. The images urls are being saved correctly within mysql (I checked), but the images are not being displayed on the site. From what I have read online the possible problematic areas are either in the URLs file(which I have not modified to accommodate media) or in my MEDIA_URL, but I have followed instructions as Django has outlined. Below I am linking the code I think is relevant. Thank you in advance for the help!
views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
from Radio.models import Song, Artist, Album
def SongsAll(request):
songs = Song.objects.all().order_by('songName')
context = {'songs' : songs}
return render_to_response('songsall.html', context, context_instance = RequestContext(request))
def SpecificSong(request, songname):
song = Song.objects.get(songName = songname)
context = {'song':song}
return render_to_response('specificsong.html',context, context_instance=RequestContext(request))
def SpecificArtist(request, artistname):
singer = Artist.objects.get(artistName = artistname)
songs = Song.objects.filter(artist = singer)
context = {'songs':songs}
return render_to_response('specificartist.html',context, context_instance=RequestContext(request))
def SpecificAlbum(request, albumname):
album = Album.objects.get(albumName = albumname)
songs = Song.objects.filter(album = album)
context = {'songs':songs}
return render_to_response('specificalbum.html', context, context_instance=RequestContext(request))
settings.py (only the relevant parts)
MEDIA_ROOT = '/home/kyle/Downloads/Django-1.5.1/radioSite/media/'
MEDIA_URL = 'http://127.0.0.1:8000/media/'
models.py
from django.db import models
class Artist(models.Model):
artistName = models.CharField(max_length = 30)
artistInfo = models.TextField()
def __unicode__(self):
return self.artistName
class Album(models.Model):
albumName = models.CharField(max_length = 30)
artist = models.ForeignKey('Artist')
date = models.DateTimeField('Release Date')
albumInfo = models.TextField()
albumArt = models.ImageField(upload_to="images/albumart/")
def __unicode__(self):
return self.albumName
class Song(models.Model):
songName = models.CharField(max_length = 30)
artist = models.ForeignKey('Artist')
album = models.ForeignKey('Album')
def __unicode__(self):
return self.songName
base.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/Radio.css"/>
{% block extended %}{% endblock %}
</head>
<body>
<div id="pageContainer">
{% block content %}
{% endblock %}
</div>
</body>
</html>
specificalbum.html
{% extends "base.html" %}
{% block content %}
<div id="singlealbum">
<p><img src="{{ songs.0.album.albumart.url }}"/>Name: {{ songs.0.album }}</p>
<p>Artist:{{ songs.0.artist }}</a></p>
<p>Song list:</p>
{% for song in songs %}
<p>{{ song }}</p>
{% endfor %}
</div>
{% endblock %}
Are your images actually getting uploaded somewhere where a web server is expecting to serve them?
From your MEDIA_URL setting I'm guessing that you're trying to get the Django server to serve the images. You can check the documentation for how to do this during development, or if you're just learning Django, but please don't try to do this for anything at all serious - you'll be much better served by using a dedicated web server like Apache or the like.