I can't get my code to save a new entry and return an error message if entry already existed. its just the views.py I can't figure out help please. code below
1 Answer
There might be more than one way of doing this, but I imported default_storage and ContentFile and it worked for me.
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
And then in my add function
file = ContentFile(content)
default_storage.save( f"entries/{title}.md", file)
return HttpResponseRedirect(title)
It looks like you've got some cut'n'paste code hanging around from the Tasks app. tasks.append(title)
will add title to a list of tasks. I think the objective though is to save the content to a title.md markdown file in the entries folder of the project.
Finally, you need to check if the title already exists and only perform the save if it doesn't. Something like:
if (title in util.list_entries())
should be a good start.
-
-
replace the two lines
tasks.append(title)
andtasks.append(content)
withutil.save_entry(title, content)
. Then your first return statement will bereturn HttpResponseRedirect(title)
. Make sure you putdjango.http import HttpResponseRedirect
at the top of the views.py– BrianJul 26, 2020 at 10:38 -