I have a model where users save their details. I am able to save user details through the template I have created. But whenever I edit the data to update it, a new entry is created in database
models.py
class User(AbstractUser):
pass
def __str__(self):
return self.username
class Detail(models.Model):
"""
This is the one for model.py
"""
username = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default="")
matricno = models.CharField(max_length=9, default="")
email = models.EmailField(default="")
first_name = models.CharField(max_length=200, default="")
last_name = models.CharField(max_length=255, default="")
class Meta:
verbose_name_plural = "Detail"
def __str__(self):
return self.first_name+ " "+self.last_name
views.py
#login_required(login_url="signin")
def details(request):
form = Details()
if request.method == "POST":
form = Details(request.POST)
if form.is_valid():
detail = form.save(commit=False)
detail.username = request.user
detail.save()
return redirect(success, pk=detail.pk)
else:
form = Details(initial={"matricno":request.user.username})
return render(request, "details.html", {"form":form})
def success(request,pk):
return render(request, "success.html", {"pk":pk})
def updatedetails(request, pk):
detail = Detail.objects.get(id=pk)
form = Details(instance=detail)
if request.method == "POST":
form = Details(request.POST, instance=detail)
if form.is_valid():
form.save()
return redirect(success, pk=detail.pk)
return render(request, "details.html", {"form":form})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("details/", views.details, name="details"),
path("success/<int:pk>/", views.success, name="success"),
path("edit/<int:pk>/", views.updatedetails, name="updatedetails"),
]
The template used for rendering out the form to input user details goes as follows
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>details</title>
</head>
<body>
<form action="/details/" method="POST">
{% csrf_token %}
{% if request.user.is_authenticated %}
<p>
{{form.matricno}}
</p>
<p>
{{form.email}}
</p>
<p>
{{form.first_name}}
</p>
<p>
{{form.last_name}}
</p>
<p>
<input type="submit" value="Create">
</p>
{% endif %}
<div>
<input type="button" value="SignOut">
</div>
</form>
</body>
</html>
After a user enters their details and it is saved to database successfully, it redirect to a success where their is a link that takes you back to the other page to edit the data you inputed and it goes as follows.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Success</title>
</head>
<body>
<h1>Thank You for Filling Out the Form</h1>
<p>Click Here To Edit</p>
</body>
</html>
My problem now is that whenever i click on the link to edit, and i edit the details i have entered, it creates a new entry in database rather than updating previous data.
You need to POST to the edit view, so:
<form action="{% url 'updatedetails' pk=form.instance.pk %}" method="POST">
...
</form>
You should thus make two templates: one to create data, and one to edit data.
Related
I'm working with django ckeditor now and I can't display content that can be saved normally and is displayed in the admin panel. Content is always displayed as textarea
As you can see at the image, editor is working properly, also if i go to admin panel everything is OK, but if i want to display content of "body" ({{ form.body|safe}}), it will display only textarea of HTML code.
models.py
class Stage(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
game_id = models.ForeignKey(Game,
on_delete=models.CASCADE)
name = models.CharField(max_length=128)
sequence = models.IntegerField(null=False)
body = RichTextUploadingField(config_name='LeftFields', blank=True, null=True)
def get_questions(self):
return Question.objects.filter(stage_id = self.id)
def __str__(self):
return str(self.name)
forms.py
class StageForm(ModelForm):
class Meta:
model = Stage
fields = ['body','name']
widgets = {
'name': TextInput(attrs={
'class': "left_input",
'style': "width: 69.3%;",
}),
}
views.py
#login_required(login_url='/signin')
#user_passes_test(lambda u: u.is_staff)
def edit(request, gameid,id):
stage = Stage.objects.get(pk=id)
if request.method == 'POST':
form = StageForm(request.POST, instance=stage)
if form.is_valid():
form.save()
return redirect('/edit/' + gameid + '/' + id)
form = StageForm(instance=stage)
return render(request, "homeSuperuser/edit_stage.html", {'stage': stage, 'form': form,'gameid':gameid})
edit_stage.html
<!doctype html>
<html>
<head> {% load static %}
<link rel="stylesheet" href="{% static 'css/edit_pages.css' %}" />
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script type="text/javascript" src="{% static 'js/edit.js' %}"></script>
</head>
<body>
<div class="row" id="mainDIV">
<form id="main" method="post" action="{{ request.path }}">
{% csrf_token %}
<div class="divs">
<a>Název: </a>
{{ form.name}}
</div>
<div class="divs"><a>Kontent:</a>
{{ form.media }}
{{ form.body}}
</div>
<div class="div_cent"><input type="submit" value="Uložit" class="subm" /></div>
</form>
</div>
{{ form.body|safe}}
</body>
</html>
form.body is the field itself, so includes the HTML textarea markup.
Instead of
{{ form.body|safe}}
try
{{ form.body.value|safe}}
By entering the phone number in the customer registration form , if the customer already exists then should fill the rest of the fields by fetching it from the backend. if the user does not exists then have to register. help me with the script used for this
this is the model i have.
class Customers(models.Model):
customer_id = models.AutoField(primary_key=True)
cname = models.CharField(max_length=100)
cnumber= models.IntegerField()
caddress= models.CharField(max_length=100)
I m using the modelform here.
class CustForm(forms.ModelForm):
class Meta:
model=Customers
fields = '__all__
this is my view
def customer(request):
form=CustForm()
if request.method=='POST':
form = CustForm(request.POST)
form
if form.is_valid():
form.save(commit=True)
messages.success(request,'successfully customer added')
return render(request,'hello.html')
else:
messages.error(request,'Invalid')
return render(request,'custdata.html',{'form':form})
This is my html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{% block content %}
<div>
<center><h2><b>Add Customer</b></h2></center>
<p><form method='post'>
{% csrf_token %}
<center>
{{form.as_p}}
<button type="submit" style="width:200px; height:30px; font-size: 20px;">ADD</button>
</center>
</form>
</div>
{% endblock %}
</body>
</html>```
I am an absolute beginner in Django development & I am unable to send the data to my database via the POST method. Please guide me on what is wrong with my approach. My model worked perfectly and I can now access my desired table on my Django admin. The function that I have created in views.py always executes the else condition.
From views.py:
from django.shortcuts import render, HttpResponse, redirect
from app.models import Tbl_Feedback
def myform(request):
return render(request, 'form.html')
def getfeedback(request):
if request == "POST":
a = request.POST.get('a')
objTbl_Feedback = Tbl_Feedback(a="a")
objTbl_Feedback.save()
return redirect("/")
else:
return HttpResponse('Form Not Submitted')
From models.py:
from django.db import models
# Create your models here.
class Tbl_Feedback(models.Model):
fdbk = models.CharField(max_length=120)
From urls.py(app):
from django.contrib import admin
from django.urls import path
from app import views
urlpatterns = [
path('',views.myform,name="form"),
path('getfeedback', views.getfeedback, name="feedback")
]
From urls.py(project):
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("app.urls"))
]
Html:
<!DOCTYPE html>
<html lang="en">
{% load static %}
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form</title>
{% load static %}
<link rel="stylesheet" href="{%static 'css.css'%}">
</head>
<body>
<form action="getfeedback" method="post" >
{% csrf_token %}
<div class="frame">
<div class="frame-header">FeedBack Please !</div>
<div class="frame-body">
<div class="form-element">
<div class="element-label"><label for="a">FeedBack</label></div>
<div class="element-controller">
<textarea name="a" id="a" cols="30" rows="5" class="controller-input"
autofocus="autofocus" maxlength="120"></textarea>
</div>
</div>
</div>
<div class="frame-footer"><button type="submit">Submit</button> </div>
</div>
</form>
</body>
</html>
In your getfeedback view there are two issues.
You need to write if request.method == 'POST':
"a" is not a field in your model
def getfeedback(request):
if request.method == "POST":
a = request.POST.get('a')
objTbl_Feedback = Tbl_Feedback(fdbk="a")
objTbl_Feedback.save()
return redirect("/")
else:
return HttpResponse('Form Not Submitted')
Colleagues, good afternoon!
There is a model book and a model chapter. Each book has many chapters. Each chapter is tied to a specific book, and if the slug of the chapter is made unique, then when book1 - chapter1, I cannot create book2 - chapter 2, an error is generated. If you make the slug non-unique, then an error is issued that one argument was expected, but 2 was passed.
How can I solve this problem? I want the slug to be a number and django understands that along the path / book1 / 1 / you need to take a slug with number 1, which is tied to book1 specifically, and not to pay attention to the slug with number 1, but tied to book2.
if the slug is unique, then I calmly end up in the right book and the right chapter, but everything collapses when I need to get there as intended.
The path is built like this: / book1 / 1 (chapter) / etc.
book2 / 1 / etc
class Book(models.Model):
some code
class Chapter(models.Model):
book= models.ForeignKey(Book, verbose_name="title", on_delete=models.CASCADE)
number = models.PositiveIntegerField(verbose_name="num chapter")
slug = models.SlugField(unique=True, verbose_name="slug_to", null=True, blank=True)
def save(self, *args, **kwargs):
self.slug = self.number
super().save(*args, **kwargs)
Views.py
class Base(View):
def get(self, request, *args, **kwargs):
book = Book.objects.all()
return render(request, "base.html", context={"book": book})
class BookDetail(DetailView):
model = Book
context_object_name = "book"
template_name = "book_detail.html"
slug_url_kwarg = "slug"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["chapter"] = Chapter.objects.filter(title=self.object)
return context
class ChapterRead(DetailView):
model = Chapter
context_object_name = "chapter"
template_name = "chapter_read.html"
slug_url_kwarg = "int"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["imgs"] = ImgChapter.objects.filter(chapter=self.object)
return context
urls.py
from django.contrib import admin
from django.urls import path
from .views import *
urlpatterns = [
path("", Base.as_view(),name="book_list"),
path("<str:slug>/", BookDetail.as_view(), name="book_detail"),
path("<str:slug>/<str:int>/", ChapterRead.as_view(), name="chapter_detail")
]
html
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>tf</title>
</head>
<body>
{% for i in book%}
{{i.name}}
{% endfor %}
</body>
</html>
book_detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ book.name }}
{% for i in chapter %}
{{ i.number }}
{% endfor %}
</body>
</html>
chapter_read.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ chapter.number }}
{% for i in imgs %}
<img src="{{ i.img.url }}">
{% endfor %}
</body>
</html>
I am creating a blog with system of comments and tags. Now I faced to a template problem with Model instances. First I put status to all new Posts as "draft" but now I set a the status to 'published' and I got this error message. If you need more code olease tell me.
I tried to watch the behavior of my code when I was adding new elemets to the my code.
models.py
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,
self).get_queryset()\
.filter(status='published')
class Post(models.Model):
STATUS_CHOICE = (
('draft', 'Draft'),
('published', 'Published')
)
title = models.CharField(max_length=250)
slug = models.CharField(max_length=250,
unique_for_date='publish')
author = models.ForeignKey(User,
on_delete=models.CASCADE,
related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now())
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,
choices=STATUS_CHOICE,
default='published')
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
objects = models.Manager()
published = PublishedManager()
tags = TaggableManager()
def get_absolute_url(self):
return reverse('blog_site:post_detail',
args=[self.publish.year,
self.publish.month,
self.publish.day,
self.slug])
views.py
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
# List of active comment fot this post
comments = post.comments.filter(active=True)
new_comment = None
if request.method == 'POST':
# A comment was posted
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object bot don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the new comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
return render(request,
'blog_site/post/detail.html',
{'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form})
Template error:
In template Z:\Django\blog\blog_site\templates\blog_site\base.html, error
at line 0
Manager isn't accessible via Post instances
1 : {% load static %}
2 : <html lang="en">
3 : <head>
4 : <meta charset="UTF-8">
5 : <meta name="viewport" content="width=device-width, initial-
scale=1">
6 : <title>{% block title %}{% endblock %}</title>
7 : <link href="{% static "css/blog_site.css" %}" rel="stylesheet">
8 : </head>
base.html
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}{% endblock %}</title>
<link href="{% static "css/blog_site.css" %}" rel="stylesheet">
</head>
<body>
<div id="pattern"></div>
<div id="header">
<div class="menu" id="logo"><b>#blog</b></div>
<div class="menu" id="nav_bar">
Recently
Best of Month
<a>People</a>
</div>
<div class="menu" id="profile">Profile of user</div>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>