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).
Related
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
I'm very new to Django but I started to create a project and I need some help. My question is very basic but I can't find the right answer.
I made a questionnaire that works fine but I don't know how to do that if a logged in user adds his answers Django associate the answers to the user.
Views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.template import loader
from .models import Stressz_teszt
from .forms import StresszForm
from django.forms import ModelForm
def stressz_item(request):
form = StresszForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('stressz/login.html')
return render(request, 'stressz/stressz-form.html', {'form':form})
Urls.py
from . import views
from django.urls import path
from django.forms import ModelForm
urlpatterns = [
path('', views.index, name='index'),
path('login/', views.login, name='login'),
#stressz teszt form
path('add', views.stressz_item, name='stressz_item'),
path('<int:item_id>/', views.detail, name='detail'),
Forms.py
from django import forms
from django.forms import ModelForm
from .models import Stressz_teszt
class StresszForm(forms.ModelForm):
class Meta:
model = Stressz_teszt
fields = ['stressz_v01', 'stressz_v02', 'stressz_v03', 'stressz_v04', 'stressz_v05',] ...
Models.py
from django.db import models
from django.contrib.auth.models import User
class Stressz_teszt(models.Model):
def __str__(self):
return self.stressz_name
user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
stressz_name = models.CharField(max_length=200)
stressz_company = models.CharField(max_length=300)
stressz_v01 = models.IntegerField()
stressz_v02 = models.IntegerField()
stressz_v03 = models.IntegerField()
stressz_v04 = models.IntegerField()
stressz_v05 = models.IntegerField()
...
Thank you in advance!
You can do it like this :
def stressz_item(request):
if form.is_valid():
stressz_teszt = form.save(commit=False)
stressz_teszt.user_name = request.user
stressz_teszt.save()
return redirect('stressz/login.html')
return render(request, 'stressz/stressz-form.html', {'form': form})
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.
I'm very new to Django and a bit overwhelmed by the documentation. I think my problem is pretty simple but everything i've found just confused me more.
I am building a little news app with a model NewsItem:
from django.db import models
from django.utils import timezone
# Create your models here.
class NewsItem(models.Model):
title = models.CharField(max_length=50)
newsText = models.TextField()
dateEntered = models.DateTimeField('date entered')
datePublished = models.DateTimeField('date published', blank=True, null=True)
user = models.CharField(max_length=30) #temporary field. will be changed to user foreign key
def __str__(self):
return self.title
def publish(self):
if (self.datePublished == None):
self.datePublished = timezone.now()
def published(self):
return self.datePublished != None
two views (technically 3) index and detail
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.views import generic
from .models import NewsItem
# Create your views here.
class IndexView(generic.ListView):
template_name = 'news/index.html'
context_object_name = 'latestNewsList'
def get_queryset(self):
return NewsItem.objects.order_by('-datePublished')[:5]
#todo
class DetailView(generic.DetailView):
model = NewsItem
template_name = 'news/detail.html'
def publish(request, itemId):
newsItem = get_object_or_404(NewsItem, pk=itemId)
newsItem.publish()
newsItem.save()
return HttpResponseRedirect(reverse('news:detail', args=(newsItem.id,)))
and an urlconf like this
from django.urls import path
from . import views
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:itemId>/publish', views.publish, name='publish'),
]
In the detail view i have a link Publish which just triggers the function views.publish. This view is supposed to redirect back to the detail view.
What i'm trying to do now is to display a little message (like article successfully published) in detail view when it was redirected by the publish view. But i have no idea what would be a good aproach
I could just render the details template in the publish view, but then it would still say news/publish in the URL instead of news/detail
Thanks in advance for your help
Have a look at the messages framework. You could add a success message before redirecting, which will be displayed on the next page.
from django.shortcuts import redirect
from django.contrib import messages
def publish(request, itemId):
newsItem = get_object_or_404(NewsItem, pk=itemId)
newsItem.publish()
newsItem.save()
messages.success(request, "The post has been published")
return redirect('news:detail', newsItem.id)
Note that I've simplified the return statement to use redirect(...) instead of HttpResponseRedirect(reverse(...)).
I'm making a blog and learning django as I go. I'm trying to incorporate urls that include both sluglines and post ids.
When I click on the "view on site" link in the admin panel, I get this error:
NoReverseMatch at /admin/r/7/2/ Reverse for 'article' with arguments '(u'test-post-3', '2')' and keyword arguments '{}' not found. 0 pattern(s) tried: []
When I manually enter the url, I get this error:
TypeError at /articles/test-post-3,2/ get_object_or_404() takes at least 1 argument (0 given)
Here's my code:
views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
# Create your views here.
from articles.models import Content
class IndexView(generic.ListView):
template_name = 'articles/index.html'
context_object_name = 'latest_articles_list'
def get_queryset(self):
return Content.objects.filter(
published_date__lte=timezone.now()
).order_by('-published_date')[:5]
def detail(request, slugline, id):
article = get_object_or_404(pk=id)
return render(request, 'articles/detail.html', {'article': article})
urls.py:
from django.conf.urls import patterns, url
from articles import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name = 'index'),
#url(r'^(?P<slugline>[-\w\d]+), (?P<pk>\d+)/$', views.DetailView.as_view(), name='detail')
url(r'^(?P<slugline>[-\w\d]+),(?P<id>\d+)/$', view=views.detail, name='article'),
)
models.py:
from django.db import models
from django.db.models import permalink
from django.utils import timezone
import datetime
# Create your models here.
class Content(models.Model):
title = models.CharField(max_length=100, unique=True)
slugline = models.SlugField(max_length=100, unique=True)
body = models.TextField()
published_date = models.DateTimeField('date published')
def __unicode__(self):
return self.title
#permalink
def get_absolute_url(self):
# return ('article', (), {
# 'slugline': self.slugline,
# 'id': self.id,
# })
from django.core.urlresolvers import reverse
return reverse('article', args=[self.slugline, str(self.id)])
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.published_date <= now
was_published_recently.admin_order_field = 'published_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
main urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'the_Bluntist.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^articles/', include('articles.urls', namespace="articles")),
url(r'^admin/', include(admin.site.urls)),
)
You have a bad usage of get_object_or_404:
Docstring:
get_object_or_404(klass, *args, **kwargs)
Uses get() to return an object, or raises a Http404 exception if the object
does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.
Note: Like with get(), an MultipleObjectsReturned will be raised if more than one
object is found.
You can make as following:
article = get_object_or_404(Article, pk=id)
article = get_object_or_404(Article.objects, pk=id))
article = get_object_or_404(Article.objects.all(), pk=id))
article = get_object_or_404(Article.objects.filter(pk=id))
article = get_object_or_404(pk=id)
You must pass the model and the filter to the call. Documentation here.
article = get_object_or_404(klass, pk=id)