Associate multiple unique forms to a unique object in Django - python

I'm trying to build a web application using Django where a user can create a 'Project' and within that 'Project', there are four different forms.
My Question is, how do I associate those forms to a specific 'project' in the sense that the form is linked to that specific 'project'.
I'm close to doing it but I'm having issues with the 'create-project.html', 'create-request-1.html' and 'create-request-2.html' pages from rendering due to the 'PK' in the 'projects.html' page URL.
The exact errors I get for navigating to those pages is -
NoReverseMatch at /projects/create-project/
Reverse for 'initiate_project' with no arguments not found. 1 pattern(s) tried: ['projects\\/project\\/(?P<pk>[0-9]+)\\/$']
Or
NoReverseMatch at /project/create-post-1/
Reverse for 'initiate_project' with no arguments not found. 1 pattern(s) tried: ['projects\\/project\\/(?P<pk>[0-9]+)\\/$']
The path is as follows -
'projects.html' -
'create-project.html' -
'initiate-project.html' -
'create-request-1.html'
'create-request-2.html'
I can navigate and go into each unique 'project' (e.g. project 1, project 2) in 'projects.html' but I can't get into my forms ('create-request-1.html', 'create-request-2.html') inside the 'initiate-project.html' page that's within each 'project' in the 'projects.html' page.
Here's my code so far -
model.py -
from django.db import models
class create_new_project(models.Model):
list_display = ('project_name', 'project_manager',
'technical_lead', 'test_lead')
class Meta:
verbose_name = 'Create New Project'
verbose_name_plural = 'Create New Projects'
project_name = models.CharField(max_length=100)
project_manager = models.CharField(max_length=100)
technical_lead = models.CharField(max_length=100)
test_lead = models.CharField(max_length=100)
environment_choices = (
('1', '1'),
('2', '2'),
('3', '3')
)
environment = models.CharField(
max_length=50, choices=environment_choices, default='ICCS')
def __str__(self):
return self.project_name
views.py
from django.shortcuts import render
from django.shortcuts import render, get_object_or_404
from main.models import *
# Create your views here.
def index(request):
return render(request, 'main/index.html')
def projects(request):
CreateNewProject = create_new_project.objects.all()
args = {'CreateNewProject': CreateNewProject}
return render(request, 'main/projects.html', args)
def create_project(request):
return render(request, 'main/create-project.html')
def initiate_project(request, pk):
InitiateProjectURL = get_object_or_404(create_new_project, pk=pk)
return render(request, 'main/initiate-project.html', {'InitiateProjectURL': InitiateProjectURL})
def create_post_request_1(request):
return render(request, 'main/create-post-request-1.html')
def create_post_section_2(request):
return render(request, 'main/create-post-request-2.html')
urls.py
from django.urls import include, path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('projects/', views.projects, name='projects'),
path('projects/create-project/', views.create_project, name='create_project'),
path('projects/project/<int:pk>/',
views.initiate_project, name='initiate_project'),
path('project/create-post-request-1/',
views.create_post_request_1, name='create_post_paid_request_section_1'),
path('project/create-post-request-2/',
views.create_post_request_2, name='create_post_request_2'),
]
projects.html
<div class="row">
<a href="{% url 'create_project' %}" class="card card-1 bg-red shadow m-2">
<div class="card-body d-flex h-100">
<div class="text-center mx-auto justify-content-center align-self-center">
{% load staticfiles %}
<img src="{% static 'main/images/plus.svg' %}" alt="Plus Icon" height="60vh">
<div class="mb-3 pt-4 text-white">Create New Project</div>
</div>
</div>
</a>
{% for create_new_project in CreateNewProject %}
<div class="card card-1 bg-white shadow m-2">
<div class="card-body">
<h4 class="card-title text-red">{{ create_new_project.project_name }}</h4>
<div class="card-text pt-2 pb-2">
<div class="mb-3"><b>Project Manager: </b>{{ create_new_project.project_name }}</div>
<div class="mb-3"><b>Project Lead: </b>{{ create_new_project.project_manager }}</div>
<div class="mb-3"><b>Test Lead: </b>{{ create_new_project.test_lead }}</div>
<div class="mb-3"><b>Environment: </b>{{ create_new_project.environment }}</div>
</div>
<div class="float-right">
<a href="{% url 'initiate_project' pk=create_new_project.pk %}" class="text-red">
{% load staticfiles %}
<img src="{% static 'main/images/next.svg' %}" class="text-red" alt="Next Icon" height="25vh"></a>
</div>
</div>
</div>
{% endfor %}
</div>
create-post-request-1.html / create-post-request-2.html
<div class="col-md-2">
Cancel
</div>
To better illustrate what I'm trying to do, See the following image - Visual description

