I've been banging my head about this for a week or so in my spare time, I currently have in my model
import recurrence.fields
.
.
.
course_recurring = recurrence.fields.RecurrenceField(null=True)
I can add recurrences and retrieve them in the admin console, but this in the template: {{ course.course_recurrence.rrules }} returns nothing.
I was suffering from the same problem, but I solved it.
Please try below steps:
1) Include {{form.media}} in your html head tag.
2) Please include the following before urlpatterns =[...]
-js_info_dict = {'packages': ('recurrence', ),}
3) Then add this url in the urls.py which includes your template:
-url(r'^jsi18n/$', django.views.i18n.javascript_catalog, js_info_dict)
Note: You need to import django library by including following line in your same urls.py file
-import django
This configuration works well for the new Django:
urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from django.views.i18n import JavaScriptCatalog
urlpatterns = [
path('admin/', admin.site.urls),
# ...
path('jsi18n/', JavaScriptCatalog.as_view(packages=['recurrence']), name='javascript-catalog'),
]
# Connect static files
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
course_form.html
<html>
<head>
<script type="text/javascript" src="{% url 'javascript-catalog' %}">
</script>
</head>
<body>
<form method="post" class="post-form">
{% csrf_token %}
{{ form.media }}
{{ form }}
<button type="submit">Submit</button>
</form>
</body>
</html>
views.py
class CourseCreateView(CreateView):
model = Course
fields = ['title', 'price', 'recurrences']
success_url = reverse_lazy('course-list')
forms.py
from django import forms
from .models import Course
class CourseForm(forms.ModelForm):
class Meta:
model = Course
fields = ('title', 'price', 'recurrences', )
models.py
from django.db import models
from recurrence.fields import RecurrenceField
class Course(models.Model):
title = models.CharField(max_length=255)
price = models.PositiveSmallIntegerField()
recurrences = RecurrenceField()
def __str__(self):
return self.title
class Meta:
verbose_name = 'Course'
verbose_name_plural = 'Courses'
Related
I was working on a django project. I made a userprofiles app to manage(create, update) user's profile in my website, but it is not working properly. I am getting 'This field is required' &
'no file chosen' while making profile as a user and if I do blank=True in models profile_picture user pictures are not saving in the media url.
I have tried so many tips from stackoverflow but they are not working.
here is my code:
# settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = str(BASE_DIR.joinpath('media'))
# models.py
from django.db import models
from django.contrib.auth import get_user_model
import uuid
class UserProfile(models.Model):
author = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
profile_picture = models.ImageField(upload_to='images/')
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
bio = models.TextField(blank=True)
occupation = models.CharField(max_length=100)
hobbies = models.TextField(blank=True)
date_of_birth = models.TimeField()
def __str__(self):
return self.author.username + ("'s profile")
# views.py
from django.views.generic import CreateView
from .forms import CustomUserCreationForm
from django.urls import reverse_lazy
class SignUpView(CreateView):
form_class = CustomUserCreationForm
template_name = "registration/signup.html"
success_url = reverse_lazy("profile_create")
# project-level urls.py
from django.contrib import admin
from django.conf import settings
from django.urls import path, include
from django.conf.urls.static import static
from django.views.generic.base import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path("accounts/", include("accounts.urls")),
path("accounts/", include("django.contrib.auth.urls")),
path("profile/", include("userprofiles.urls")),
path("", TemplateView.as_view(template_name="home.html"), name="home"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# app-level urls.py
from django.urls import path
from .views import ProfileCreateView
urlpatterns = [
path("create/", ProfileCreateView.as_view(), name="profile_create")
]
# profile_create.html
{% extends 'base.html' %}
{% block title %}Create Your Profile{% endblock title %}
{% block content %}
<h2>Create Your Profile</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Create my profile</button>
</form>
{% endblock content %}
tell me what is the problem with it, I am stucked out of it, Thank you
I believe you missed enctype in html form,
enctype="multipart/form-data"
from docs,
Note that request.FILES will only contain data if the request method
was POST, at least one file field was actually posted, and the
that posted the request has the attribute
enctype="multipart/form-data". Otherwise, request.FILES will be empty.
HTML form should be,
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Create my profile</button>
</form>
Sir, I'm developing a slug project in Django. When I try to print the slug id post it will not display shows 404 error. Tried n number of times. Anyone, please help me to fix this in urls.py.
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/postscommentapp/6/how-learn-anything-very-easily
Using the URLconf defined in postscommentpro.urls, Django tried these URL patterns, in this order:
admin/
postscommentapp/(?P\d+)/(?P[\w-]+)/$ [name='post_detail']
The current path, postscommentapp/6/how-learn-anything-very-easily, didn't match any of these.
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'draft'),
('published', 'published')
)
title = models.CharField(max_length=50)
slug = models.CharField(max_length=50)
author = models.ForeignKey(User, on_delete = models.CASCADE)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft')
def __str__(self):
return self.title
admin.py
from django.contrib import admin
from .models import Post
# Register your models here.
class AdminPost(admin.ModelAdmin):
list_display = ['title', 'slug', 'body', 'author', 'created', 'updated', 'status']
prepopulated_fields = {'slug':('title',)}
list_editable = ('status',)
admin.site.register(Post, AdminPost)
views.py
from django.shortcuts import render
from .models import Post
# Create your views here.
def post_List(request):
posts = Post.objects.all()
return render(request, 'postscommentapp/post_list.html', {'posts':posts})
def post_detail(request, id, slug):
post = Post.objects.get(id=id)
return render(request, 'postscommentapp/post_detail.html', {'post':post})
url.py - postscommentapp
from django.urls import path
from postscommentapp import views
urlpatterns = [
path('', views.post_List, name=''),
path('postscommentapp/(?P<id>\d+)/(?P<slug>[\w-]+)/$', views.post_detail, name='post_detail'),
]
urls.py
"""postscommentpro URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('postscommentapp.urls')),
]
post_detail.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>{{ post.title }}</h2>
</body>
</html>
post_list.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- Bootstrap CDN Lines -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght#600;700&display=swap" rel="stylesheet">
</head>
<style>
.col-md-6{
text-align: justify;
}
.img-thumbnail{
border:1px solid #6b6b47;
}
.title{
font-family: 'Poppins', sans-serif;
}
</style>
<body style="font-family: 'Poppins', sans-serif;">
<div class="container-fluid">
<br>
<h2 class="text-center" style="font-weight:bold; color: #0040ff;">Post Comments Python/Django Project:</h2>
<div class="row">
{% for each_item in posts %}
<div class="col-md-6">
<br>
<div class="img-thumbnail">
⭐ {{ each_item.title }}<small style="float:right">{{ each_item.created }}</small><br>
➟ Author: {{ each_item.author }}<br><br>
{{ each_item.body }}<br>
</div>
<br>
</div>
{% endfor %}
</div>
</div>
</body>
</html>
I solved this error in my own way. In urls.py postscommentapp
from django.urls import path
from postscommentapp import views
urlpatterns = [
path('', views.post_List, name=''),
path('postscommentapp/(?P<id>\d+)/(?P<slug>[\w-]+)/$', views.post_detail, name='post_detail'),
]
change this url code in to this urls.py - postscommentapp
from django.urls import path
from postscommentapp import views
urlpatterns = [
path('', views.post_List, name=''),
path('post/<int:id>/<slug:slug>/', views.post_detail, name='post_detail'),
]
Write this line in views.py
from django.shortcuts import render, get_object_or_404
from .models import Post
# Create your views here.
def post_List(request):
posts = Post.objects.all()
return render(request, 'postscommentapp/post_list.html', {'posts':posts})
def post_detail(request, id, slug):
# post = Post.objects.get(id=id)
post = get_object_or_404(Post, id=id, slug=slug)
return render(request, 'postscommentapp/post_detail.html', {'post':post})
I'm getting a NoReverseMatch error in my home page. It is from the html that I injected from my announcement app. It says that the reverse of the link is cannot be found. When I removed that line It shows the card but the text with template tag.
_announcement_home.html:
<div class="container">
<div class="card announcement-card" style="width: 18rem;">
<h5 class="card-header">Announcement</h5>
<div class="card-body">
<h5 class="card-title">{{announcement.title}}</h5>
<p class="card-text">{{announcement.text}}</p>
<span class="announcement-date">{{announcement.date}}</span>
{% if user.is_authenticated %}
Change
{% endif %}
</div>
</div>
<br>
</div>
index.html:
{% extends 'base.html' %}
{% block content %}
<div class="w3-container w3-teal">
<h1>BANNER HERE</h1>
<p>Dito yung banner</p>
</div>
{% include 'announcement/_announcement_home.html' %}
{% endblock %}
urls.py:
from django.urls import path
from . import views
app_name = 'announcement'
urlpatterns = [
path('create/', views.AnnouncementCreateView.as_view(), name='create'),
path('', views.AnnouncementListView.as_view(), name='list'),
path('posts/<int:pk>/', views.AnnouncementDetailView.as_view(), name='single'),
path('delete/<int:pk>/', views.AnnouncementDeleteView.as_view(), name='destroy'),
path('edit/<int:pk>/', views.AnnouncementUpdateView.as_view(), name='edit')
]
main urls.py:
"""urcipro URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from home import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.Home.as_view(), name='home'),
path('bod/', views.BOD.as_view(), name='bod'),
path('announcement/', include('announcement.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
views.py:
from django.shortcuts import render
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy, reverse
from django.contrib import messages
from . import forms
from . import models
# Create your views here.
class AnnouncementListView(LoginRequiredMixin, generic.ListView):
model = models.Announcement
class AnnouncementDetailView(LoginRequiredMixin, generic.DetailView ):
model = models.Announcement
class AnnouncementUpdateView(LoginRequiredMixin, generic.UpdateView):
model = models.Announcement
form_class = forms.AnnouncementForm
class AnnouncementCreateView(LoginRequiredMixin, generic.CreateView ):
model = models.Announcement
form_class = forms.AnnouncementForm
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
class AnnouncementDeleteView(LoginRequiredMixin, generic.DeleteView ):
model = models.Announcement
def get_success_url(self):
return reverse('home')
def delete(self, *args, **kwargs):
messages.success(self.request, "Post Deleted")
return super().delete(*args, **kwargs)
home app views.py:
from django.shortcuts import render
from django.views.generic import TemplateView
# Create your views here.
class Home(TemplateView):
template_name = 'index.html'
class BOD(TemplateView):
template_name = 'bod.html'
This is what I see when I remove the a tag:
Error traceback:
It looks like the context has announcement to display this information, and then you used self in the url tag which isn't defined.
So change the url param to announcement.pk which we can assume will exist because that's the object in use with this block.
<div class="card-body">
<h5 class="card-title">{{announcement.title}}</h5>
<p class="card-text">{{announcement.text}}</p>
<span class="announcement-date">{{announcement.date}}</span>
{% if user.is_authenticated %}
Change
{% endif %}
</div>
I'd like to add Imageform to my form to allow all users to add a photo.
I've read this https://docs.djangoproject.com/en/dev/ref/forms/fields/#imagefield
and this https://docs.djangoproject.com/en/dev/ref/forms/api/#binding-uploaded-files
but still I'm confused about how to achieve that. How can I change my codes to allow users to add a photo from their own folders?Here's my codes and I also attached the ideal form I'd like to create.
[My ideal form]
models.py
from django.db import models
from django.forms import ModelForm
class Sell(models.Model):
subject = models.CharField(max_length=100)
price = models.CharField(max_length=100)
condition = models.CharField(max_length=100)
photo = models.ImageField(upload_to="media")
email = models.EmailField()
body = models.CharField(max_length=200)
forms.py
from django.forms import ModelForm
from uasite1.models import Sell
class SellForm(ModelForm):
class Meta:
model = Sell
views.py
from django.shortcuts import render_to_response,get_object_or_404
from django.http import HttpResponseRedirect
from uasite1.forms import SellForm
from uasite1.models import Sell
from django.template import RequestContext
def sell_create(request):
context = {}
if request.method == 'POST':
form = SellForm(request.POST)
if form.is_valid():
new_sell = form.save()
return HttpResponseRedirect('/sechand/%d/' % new_sell.pk)
else:
form = SellForm()
context['form'] = form
return render_to_response('sell.html',context,context_instance = RequestContext(request))
sell.html
{% extends 'base.html' %}
{% block extrahead %}
{% endblock %}
{% block content %}
<form enctype="multipart/form-data" action = "/sechand/" method = "post">
{% csrf_token %}
{{ form.as_p }}
<input type = "submit" value="Submit" />
</form>
{% endblock%}
sell_display.html (this is the template where the submitted information would show up.)
{% extends 'base.html' %}
{% block content %}
<div id = 'sell'>
<h3> Product Name : [ {{ sell.subject }}]</h3>
<p>Photo{{ sell.photo }}</p>
<p>Price: [ {{ sell.price }} ]</p>
<p>Condition: [ {{ sell.condition }} ]</p>
<p>Comments: [ {{sell.body}} ]</p>
<p>Contact Email:[ {{ sell.email }} ]</p>
</div>
{% endblock %}
urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^sechand/$','uasite1.views.sell_create'),
url(r'^sechand/(?P<pk>\d+)/$', 'uasite1.views.sell_detail'),
url(r'^products/electronics/$', 'uasite1.views.Electronics'),
url(r'^products/$', 'uasite1.views.ProductsAll'),
url(r'^admin/', include(admin.site.urls)),
)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I did not go through your entire code but I can notice 1 important mistake, view should have the following:
form = SellForm(request.POST, request.FILES)
Also, this line:
<p>Photo{{ sell.photo }}</p>
I don't think that's the way to show a photo, I would put a link to the photo doing:
<p>Photo{{ sell.photo.url }}</p>
And finally, for development environments you may want to serve media files so just add this line to your main urls.py file:
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = patterns('',
# your url patterns in here
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
editing:
Serving media files. That link should give you a good overview, it's confusing I know, so I am going to give you an example, just like I do in my projects. First the way I do it in settings.py:
#settings.py
from os.path import dirname, join, realpath
# have in mind that I have settings.py under project_root/project/settings.py
# so you probably want to check your path to your project root folder first
ROOT_DIR = realpath(join(dirname(__file__), '..'))
MEDIA_ROOT = realpath(join(ROOT_DIR, 'media'))
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
join(ROOT_DIR, "static"),
)
That's the way I do it, you could find many ways that also work. To give you a better clue my folders look like this:
project_root/
media/
static/
project/
settings.py
i get :
Using the URLconf defined in blog.urls, Django tried these URL patterns, in this order:
^ ^$
^ ^/(?P[a-zA-Z0-9]+) [name='view_blog_post']
The current URL, duzeltme-yazisi/, didn't match any of these.
this error.
here some outputs :
urls.py (in project folder) :
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^', include('userside.urls')),
)
urls.py (in app's folder) :
from django.conf.urls import patterns, include, url
urlpatterns = patterns('userside.views',
url(r'^$','index'),
url(r'^/(?P<postslug>[^\.]+)','userside.views.singlePost',name='view_blog_post'),
)
views.py :
from userside.models import Post
from django.shortcuts import render_to_response
from django.template import RequestContext
def index(request):
post_list = Post.objects.all()
return render_to_response('userside/index.html',
{'post_list':post_list},
context_instance = RequestContext(request))
def singlePost(request,postslug):
post = Post.objects.get(slug=postslug)
context = {'post':post}
return render_to_response('userside/detail.html',context,context_instance = RequestContext(request))
models.py :
from django.db import models
#from django.utils import timezone
from django.db.models import permalink
class Post(models.Model):
title = models.CharField(max_length = 100)
# date = models.DateTimeField(auto_now_add=True)
text = models.TextField()
slug = models.SlugField(unique=True)
def __unicode__(self):
return self.title
#permalink
def get_absolute_url(self):
return ('view_blog_post',None, {'postslug':self.slug})
and here is my index.html template file :
<html>
<head>
<title>Welcome</title>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/index.css" />
</head>
<body>
<h1>Hello Mars</h1>
<br>
{% if post_list %}
{% for x in post_list %}
<p>{{ x.title }}</p>
<p>{{ x.text }}</p>
<hr>
{% endfor %}
{% else %}
<div class="center">No records! ( but looks like code works correctly!)</div>
{% endif %}
</body>
</html>
Django version : 1.4
whats wrong here ? :/
thank you
project - urls.py
url(r'^$', include('userside.urls')),
userside - urls.py
url(r'^(?P<postslug>[-\w]+)/$',
# ../gis-grundlagen/
view = 'singlePost',
name = 'userside-single-post',
),
userside - views.py
def singlePost(request, postslug):
post = get_object_or_404(Post, slug=postslug)
context = {'post':post}
return render_to_response('userside/detail.html',context,context_instance = RequestContext(request))
There shouldn't be a $ when using include, try:
url(r'^', include('userside.urls')),
normally you would have a subfolder indicated, e.g.
url(r'^userside/', include('userside.urls')),
The initial slash (/) is probably also a mistake:
url(r'^/(?P<postslug>[^\.]+).html','userside.views.singlePost',name='view_blog_post'),
should likely be
url(r'^(?P<postslug>[^\.]+).html','userside.views.singlePost',name='view_blog_post'),