I need help in django - python

I want to print First semester's Subjects in First Semester & Second semester's Subjects in Second Semester and so on. See this pic
cick in image here
Maybe there is some logic in views.py that Im not having on my mind rn.Can someone help me in this logic and how to render it in semester.html page
My code is here.
models.py
from django.db import models
from django.db.models.base import ModelState
# Create your models here.
class Course(models.Model):
faculty = models.CharField(max_length=100)
class Semester(models.Model):
sem = models.CharField(max_length=100)
faculty = models.ForeignKey(Course, on_delete=models.CASCADE)
def __str__(self):
return F"Semester {self.sem} at Faculty {self.faculty}"
class Subject(models.Model):
faculty = models.ForeignKey(Course, on_delete=models.CASCADE)
sem = models.ForeignKey(Semester, on_delete=models.CASCADE)
subject_name = models.CharField(max_length=100)
def __str__(self):
return str(self.id)
views.py
from django.shortcuts import render
from django.views import View
from django.contrib import messages
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField
from django import forms
from django.utils.translation import gettext, gettext_lazy as _
from .forms import CustomerRegistrationForm
from .models import Course, Semester, Subject
# Create your views here.
def home(request):
return render(request, 'app/home.html')
def faculty(request):
course = Course.objects.all()
return render(request, 'app/faculty.html', {'course':course})
class SemesterView(View):
def get(self, request,id):
obj = Course.objects.get(id=id)
print(obj)
semobj = Semester.objects.filter(faculty=obj)
print(semobj)
subobj = Subject.objects.filter(faculty=obj)
print(subobj)
return render(request, 'app/semester.html', {'obj':obj, 'semobj':semobj, 'subobj':subobj})
semester.html
{% extends 'app/base.html' %}
{% load static %}
{% block semester %}
<div class="bsc-csit">
<div class="container">
<div class="row" style="margin-top:90px; padding-top:20px;">
{% for so in semobj %}
<div class="col-md-3">
<div class="bsccsit-box">
<h3 style="color: black">{{so.sem}}</h3>
<ul>
{% for suo in subobj %}
<li>1.{{suo.subject_name}}</li>
{% endfor %}
</ul>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
{% endblock semester %}

Try replacing the following in your template:
{% for subject in so.subject_set.all %}
<li>{{ forloop.counter }}. {{subject.subject_name}}</li>
{% endfor %}
You can get all Subject's from a specific semester via subject_set.all.
You can also use {{ forloop.counter }} to provide a enumerative number with the associated subject.

Related

Slug URL turns into a number when navigating to the next link in django

I tried searching for this problem here but I didn't find anything, I hope someone can help answering or sending a link to a solution on stackoverflow...
I have been creating a blog, and when I click on the post title, it goes to 'post_details.html' and in the URL shows a slug with the post title. Like here:
examplename.com/blog/brooklyn-nets-at-miami-heat-preview/
But when I click to write a comment on the post it takes me to a form page, but the slug title disappear, it just shows the post number. Like this:
examplename.com/blog/3/add-comment
Can someone explain why is this happening? I want to know how to solve this and understand from where it comes this number that shows up.
Post_detail.html
{% block content %}
<h2 class="title">
<a class="post-title" href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="date">
Publicado em {{ post.created }} por {{ post.author }}
</p>
{{ post.body|linebreaks }}
<hr>
<h3>Comments</h3>
{% if not post.comments.all %}
Nobody commented yet...Add a comment
{% else %}
Add a comment
{% for comment in post.comments.all %}
{{ comment.name }}
{{ comment.date }}
<br>
{{ comment.body }}
{% endfor %}
{% endif %}
<a class="swen" href="{% url 'blog:list' %}">More Articles</a>
{% endblock %}
urls.py
from unicodedata import name
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path("", views.PostListView.as_view(), name="list"),
path("<slug:slug>/", views.PostDetailView.as_view(), name="detail"),
path("<slug:slug>/add-comment", views.CommentView.as_view(), name="commentview")
]
models.py
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse ('blog:detail', kwargs={"slug":self.slug})
class Meta:
ordering = ("-created",)
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
name = models.CharField(max_length=255)
body = models.TextField()
date = models.DateField(auto_now_add=True)
slug = Post.slug
def __str__(self):
return reverse (self.post.title, self.name, self.post.slug)
views.py
from xml.etree.ElementTree import Comment
from django.views.generic import DetailView, ListView, CreateView
from .models import Post, Comment
class PostListView(ListView):
model = Post
class PostDetailView(DetailView):
model = Post
class CommentView(CreateView):
model = Comment
template_name = 'add_comment.html'
fields = '__all__'
you're passing pk which is a type integer as parameter instead of a slug at path name commentview. May be you should check on that.