the href for the a tag in create-post-request-1.html / create-post-request-2.html should be sth like "{% url 'initiate_project' pk=any_pk_you_choose %}" instead of {% url 'initiate_project' %}

Related

i cant make the image_url to load on local host please hlp

i am making like a demo website that sells fruits i am following a youtube tutorial by (code with mosh) his images loaded properly but my images wont other things like add to cart button and name of product loaded properly. i ghave added on one url i.e
( https://upload.wikimedia.org/wikipedia/commons/7/7b/Orange-Whole-%26-Split.jpg )
admin.py
from django.contrib import admin
from .models import Product, Offer
class OfferAdmin(admin.ModelAdmin):
list_display = ('code', 'discount')
class ProductAdmin(admin.ModelAdmin):
list_display = ('name', 'price', 'stock')
admin.site.register(Product, ProductAdmin)
admin.site.register(Offer, OfferAdmin)
apps.py
from django.apps import AppConfig
class ProductsConfig(AppConfig):
name = 'products'
models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.FloatField()
stock = models.IntegerField()
image_url = models.CharField(max_length=2083)
class Offer(models.Model):
code = models.CharField(max_length=10)
description = models.CharField(max_length=255)
discount = models.FloatField()
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('new', views.new)
]
views.py
from django.http import HttpResponse
from django.shortcuts import render
from .models import Product
def index(request):
products = Product.objects.all()
return render(request, 'index.html',
{'products': products})
def new(request):
return HttpResponse('New products')
index.py
{% extends 'base.html' %}
{% block content %}
<h1>Products</h1>
<div class="row">
{% for product in products %}
<div class="col">
<div class="card" style="width: 18rem;">
<img src="{{ image_url }}" alt="...">
<div class="card-body">
<h5 class="card-title">{{ product.name }}</h5>
<p class="card-text">{{ product.price }}₹</p>
Add to cart
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
my first django project and the images_url dosent load anything every thing works perfectly but but the images wont load.
Change
<img src="{{ image_url }}" alt="...">
To
<img src="{{ product.image_url }}" alt="...">

how to make a list of posts titles in django

I am creating a blog web app with django where i want to make a list which contains only titles of the posts.
i wanna make two lists namely
Latest posts
All posts
In Latest posts , i wanna list out titles of the posts created recently.Means post created at last should be in first place of the list. simple
In All Posts , i want to list out titles of all posts in ascending order.
i am not sure how to do it.
Here is my code goes.....
views.py
from django.shortcuts import render , redirect
from django.views.generic import TemplateView , ListView , DetailView
from .models import home_blog_model
from .forms import create_post
class home_view(ListView):
model = home_blog_model
template_name = "home.html"
context_object_name = "posts"
def detail_view(request , pk):
obj = home_blog_model.objects.get(id=pk)
context = {"obj":obj}
return render(request , "detail.html" , context)
def create_post_view(request):
if request.method == "POST":
form = create_post(request.POST)
if form.is_valid():
form.save()
return redirect("/home/")
else:
form = create_post()
return render(request , "create_post.html" , {"form":form})
home.html
{% extends "base.html" %}
{% load static %}
{% block body %}
<img src="{% static 'hori.jpg' %}" style="margin-top: 50px;margin-left: 250px;width: 60%">
<div class="row" style="margin-top: 40px;margin-left: 320px;margin-right: 20px">
{% for post in posts %}
<div class="col-sm-6 mb-4">
<div class="container" style="width: 300px;box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);transition: 0.3s;width: 100%;padding: 0px;">
<div class="card" style="height: 200px;padding: 12px;" onclick="location.href='{% url 'detail' post.id %}'">
<h2>{{ post.title }}</h2>
<div class="card-body">{{ post.summary }}</div>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
{% block head %}
<style>
.card:hover { box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);}
</style>
{% endblock %}
models.py
from django.db import models
class home_blog_model(models.Model):
title = models.CharField(max_length=100)
summary = models.CharField(max_length=300)
content = models.TextField()
date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
urls.py
from django.urls import path
from . import views
from django.contrib.auth.views import LoginView , LogoutView
urlpatterns = [
path("" , views.home_view.as_view() , name="blog-home"),
path("posts/<int:pk>/" , views.detail_view , name="detail"),
path("admin/login/" , LoginView.as_view(template_name="admin-login.html") , name="admin-login"),
path("admin/logout/" , LogoutView.as_view() , name="admin-logout"),
path("admin/post/create/" , views.create_post_view , name="create_post"),
]
thanks in advance.
You can use dictsortreversed for latest posts. For example:
# top 5 posts
{% for post in posts|dictsortreversed:"id"|slice:"5" %}
{{ post.title }}
{% endfor %}
In this way you can have posts in ascending order (like the implementation of your code) and reversed order in same template without adding anything in view. slice was added for slicing the list for 5 objects.

