Django model does not recognize MarkdownxFormField field - python

I am trying to add markdownx support to my model, which will enable preview editing from the admin panel. However, once i change my content field from models.FileField to MarkdownXFromField() django just deletes the content field when migrating and ignores it as if it wasn't part of the model at all.
I've followed these docs exactly but it's not working.
I have also ran collectstatic.
# models.py
from os.path import splitext
from uuid import uuid4
from django.db import models
from markdownx.fields import MarkdownxFormField
def hashImageFilename(instance, name):
ext = splitext(name)[1]
return "images/{}{}".format(uuid4(), ext)
class Article(models.Model):
title = models.CharField(("title"), max_length=100)
content = MarkdownxFormField()
description = models.TextField(("description"), default='')
uploadDate = models.DateTimeField(("uploadDate"), auto_now=True)
lastModified = models.DateTimeField(("uploadDate"), auto_now=True)
publicationDate = models.DateField("publicationDate")
image = models.ImageField("image", upload_to=hashImageFilename)
def __str__(self):
return self.title
# urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf.urls import url
from django.conf import settings
from markdownx import urls as markdownx
urlpatterns = [
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls')),
path('api/articles/', include('articles.api.urls')),
url(r'^markdownx/', include('markdownx.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# admin.py
from django.contrib import admin
# Register your models here.
from markdownx.admin import MarkdownxModelAdmin
from .models import Article
admin.site.register(Article, MarkdownxModelAdmin)
# settings.py
INSTALLED_APPS = [
#...
'markdownx'
]

You are confusing the MarkdownxFormField form field with the MarkdownxField model field. You should rewrite the model to:
# models.py
from os.path import splitext
from uuid import uuid4
from django.db import models
from markdownx.models import MarkdownxField
def hashImageFilename(instance, name):
ext = splitext(name)[1]
return "images/{}{}".format(uuid4(), ext)
class Article(models.Model):
title = models.CharField(("title"), max_length=100)
content = MarkdownxFormField()
description = models.TextField(("description"), default='')
uploadDate = models.DateTimeField(("uploadDate"), auto_now=True)
lastModified = models.DateTimeField(("uploadDate"), auto_now=True)
publicationDate = models.DateField("publicationDate")
image = models.ImageField("image", upload_to=hashImageFilename)
def __str__(self):
return self.title
The MarkdownxFormField is used for forms, it will thus render with a specific widget, etc. In order to store content in the database, you need a model field.

Related

Django serializer returns empty list

I have a class-based view that returns all the data in the table. But while accessing the URL all I get is an empty list.
models.py
from django.db import models
class EmployeeModel(models.Model):
EmpID = models.IntegerField(primary_key=True)
EmpName = models.CharField(max_length=100)
Email = models.CharField(max_length=100)
Salary = models.FloatField()
class Meta:
verbose_name = 'employeetable'
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import EmployeeModel
from .serializers import EmployeeSerialize
class EmployeeTable(APIView):
def get(self,request):
emp_obj = EmployeeModel.objects.all()
empserializer = EmployeeSerialize(emp_obj,many=True)
return Response(empserializer.data)
serializers.py
from rest_framework import serializers
from .models import EmployeeModel
class EmployeeSerialize(serializers.ModelSerializer):
class Meta:
model = EmployeeModel
fields = '__all__'
urls.py
from django.contrib import admin
from django.urls import path, include
from .views import EmployeeTable, transformer_list
urlpatterns = [
path('display/',EmployeeTable.as_view()),
]
The table has 5 rows. It is not empty.
I want to serialize all 5 rows
I have also created the same but in my case, it worked see the below images
See my serializer
See my models below
and my output is here below
I think there are some issue at your code or some mistake can be there can you please provide full information

Django : HttpRequest.__init__() takes 1 positional argument but 2 were given

So I simply want when I click on the particular article to output its slug, for example if the slug of the given article is django-rules then i want it to be outputted as django-rules when i click on it. just that
here is my model
from django.db import models
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField()
body = models.TextField()
date = models.DateTimeField(auto_now_add = True)
#add in tubnail and author later
def __str__(self):
return self.title
def snippet(self):
return self.body[:50]+'...'
Here is my views.py
from datetime import date
from django.shortcuts import render
from .models import Article
from django.http import HttpRequest
# Create your views here.
def article_list(request):
articles = Article.objects.all().order_by('date')
return render(request,'articles/article_list.html', {'articles': articles} )
def article_detail(request, slug):
return HttpRequest(slug)
url.py
from posixpath import relpath
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from . import views
app_name = 'articles'
urlpatterns = [
path('', views.article_list, name = 'list'),
path('<slug:slug>/', views.article_detail, name = 'detail'),
]
Please dont suggest to add as_view()
its not working.
Instead of return HttpRequest(slug), you need to return HttpResponse(slug).

Django URL Path from DB file value

I am trying to create 'project' pages that have their paths generated with the
{{ project.title }} values, rather than the current method I have which uses ints. I don't quite understand how I can do this, but feel I am close?
Models.py
from django.db import models
# Create your models here.
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
technology = models.CharField(max_length=20)
image = models.FilePathField(path='projects/static/img/')
live = models.URLField()
source = models.URLField()
def __str__(self):
return self.title
Urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.project_index, name="projects"),
path("<int:pk>/", views.project_details, name="project_details"), # PK for Primary Key
]
Views.py
from django.shortcuts import render
from .models import Project
# Create your views here.
def project_index(request):
projects = Project.objects.all()
context = {'projects': projects}
return render(request, 'projects/project_index.html', context)
def project_details(request, pk):
project = Project.objects.get(pk=pk)
context = {'project': project}
return render(request, 'projects/project_details.html', context)
I figure path("<int:pk>/", will need to be a slug, but I just cannot figure out how to tie in the DB data.
Potentially context = {'project': project}?
Currently the url is http://127.0.0.1:8000/projects/1/ - I am looking for http://127.0.0.1:8000/projects/EXAMPLE/
Thanks
You have to add a SlugField to your models.py file:
Models.py
from django.db import models
from django.utils.text import slugify
# Create your models here.
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
technology = models.CharField(max_length=20)
image = models.FilePathField(path='projects/static/img/')
live = models.URLField()
source = models.URLField()
slug = models.SlugField(default="", blank=True, null=False, db_index=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)
Views.py
from django.shortcuts import render
from .models import Project
# Create your views here.
def project_index(request):
projects = Project.objects.all()
context = {'projects': projects}
return render(request, 'projects/project_index.html', context)
def project_details(request, slug):
project = Project.objects.get(slug=slug)
context = {'project': project}
return render(request, 'projects/project_details.html', context)
Urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.project_index, name="projects"),
path("<slug:slug>/", views.project_details, name="project_details"),
]
Make sure to run makemigrations and then migrate.
urls.py
path("<title>/", views.project_details, name="project_details"),
views.py
def project_details(request, title: str):
project = Project.objects.filter(title=title).first()
if project is None:
titles = list(Project.objects.all().values_list('title', flat=True))
msg = f'Project(title=title) not found. Exist titles are: {titles}'
raise Exception(msg)
...

