Creating a separate comments app for ticket app. My issue is that when I create and submit my comment on a particle ticket, it creates its own new page of tickets instead of being attached to original ticket. I think the issue has to do with my urls.py file and I feel like i'm close to solving this but i’m not sure how to proceed.
Here is my comment models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from tickets.models import Ticket
class Comment(models.Model):
ticket = models.ForeignKey(Ticket, related_name='comments', on_delete=models.CASCADE,
null=True)
title = models.CharField(max_length=20)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('tickets:ticket-detail', kwargs={'pk': self.pk})
Here is my ticket models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from users.models import Profile
class Ticket(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
assignee = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True)
status = models.BooleanField(choices=MARKED, default=True)
priority = models.TextField(choices=PRIORITIES, default='None', max_length=10)
label = models.CharField(choices=TYPES, default='Misc', max_length=100)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('ticket-detail', kwargs={'pk': self.pk})
Here is the main urls.py
from django.conf import settings
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
app_name = 'tickets'
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('users.urls')),
path('', include(('tickets.urls', 'tickets'), namespace='tickets')),
path('', include('tickets.urls')),
path('', include('comments.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Here is the ticket urls.py
from django.conf import settings
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
app_name = 'tickets'
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('users.urls')),
path('', include(('tickets.urls', 'tickets'), namespace='tickets')),
path('', include('tickets.urls')),
path('', include('comments.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Here is my comments urls.py
from django.urls import include, path
from .views import (
CommentListView,
CommentCreateView,
CommentUpdateView,
CommentDeleteView,
)
urlpatterns = [
path('tickets/<int:pk>/', CommentListView.as_view(), name='ticket-detail'),
path('tickets/<int:pk>/comments/new/', CommentCreateView.as_view(), name='comment-create'),
path('tickets/comments/<int:pk>/update/', CommentUpdateView.as_view(), name='comment-update'),
path('tickets/comments/<int:pk>/delete/', CommentDeleteView.as_view(), name='comment-delete'),
]
Related
I am trying to build a website on cPanel using django. My models were working fine untill I created my first html page and tried to render it. Now whenever I try to load my site I get "AttributeError at /admin/
module 'artclBlog.views' has no attribute 'home'" pic of error message
my views.py
from django.shortcuts import render, get_object_or_404
from .models import Blog
def home(request):
blogs = Blog.objects.order_by('-date')
return render(request, 'blog/home.html', {'blogs': blogs})
my urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from artclBlog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('blog/', include('blog.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
my models.py
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=200, default='')
summary = models.CharField(max_length=200, default='')
pageOne = models.TextField(default='')
pageTwo = models.TextField(default='')
pageThree = models.TextField(default='')
pageFour = models.TextField(default='')
date = models.DateField(default='')
def __str__(self):
return self.title
I am using django 2.2.2 . I am trying to include path('api/', include('music.urls')),into my root url but I get an exception thrown from resolvers.py file.
Here is my music/urls.py
urls.py
from django.urls import path
from . import views
app_name = 'music'
urlpatterns = [
path('songs/', ListSongsView.as_view(), name = 'songs-all'),
]
here is my root url file
urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('music.urls')),
]
views.py
from django.shortcuts import render
from rest_framework import generics
from .models import Songs
from serializers import SongSerializer
# Create your views here.
class ListSongsView(generics.ListApiView):
queryset = Songs.objects.all()
serializer_class = SongsSerializer
models.py
from django.db import models
# Create your models here.
class Songs(models.Model):
title = models.CharField(max_length=255, null = False)
artist = models.CharField(max_length=50, null= False)
def __str__(self):
return "{} - {}".format(self.title, self.artist)
and my stacktrace
File "/home/brianonchari/Documents/django/drf/myapi/lib/python3.5/site-
packages/django/urls/resolvers.py", line 588, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'rest.urls' does not
appear to have any patterns in it. If you see valid patterns in the file then the issue is
probably caused by a circular import.
music/urls.py
from django.urls import path
from .views import ListSongsView
app_name = 'music'
urlpatterns = [
path('songs/', ListSongsView.as_view(), name='songs-all'),
]
root urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('music.urls')),
]
music/views.py:
from django.shortcuts import render
from rest_framework import generics
from .models import Songs
from .serializers import SongSerializer
# Create your views here.
class ListSongsView(generics.ListAPIView):
queryset = Songs.objects.all()
serializer_class = SongSerializer
music/models.py:
from django.db import models
# Create your models here.
class Songs(models.Model):
title = models.CharField(max_length=255, null=False)
artist = models.CharField(max_length=50, null=False)
def __str__(self):
return "{} - {}".format(self.title, self.artist)
music/serializers.py:
from rest_framework import serializers
from .models import Songs
class SongSerializer(serializers.ModelSerializer):
class Meta:
model = Songs
fields = ('title', 'artist')
run your migration for Songs model:
python manage.py makemigrations
python manage.py migrate
I followed the qblog tutorial, using python 2.7.10 and django 1.9.5.
When i enter the admin's blog interface, and clicked add blog entry, then it shown me below:
TemplateDoesNotExist at /admin/blog/entry/add/
django_markdown/editor_init.html
but i have installed django-markdown already. I would like to show the code below:
models.py:
class Entry(models.Model):
title = models.CharField(max_length=200)
body = MarkdownField()
slug = models.SlugField(max_length=200, unique=True)
publish = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField(Tag)
objects = EntryQuerySet.as_manager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("entry_detail", kwargs={"slug": self.slug})
class Meta:
verbose_name = "Blog Entry"
verbose_name_plural = "Blog Entries"
ordering = ["-created"]
admin.py:
from django.contrib import admin
from . import models
from django_markdown.admin import MarkdownModelAdmin
from django_markdown.widgets import AdminMarkdownWidget
from django.db.models import TextField
class EntryAdmin(MarkdownModelAdmin):
list_display = ("title", "created")
prepopulated_fields = {"slug": ("title",)}
# Next line is a workaround for Python 2.x
formfield_overrides = {TextField: {'widget': AdminMarkdownWidget}}
admin.site.register(models.Entry, EntryAdmin)
admin.site.register(models.Tag)
qblog/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
import settings
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^markdown/', include("django_markdown.urls")),
url(r'^', include('blog.urls')),
)
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
You need to add the editor_init.html file in your project.
If your project root is project/ there should be a directory called templates in there. If that directory does not exist, create it (so the path would be project/templates).
Place the editor_init.html file in this directory and everything should work.
You can find more information about setting up templates here and in the django docs.
I think I done everything correct but I don't know why it doesn't work. When I try to reach a page I get error "Page not found (404)".
So, this all products page works 127.0.0.1:8000/products/ but when I try to visit single product page 127.0.0.1:8000/products/audi I get error that it's not found...
So, maybe you what's wrong here?
Thank you.
Page not found (404)
Request Method: GET
Request URL: http://link/products/audi
Using the URLconf defined in ecommerce.urls, Django tried these URL patterns, in this order:
^static/(?P<path>.*)$
^media/(?P<path>.*)$
^admin/doc/
^admin/
^products/ ^$ [name='products']
^products/ ^$(?P<slug>.*)/$
^contact/ [name='contact_us']
The current URL, products/audi, didn't match any of these.
Main project urls.py:
from django.conf import settings
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT
}),
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT
}),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^products/', include('products.urls')),
url(r'^contact/', 'contact.views.contact_us', name='contact_us'),
)
Products app urls.py:
from django.conf import settings
from django.conf.urls import patterns, include, url
urlpatterns = patterns('products.views',
url(r'^$', 'all_products', name='products'),
url(r'^$(?P<slug>.*)/$', 'single_product'),
)
views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, RequestContext, get_object_or_404
from .models import Product
def all_products(request):
products = Product.objects.filter(active=True)
return render_to_response('products/all.html', locals(), context_instance=RequestContext(request))
def single_product(request, slug):
product = get_object_or_404(Product, slug=slug)
return render_to_response('products/single.html', locals(), context_instance=RequestContext(request))
models.py
from django.db import models
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length=220)
description = models.CharField(max_length=3000, null=True, blank=True)
price = models.DecimalField(max_digits=1000, decimal_places=2, null=True, blank=True)
slug = models.SlugField()
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
def __unicode__(self):
return self.title
class Meta:
ordering = ['title',]
class ProductImage(models.Model):
product = models.ForeignKey(Product)
description = models.CharField(max_length=3000, null=True, blank=True)
image = models.ImageField(upload_to='product/images/')
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
def __unicode__(self):
return self.image
Your URL pattern has an extra $ at the beginning, so it can never match anything:
url(r'^$(?P<slug>.*)/$', 'single_product')
This should be:
url(r'^(?P<slug>.*)/$', 'single_product')
This still requires a trailing slash, which is the normal pattern. With that corrected, your URL should be /products/audi/. You don't show the context in which that URL is created, but this is one example of why it's a good idea to use Django's url reversal to build URLs if at all possible. That would look something like this, in Python code (for instance, possibly in a get_absolute_url method on the model:
reverse('single_product', kwargs={'slug': someproduct.slug})
Or like this, in a template:
Django 1.5:
{% url 'single_product' someproduct.slug %}
Django 1.4 and earlier:
{% url single_product someproduct.slug %}
You have a typo:
url(r'^$(?P<slug>.*)/$', 'single_product'),
Note this $ just after ^, in regexp it states for a string end. Replace with
url(r'^(?P<slug>.*)/$', 'single_product'),
name 'entry_resource' is not defined
This is my models.py
from tastypie.utils.timezone import now
from django.contrib.auth.models import User
from django.db import models
from django.template.defaultfilters import slugify
class Entry(models.Model):
user = models.ForeignKey(User)
pub_date = models.DateTimeField(default=now)
title = models.CharField(max_length=200)
slug = models.SlugField()
body = models.TextField()
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
# For automatic slug generation.
if not self.slug:
self.slug = slugify(self.title)[:50]
return super(Entry, self).save(*args, **kwargs)
This is my api.py:
from tastypie.resources import ModelResource
from links.models import Entry
class EntryResource(ModelResource):
class Meta:
queryset = Entry.objects.all()
resource_name = 'entry'
This is my urls.py
from django.conf.urls import patterns, include, url
from links.api import EntryResource
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
(r'^api/', include(entry_resource.urls)),
)
I'm quite sure I am doing something rather silly. Just not able to find what though.
From official tastypie documentation (https://github.com/toastdriven/django-tastypie#whats-it-look-like):
# urls.py
# =======
from django.conf.urls.defaults import *
from tastypie.api import Api
from myapp.api import EntryResource
v1_api = Api(api_name='v1')
v1_api.register(EntryResource())
urlpatterns = patterns('',
# The normal jazz here then...
(r'^api/', include(v1_api.urls)),
)