Not redirecting from createView form to Home

I am learning fresh django development. Working on a blog project I am facing a issue that, while publishing a new blog, that doesn't redirects to home/blogs page. I tried to manually to go home It says,
OperationalError at /blog/
no such column: App_Blog_blog.author_id
I tried to debug several times, searched in documentation can't get away with this author_id. These are my codes:
Views.py
class CreateBlog(LoginRequiredMixin, CreateView):
model = Blog
template_name = 'App_Blog/create_blog.html'
fields = ('blog_title', 'blog_content', 'blog_image',)
def form_valid(self, form):
blog_obj = form.save(commit=False)
blog_obj.author = self.request.user
title = blog_obj.blog_title
blog_obj.slug = title.replace(" ", "-") + "-" + str(uuid.uuid4())
blog_obj.save()
return HttpResponseRedirect(reverse('index'))
class BlogList(ListView):
context_object_name = 'blogs'
model = Blog
template_name = 'App_Blog/blog_list.html'
Views.py of main project file
def index(request):
return HttpResponseRedirect(reverse('App_Blog:blog_list'))
urls.py
from django.urls import path
from App_Blog import views
app_name = 'App_Blog'
urlpatterns = [
path('', views.BlogList.as_view(), name='blog_list'),
path('write/', views.CreateBlog.as_view(), name='create_blog'),
]
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Blog(models.Model):
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='post_author')
blog_title = models.CharField(max_length=264, verbose_name="Put a Title")
slug = models.SlugField(max_length=264, unique=True)
blog_content = models.TextField(verbose_name="What is on your mind?")
blog_image = models.ImageField(
upload_to='blog_images', verbose_name="Image")
publish_date = models.DateTimeField(auto_now_add=True)
update_date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.blog_title
create_blog.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title_block %}
Write a Blog
{% endblock title_block %}
{% block body_block %}
<h2>Start Writing:</h2>
<form method="POST">
{{ form | crispy }}
{% csrf_token %}
<br>
<button type="button" class="btn btn-success btn-sm">Publish</button>
</form>
{% endblock body_block %}
blog_list.html
{% extends 'base.html' %}
{% block title_block %} Home {% endblock %}
{% block body_block %}
{% for blog in blogs %}
<h3>{{blog.blog_title}}</h3>
<h6>{{blog.publish_date}}</h6>
{% endfor %}
{% endblock %}
Create Blog form:
Error showing on site:

if statement in Django template not working