Django ImageField is empty

I am trying to create a form that uses ajax to create a new user. All the other fields work, besides the ImageField. I don't get a error when submitting, but the image will still not save.
Github Repo: https://github.com/VijaySGill/matching-app
urls.py
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('matchingapp/', include('matchingapp.urls')),
path('admin/', admin.site.urls),
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
gender = models.CharField(max_length=6, blank=False)
dateOfBirth = models.DateField(null=True, blank=False)
bio = models.TextField(max_length=500, blank=True)
profileImage = models.ImageField(upload_to="profileimage", blank=True, null=True)
hobby = models.ManyToManyField(Hobby, blank=False)
views.py
#csrf_exempt
def registerUser(request):
...
image = ImageUploadForm(request.POST, request.FILES, instance=newUser)
if image.is_valid():
userprofile = image.save(commit=False)
userprofile.user = request.user
userprofile.save()
...
return JsonResponse(data, safe=False)
register.html
$('form').on('submit',function(e){
e.preventDefault();
...
var fd = new FormData($("#profileImage").get(0));
fd.append("username", $("#username").val());
fd.append("email", $("#email").val());
fd.append("password", $("#password").val());
fd.append("firstName", $("#firstName").val());
fd.append("lastName", $("#lastName").val());
fd.append("gender", gender);
fd.append("dateOfBirth", dob);
fd.append("hobbies", JSON.stringify(selectedHobbies));
if($("#password").val() == $("#confirmPassword").val()){
$.ajax({
type:'POST',
url: '/matchingapp/registerUser/',
processData: false,
contentType: false,
data: fd,
...
});
forms.py
class ImageUploadForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('profileImage',)
I suggest using the following method:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
gender = models.CharField(max_length=6, blank=False)
dateOfBirth = models.DateField(null=True, blank=False)
bio = models.TextField(max_length=500, blank=True)
profileImage = models.ImageField(upload_to="UploadTo('user_photo')", blank=True, null=True)
hobby = models.ManyToManyField(Hobby, blank=False)
Where UploadTo is a class for saving your photos under a directory called user_photo in your media folder.
from django.utils.deconstruct import deconstructible
from uuid import uuid4
#deconstructible
class UploadTo(object):
def __init__(self, path):
self.sub_path = path
def __call__(self, instance, filename):
ext = filename.split('.')[-1]
# get filename
if instance.pk:
filename = '{}.{}'.format(instance.pk, ext)
else:
# set filename as random string
filename = '{}.{}'.format(uuid4().hex, ext)
# return the whole path to the file
return os.path.join(self.sub_path, filename)
This class will set properly the path to be used so that your photo can be found, because the problem is in the path you are passing to upload_to.
Disclaimer: the code above is not mine, but worked well for me.
I would comment, but I can't. How does the post data look like and is the image actually in there?
You might wanna remove blank=True and null=True from the ImageField for testing purposes. Django should complain about the image not being there or something.
if image.is_valid()
might return false and therefore not save the image

How can I create a new url in a Django app?

I have implemented a model in a Django app and I would like add an url to handle the view for this model.
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
Can you help me?
I would recommend the Django tutorial as well: https://docs.djangoproject.com/en/1.10/intro/tutorial01/
However, to answer your question, you could do a setup like this:
views.py:
from django.shortcuts import render
from .models import Post
def my_view(request):
posts = Post.objects.all()
return render(request, 'template.html', {'posts': posts})
urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.my_view, name='my_view')
]

Categories

Resources