Django dropdown filter with ajax?

I need to update my template when the user chooses a value of the dropdown list. Is there a possibility to do this with an ajax call or similiar? It would be perfect that if the user is selecting a value of the dropdown, this value would be send to my view and the content in my page would update without page refresh.
I tried different things but nothing worked... Any suggestion is welcome.
Here's my shortened code:
models.py
class Author(models.Model):
id = models.IntegerField(primary_key=True)
author = models.CharField(max_length=50)
status = models.CharField(max_length=50)
[...]
views.py
def authors(request):
authors = Author.objects.all()
if request.method="GET":
authors = Author.objects.filter(status = filter)
template
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Choose status
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#">Staff</a>
<a class="dropdown-item" href="#">Admin</a>
[...]
</div>
</div>
{% for author in authors %}
{{author.author}}
{% endfor %}
template
<a class="dropdown-item" href="{% url 'admin' %}">Staff</a>
<a class="dropdown-item" href="{% url 'staff' %}">Admin</a>
urls.py
url(r'^admin/', authors_admin, name='admin'),
url(r'^staff/', authors_staff, name='staff'),
views.py
def authors_admin(request):
authors = Author.objects.all()
if request.method="GET":
authors = Author.objects.filter(status = 'admin')
return render(request, 'template.html', {
'authors ': authors
})
def authors_staff(request):
authors = Author.objects.all()
if request.method="GET":
authors = Author.objects.filter(status = 'staff')
return render(request, 'template.html', {
'authors ': authors
})

ImproperlyConfigured at /app/category/Python/

I wanna make a page which shows POST's models' contents is shown each category.For example, when I put Python link in in detail.html,only POST's models' contents with Python's category is shown in category.html.When I put Python link in category.html,I got an error,ImproperlyConfigured at /app/category/Python/ CategoryView is missing a QuerySet. Define CategoryView.model, CategoryView.queryset, or override CategoryView.get_queryset(). I wrote codes in views.py
def top(request):
content = POST.objects.order_by('-created_at')[:5]
category_content = Category.objects.order_by('-created_at')[:5]
page = _get_page(blog_content, request.GET.get('page'))
return render(request, 'top.html',{'content':content,'category_content':category_content,"page":page})
class CategoryView(BaseListView):
template_name = 'category.html'
def get_queryset(self):
category_name = self.kwargs['category']
self.category = Category.objects.get(name=category_name)
queryset = super().get_queryset().filter(category=self.category)
return queryset
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['category'] = self.category
return context
in urls.py
urlpatterns = [
path('top/', views.top, name='top'),
path('category/<str:category>/',views.CategoryView.as_view(), name='category'),
]
in models.py
class Category(models.Model):
name = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class POST(models.Model):
title = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
def __str__(self):
return self.title
in top.html
<div class="list-group">
<a href="#">
Category
</a>
<div>
{% for category in category_content %}
<a href="{% url 'category' category.name %}">
{{ category.name }}
</a>
{% endfor %}
</div>
</div>
in category.html
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Category</title>
</head>
<body>
<div>
{% for content in queryset %}
<h2>{{ content.title }}</h2>
<img src="content.image.url" />
<a class="btn btn-outline-primary btn-lg btn-block" href="{% url 'detail' content.pk %}">SHOW DETAIL</a>
{% endfor %}
</div>
<div>
<a href="#" class="list-group-item active">
Category
</a>
<div>
{% for category in category_content %}
<a class="list-group-item justify-content-between" href="{% url 'category' category.name %}">
{{ category.name }}
</a>
{% endfor %}
</div>
</div>
</body>
</html>
I really cannot understand why ImproperlyConfigured which means settings.py is wrong.When I changed BaseListView into ListView,same error happens.I wrote get_queryset in CategoryView's class so I cannot understand codes needs QuerySet. How should I fix this?What is wrong in my codes?
One issue is that you're calling super().get_queryset(), which expects your class to define a queryset or a model. Adding model = Category will fix that error.
It looks like you're returning a queryset with just one entry, though. If you only want to get the one category, it would be simpler to use a DetailView:
from django.views.generic import DetailView
from .models import Category # or wherever it is
class CategoryView(DetailView):
model = Category
template_name = 'category.html'
def get_object(self):
category_name = self.kwargs['category']
return Category.objects.get(name=category_name)
Note that your template would need to be updated to reference category or object instead of looping through the queryset.