I can't find out why this is not working.
It always goes to {% else %} block.
The text in machine_model is something like "Lidl - Food Market" or "Kaufland - Buy Here" or something other without those two words.
models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django import forms
from django.urls import reverse
class MyName(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
class MyModel(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
class MySide(models.Model):
name = models.CharField(max_length=50, unique=True)
class MyMachine(models.Model):
date_delivery = models.DateTimeField(null=True)
machine_name = models.ForeignKey(MyName, on_delete=models.PROTECT)
machine_model = models.ForeignKey(MyModel, on_delete=models.PROTECT)
machine_serial = models.CharField(max_length=15, default='0')
use_side = models.ForeignKey(MySide, on_delete=models.PROTECT)
views.py
from django.views.generic import ListView
from .models import MyMachine
class MyMachineListView(ListView):
model = MyMachine
template_name = 'site/home.html'
context_object_name = 'machines'
ordering = ['date_delivery']
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
site_title = 'Home'
context["site_title"] = site_title
return context
home.html
{% extends "site/base.html" %}
{% load static %}
{% block content %}
{% for machine in machines %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<small class="text-muted">{{ machine.date_delivery|date:"d.F Y" }}
</small>
</div>
<h2><a class="article-title" href="">{{ machine.machine_name }} - {{ machine.machine_serial }}</a></h2>
{% if 'Lidl' in machines.machine_model %}
<p class="article-content">{{ machine.use_side }} - Lidl</p>
{% elif 'Kaufland' in machines.machine_model %}
<p class="article-content">{{ machine.use_side }} - Kaufland</p>
{% else %}
<p class="article-content">{{ machine.use_side }} - {{ machine.machine_model}}</p>
{% endif %}
</div>
</article>
{% endfor %}
{% endblock content %}
everything else is working fine. Thank You in advance!
I see two problems here.
One, you're referencing machines.machine_model, but machines is a queryset. I'm somewhat surprised referencing machine_model on it doesn't just fail with a rendering error. It should be machine.machine_model, since that's your loop variable.
That leads us to the second problem. machine.machine_model is a foreign key reference to another model, not a string. There's no string that's in a model instance (barring defining the membership function yourself). I haven't personally tested but I don't think Django stringifies on the fly (as it will when you reference {{ machine.machine_model }}). Try it with if ... in machine.machine_model.name.

How can I get data from a form model into a database in Django

I am trying to get data from a model form and then put it into a database. I have figured out how to make the form, but when clicking the submit button it doesn't seem to be put anywhere in my database. Am I doing anything wrong or am I not looking in the correct place in the database.
forms.py
from django import forms
from sxsw.models import Account
class AccountForm(forms.ModelForm):
class Meta:
model = Account
fields = ['firstName', 'lastName', 'email']
views.py
from django.shortcuts import render
from django.shortcuts import redirect
from .forms import AccountForm
from .models import Account
def sxsw(request):
if request.method == 'POST':
form = AccountForm(request.POST)
if form.is_valid():
form.save()
else:
print form.errors
else:
form = AccountForm()
return render(request, 'sxsw/sxsw.html', {'form': form})
def formSubmitted(request):
return render(request, 'sxsw/formSubmitted.html',{})
models.py
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Account(models.Model):
firstName = models.CharField(max_length = 50)
lastName = models.CharField(max_length = 50)
email = models.EmailField()
def __unicode__(self):
return self.firstName
class Module(models.Model):
author = models.ForeignKey(Account, on_delete = models.CASCADE)
nameOfModule = models.CharField(max_length = 150) #arbitrary number
moduleFile = models.FileField(upload_to = 'uploads/')#Not exactly sure about the upload_to thing
public = models.BooleanField()
def __unicode__(self):
return self.nameOfModule
sxsw.html
{% extends "base.html" %}
{% block content %}
<div class="container-fluid">
<div class="jumbotron text-center">
<h3>SXSW Form</h3>
</div>
</div>
<div align="center">
<h1>New Form</h1>
<form role='form' action="/sxsw/formSubmitted/" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
</div>
</div>
{% endblock %}
formSubmitted.html
{% extends "base.html" %}
{% block content %}
<div class="container-fluid">
<div class="jumbotron text-center">
<h3>Form Successfully submitted</h3>
</div>
</div>
<div align="center">
Submit Another Response
</div>
</div>
{% endblock %}
Your form is posting to what I presume is the wrong url
<form role='form' action="/sxsw/formSubmitted/" method="post">
should use the url for the sxsw view
<form role='form' action="/sxsw/" method="post">
Once submitted, you'll likely want to redirect to the submitted view
return redirect('/sxsw/formSubmitted/') # Preferably use the url pattern name here
It looks like your form's action is set to /sxsw/formSubmitted/ that always simply return the submitted page, instead of the url that will call the sxsw view where the form's save method is called.

Django blank page

This is my index.html file:
{% extends "base_site.html" %}
{% block content %}
{% if info %}
<ul>
{% for object in info %}
{{ Hello }}
{% endfor %}
</ul>
{% else %}
<p>No objects are available.</p>
{% endif %}
{% endblock %}
This is my views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader
from notendur.models import *
from django.views import generic
class IndexView(generic.ListView):
template_name = 'notendur/index.html'
context_object_name = "info"
def get_queryset(self):
"""Return the last five published polls."""
return Information.objects.all()
This is my models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Information(models.Model):
title = models.CharField(max_length = 200)
body = models.TextField()
date = models.DateTimeField()
def __unicode__(self):
return self.title
class InformationChild(models.Model):
information = models.ForeignKey(Information)
child_text = models.CharField(max_length = 200)
def __unicode__(self):
return self.child_text
When I start the server, however, nothing appears. This has to be some url-link issue, because the else clause doesn't even activate. Perhaps you want urls.py as well?
Let me know if you need further information.
The error is not in the use of info, it's in what's inside the for loop: {{ Hello }} is not an item in the context. Use {{ object.title }}, for example.

Categories

Resources