I want to create a simple blog using Django, this is my code :
class Blog(models.Model):
title = models.CharField(max_length = 50)
content = models.TextField(max_length = 10000)
publication_date = models.DateField(blank = True, null = True)
author = models.CharField(max_length = 50)
image = models.ImageField(upload_to='image',verbose_name = 'My photos',blank = True)
def __str__(self):
return self.title
When I display the content field, I don't know how to add images (in the body of content field) , strong text, ...
Is there anyone can show me how to do this?, sorry if it's a silly question,
I've searched for hours but I didn't find out the answer
This is to be done using Rich text editors. See the list of available django packages here. CKEditor and TinyMCE are promising to easily handle images.
Related
Sorry if the title is confusing, I can't really think of how else to word it.
I am creating a site where there are many quizzes. Each Quiz model
class Quiz(models.Model):
name = models.CharField(max_length = 80)
description = models.CharField(max_length = 300)
num_questions = models.IntegerField(default = 10)
slug = models.SlugField(max_length = 20)
img = models.URLField(blank = True) # allow it to be none
def __str__(self):
return self.name
def get_questions(self):
return self.question_set.all()
looks like this... and it has some attributes like name, description, etc. There are many Question models that have ForeignKey to one Quiz:
class Question(models.Model):
quiz = models.ForeignKey(Quiz, on_delete = models.CASCADE)
img = models.URLField(blank = True) # allow none`
content = models.CharField(max_length = 200)
def __str__(self):
return self.content
def get_answers(self):
return self.answer_set.all()
and then there are some Choice models that have ForeignKey to one Question:
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete = models.CASCADE)
content = models.CharField(max_length = 200)
correct = models.BooleanField(default = False)
Now. I want to create one single ModelForm from which I can create 1 quiz record, and then 10 question records with 4 choice records per question. It would be very nice if they could automatically set their foreignkey to the Question that is being created. How can I go about this? Is it even possible? I don't even know if my wording of this question is making sense because I have a great big idea in my head but no idea how to express it properly in words or code.
Help is appreciated :)
If you have 3 models and you want to show them in a single form in your HTML file. Then you can simply create a model form for each of them and add them in a single <form> tag.
The answer to a similar question is posted here.
If you mean inserting multiple records at the same time, then consider looking at formset factory - https://docs.djangoproject.com/en/3.2/topics/forms/formsets/
I built a django web app to manage medical datas.
I have many specialities using the same project. I'd like to display specific interfaces/forms/templates...depending of the user speciality.
I'm on django 1.11 python 3.6.
The app is running well. I have patients, and users.
Each user have only one speciality (cardiologist, surgeon...), defined by a specific class and linked to the user by a ForeignKey.
models.py
class Specialite(Auditable): #list of specialites, and link it to user !
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
spe = models.CharField( max_length = 200, null = False,)
#define which app the specialite is linked to...
data_app = models.CharField(max_length = 200, null = False, blank = False)
def __str__(self):
return self.spe
class Patient(Auditable):
# https://stackoverflow.com/questions/3052975/django-models-avoid-duplicates
class Meta:
unique_together = ["nom", "prenom", "dob"]
MALE = "MALE"
FEMALE = "FEMALE"
SEXE = (
(MALE, 'Homme'),
(FEMALE, 'Femme'),
)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
nom = models.CharField( max_length=50,)
nom_naissance = models.CharField( max_length=50,)
prenom = models.CharField(max_length=150,)
sexe = models.CharField(max_length = 100,
choices = SEXE,
)
For now, i have one table by patient: first name, last name, dob, weight, height...Only general informations shared by all specialities.
I'd like to create specific onetoone tables depending of the speciality to display relevant informations for each speciality/practicioner.
Each field is based on a SNOMED CT classification for more consistency and data connection.
I though about many ways:
A huge model on top with a lot of fields, with abstract = true, and sub models using this model
A huge model with a lot of fields, and for each speciality specific template, form to update datas, but data might change as long as doctors might have a different analysis of the data...
Eventually, the one i think would be the more appropriate: an app for each speciality with all the logic of the fields, forms etc... inside the app.
So my choice is more into creating an app for each speciality, linked to the "speciality" model by a foreign key or text (like the name of the app:
data_app = models.CharField(max_length = 200, null = False, blank = False)
).
In each app, i have a model with just a class linked to a patient by a OneToOne relationship.
class Cardiology (Auditable):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
zkf_patient = models.OneToOneField(Patient, on_delete = models.PROTECT, null = True, blank = True)
hta = models.BooleanField()
tobacco = models.BooleanField()
.....
For now, i'm ok with creating a new entry for a patient with inline formset factory.
However, what i'd like to do is displaying the appropriate Template/CBV/Urls... depending of the user speciality to edit and display the related information.
For instance, if i'm a cardiologist: show on the main page, along with the "patient" model class details, specific information related to cardiology. But if i'm a surgeon, showing the same page, but with the specific informations for surgery...
I can do that now, i'm using the {% include '...html' %} in my template to insert what i want.
I'm thinking about creating a specific tag to dynamically display the related information...
But i've no clue about how to do for the edit page etc....Except creating a script with bunch of dicts to create the relationships, but it seems to me a nightmare.
What's your opinion, is there a more elegant way, more "logic". Based on names of each class view maybe...
Thanks for your help !
I eventually ended up with a custom tag...Works well so far :) !
#TAGS
from django import template
from django.template.loader import render_to_string #generate a string from a template
import datetime
from django.urls import reverse
from django.template.base import (
Node, Template, TemplateSyntaxError, TextNode, Variable, token_kwargs,
)
register = template.Library()
def get_activ_specialite(request, context):
app_name = request.resolver_match.app_name
if app_name == 'patient':
#get the specialite of the user
specialite = request.user.profile.specialite_active.spe
specialite = '_'.join(specialite.lower().split(' '))
return specialite
elif app_name == 'hospitalisation':
#get the specialite of the service where the patient is hospitalized !
specialite = context['hospitalisation'].specialite_referente.spe
specialite = '_'.join(specialite.lower().split(' '))
return specialite
return
#register.simple_tag(takes_context=True)
def routing_antecedents(context, destination):
if 'patient' in context:
patient = context['patient']
id = patient.id
if 'hospitalisation' in context:
hos = context['hospitalisation']
id = hos.id
request = context['request']
#1/get service référent du patient
app_name = get_activ_specialite(request, context)
#2/ redirect to urls...! Name consistency is mandatory !!!
url = str(app_name + ":" + destination)
url = reverse(str(url), args=(id,) )
# return url path !
return url
#register.simple_tag(takes_context=True)
def include_antecedents_spe(context, template_name):
request = context['request']
#1/get service référent du patient
app_name = get_activ_specialite(request, context)
template_name = template_name.replace("'","").replace('"', '')
template_name = str(str(app_name) + "/" + str(template_name))
html = render_to_string(template_name, context.flatten())
return html
I want to know how to display images separated by albums onto a page in Django. So far, I've learned how to do so with the line
<img src="{% static "images/python-logo#2x.png" %}">
in my html file.
structure:
/PersonalWebsite
/static
/img
/albums
/album1
img1
/album2
img2
...etc
What I want to do is have a few album thumbnails out and upon click, all the images from the album should be displayed. I believe I would do this with an AJAX request. I am probably going to categorized these photos with tags and put names one them and other characteristics. This would be done in my models.py which I have: (though not completed)
from django.db import models
from django.contrib import admin
import os
from PersonalWebsite.settings import MEDIA_ROOT
class Album(models.Model):
title = models.CharField(max_length = 60)
def __unicode__(self):
return self.title
def get_image_by_album(self):
images = []
for root, dirs, files in os.walk(os.path.join(MEDIA_ROOT, 'albums', self.title)):
mypath = os.sep.join(os.path.join(root, file).split(os.sep[4:]))
images.append(mypath)
return images
class Tag(models.Model):
tag = models.CharField(max_length = 50)
def __unicode__(self):
return self.tag
class Image(models.Model):
title = models.CharField(max_length = 60, blank = True, null = True)
#image = models.FileField(upload_to = get_upload_file_name)
tags = models.ManyToManyField(Tag, blank = True)
albums = models.ForeignKey(Album)
width = models.IntegerField(blank = True, null = True)
height = models.IntegerField(blank = True, null = True)
created = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.image.name
class AlbumAdmin(admin.ModelAdmin):
search_fields = ["title"]
list_display = ["title"]
class TagAdmin(admin.ModelAdmin):
list_display = ["tag"]
class ImageAdmin(admin.ModelAdmin):
search_fields = ["title"]
list_display = ["__unicode__", "title", "created"]
list_filter = ["tags", "albums"]
admin.site.register(Album, AlbumAdmin)
admin.site.register(Tag, TagAdmin)
admin.site.register(Image, ImageAdmin)
My "get_image_by_album" parses through the albums and appends the path to "images" list. Thats as far as I've got right now =/ I also want to set up an admin so I can maintain the site easily later on. I think I am going to make a view method that will simply get the list of image paths and display it that way. I am open to suggestions! let me know what you think! I also want to set up an admin interface that would enable me to upload and edit meta data from the photos manually but I will figure out how to do so later.
I built a very simple gallery app using django-photologue. http://gallery.gentryart.us
I am doing Udacity's Web Dev Course with Google Appengine and Python.
I would like to know how I could assign to a created entity, its own author.
For example, I have two ndb.Models kinds:
class User(ndb.Model):
username = ndb.StringProperty(required = True)
bio = ndb.TextProperty(required = True)
password = ndb.StringProperty(required = True)
email = ndb.StringProperty()
created = ndb.DateTimeProperty(auto_now_add = True)
class Blog(ndb.Model):
title = ndb.StringProperty(required = True)
body = ndb.TextProperty(required = True)
created = ndb.DateTimeProperty(auto_now_add = True)
When a Blog entity is created by a logged-in user, its own author (User entity) should also be identified with it.
Ultimately, I would like to display a blog's post with its author's information (for example, the author's bio)
How can this be achieved?
Your Blog class should include a property to store the key of the user who wrote it:
author = ndb.KeyProperty(required = True)
You can then set this property when you create a Blog instance:
blog = Blog(title="title", body="body", author=user.key)
For optimization, if you know the logged in user's ndb.Key, and you don't need the user entity itself, you would pass that directly, instead of needing to fetch the user first.
assert isinstance(user_key, ndb.Key)
blog = Blog(title="title", body="body", author=user_key)
In full:
class User(ndb.Model):
username = ndb.StringProperty(required = True)
password = ndb.StringProperty(required = True)
email = ndb.StringProperty()
created = ndb.DateTimeProperty(auto_now_add = True)
class Blog(ndb.Model):
title = ndb.StringProperty(required = True)
body = ndb.TextProperty(required = True)
created = ndb.DateTimeProperty(auto_now_add = True)
author = ndb.KeyProperty(required = True)
def new_blog(author):
"""Creates a new blog post for the given author, which may be a ndb.Key or User instance"""
if isinstance(author, User):
author_key = author.key
elif isinstance(author, ndb.Key):
assert author.kind() == User._get_kind() # verifies the provided ndb.Key is the correct kind.
author_key = author
blog = Blog(title="title", body="body", author=author_key)
return blog
You may get bonus points if you standardize the beginning of new_blog to a utility function.
All,
i have the following model defined,
class header(models.Model):
title = models.CharField(max_length = 255)
created_by = models.CharField(max_length = 255)
def __unicode__(self):
return self.id()
class criteria(models.Model):
details = models.CharField(max_length = 255)
headerid = models.ForeignKey(header)
def __unicode__(self):
return self.id()
class options(models.Model):
opt_details = models.CharField(max_length = 255)
headerid = models.ForeignKey(header)
def __unicode__(self):
return self.id()
AND IN MY VIEWS I HAVE
p= header(title=name,created_by=id)
p.save()
Now the data will be saved to header table .My question is that for this id generated in header table how will save the data to criteria and options table..Please let me know..
Thanks..
Given your:
p= header(title=name,created_by=id)
p.save()
You can now:
c=criteria(details='some details', headerid=p)
c.save()
o=options(opt_details='more details', headerid=p)
o.save()
Hope this helps.
Take advantage of <related>_set query managers, it's clearer and shorter than constructing and saving objects in separate operations.
h = header.objects.create(title=name,created_by=id)
c = h.criteria_set.create(details='some details')
o = h.options_set.create(opt_details='more details')
And some offtopic: please, start class names from uppercase letter, it really makes code easier to read.