problems with an edit form/view

I work with Django 1.9. I created a view to add a new object and it works, but when to create a view to edit the objects, I have two different problems:
when I want to edit an album I click the link to the page where I want to see the entire list of albums for editing, but I get the error Exception Type: NameError and Exception Value: name 'album' is not defined that relates -> views.py in mod_artist form = AlbumForm(instance=album)
instead, when I want to edit an artist, I do the same thing as before to see the whole list of artists to be able to edit, but I get the error Exception Type:
UnboundLocalError and Exception Value: local variable 'artist' referenced before assignment that relates -> views.py in mod_artist form = ArtistForm(instance=artist)
my views.py file is
from django.shortcuts import render, redirect, get_object_or_404
from .forms import *
from .models import *
def mod_album(request):
if request.method == "POST":
form = AlbumForm(request.POST, instance=album)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('http://127.0.0.1:8000/')
else:
form = AlbumForm(instance=album)
return render(request,'polls/mod_album.html',{'form':form})
def mod_artist(request):
if request.method == 'POST':
form = ArtistForm(request.POST, instance=artist)
if form.is_valid():
artist = form.save(commit=False)
artist.author = request.user
artist.save()
return redirect('http://127.0.0.1:8000/')
else:
form = ArtistForm(instance=artist)
return render(request,'polls/mod_artist.html',{'form':form})
my index.html file is
...
<body>
<div class="container-fluid">
<div class="header">
<div>
<h1>personal library</h1>
</div>
<div id="wrap-nav">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active">+ add album</li>
<li class="active">- edit album</li>
<li class="active">+ add artist</li>
<li class="active">- edit artist</li>
<li class="active">view the list of albums</li>
</ul>
</div>
</div>
</nav>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6">
{% for album in albums %}
<ul>
<li>Album name: {{album.name}}</li>
<li>Artist: {{album.artist}}</li>
<li>Genre: {{album.genre}}</li>
<li>Songs: , </li>
<li>Vote: {{album.vote}}</li>
</ul>
<hr />
{% endfor %}
</div>
<div class="col-xs-6 col-md-6">
{% for artist in artists %}
<ul>
<li>Artist name: {{artist.name}}</li>
</ul>
<hr />
{% endfor %}
</div>
</div>
</div>
</body>
...
my urls.py file is
from django.conf.urls import url
from . import views
urlpatterns=[
...
url(r'^new_album/$', views.new_album, name='new_album'),
url(r'^mod_album/$', views.mod_album, name='mod_album'),
url(r'^new_artist/$', views.new_artist, name='new_artist'),
url(r'^mod_artist/$', views.mod_artist, name='mod_artist'),
]
and my forms.py file is
from django import forms
from .models import *
class AlbumForm(forms.ModelForm):
class Meta:
model = Album
fields = ['name','artist','year','genre','vote']
class ArtistForm(forms.ModelForm):
class Meta:
model = Artist
fields = ['name']
thanks in advance of our time.

Categories