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>```
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}}
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.
I want to send an 8-digit authentication number by e-mail.
No matter how hard I try, I don't know what I'm doing wrong.
First, I set the smtp. Then, I filled out the form. After creating the view, I created a template.
After entering e-mail and username, I pressed the Send button.
WHAT? id:
email:
[29/Mar/2022 09:43:39] "GET /recovery/pw/?email=wlgns000%40gmail.com&username=wlgns HTTP/1.1" 200 2030
However, only these logs appear, and the authentication number does not come by e-mail.
How can I send an authentication number by e-mail?
#settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.naver.com'
EMAIL_PORT = 465
EMAIL_HOST_USER = #email
EMAIL_HOST_PASSWORD = #password
EMAIL_USE_TLS = True
DEFAULT_FROM_MAIL = EMAIL_HOST_USER
{% load static %}
<!DOCTYPE html>
<html lang="KO">
<head>
....
<link href="{% static 'users/css/recovery_pw.css' %}" rel="stylesheet">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="{% static 'users/js/recovery_pw.js' %}"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<script>
$.ajaxSetup({
headers: { "X-CSRFToken": '{{csrf_token}}' }
});
</script>
</head>
<body>
{% block content %}
<form method="get" enctype="multipart/form-data">
{% csrf_token %}
<div class="container">
<div class="inner-box">
...
<div class="input-box">
<div class="id">
<input type="email" placeholder="등록하신 메일로 인증번호가 발송됩니다." name="email" maxlenth="20" autocomplete="off" value="{{ form.email.value|default_if_none:'' }}" required />
</div>
<div class="password">
<input type="username" placeholder="아이디를 입력하세요" name="username" maxlength="20" value="{{ form.username.value|default_if_none:'' }}" required />
</div>
</div>
<div class="btn">
<div class="btn-white" id="btn_white"><button type="submit">send mail</button></div>
</div>
...
</form>
{% endblock %}
</body>
</html>
# views.py
class RecoveryPwView(View):
template_name = 'users/recovery_pw.html'
recovery_pw = RecoveryPwForm
def get(self, request):
if request.method=='GET':
print("here?")
form = self.recovery_pw(None)
return render(request, self.template_name, { 'form':form, })
#csrf_exempt
def ajax_find_pw_view(request):
username = request.POST.get('username')
email = request.POST.get('email')
target_user = User.objects.get(username=username, email=email)
if target_user:
auth_num = email_auth_num()
print(auth_num, "1111")
target_user.auth = auth_num
print(target_user.auth, "2222")
target_user.save()
send_mail(
'email',
['#email'],
html=render_to_string('users/recovery_email.html', {
'auth_num': auth_num,
}),
)
print(send_mail, "3333")
return HttpResponse(json.dumps({"result": target_user.username}, cls=DjangoJSONEncoder), content_type = "application/json")
#forms.py
class RecoveryPwForm(forms.Form):
username = forms.CharField(label='id')
email = forms.EmailField(label='email')
class Meta:
fields = ['username', 'email']
and last email.html
It is an HTML containing the authentication number sent by e-mail.
{% autoescape off %}
<!DOCTYPE html>
<html lang="ko">
<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>Document</title>
<link href="{% static 'users/css/recovery_email.css' %}" rel="stylesheet">
<link href="{% static 'users/css/default.css' %}" rel="stylesheet">
<script>
$.ajaxSetup({
headers: { "X-CSRFToken": '{{csrf_token}}' }
});
</script>
</head>
<body>
...
<div class="auth"><p class="auth-p">{{ auth_num }}</p></div>
...
</body>
</html>
{% endautoescape %}
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>
I am trying to display data from mysql database. I have already uploaded data to database using django admin:
enter image description here
This is my models.py:
from django.db import models
# Create your models here.
class Newsform(models.Model):
headline = models.CharField(max_length=50)
description = models.CharField(max_length=100, default='')
content = models.CharField(max_length=100, default='')
image = models.ImageField(upload_to='news_image', blank=True)
views.py:
from django.shortcuts import render
from blog.models import Newsform
def first(request):
return render(request, 'blog/index.html')
def show_content_from_database(request):
headline_news=Newsform.objects.all()
context = {
'headline_news': headline_news
}
return render(request, 'blog/index.html', context)
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>{{ headline_news.headline }}</h1>
<img src="{{ headline_news.image }}">
</body>
</html>
I have blank page as a result. What's wrong?
headline_news is a queryset, ie a list of all the Newsform items in the database. The queryset itself doesn't have a headline or an image, only the individual items in it do. So you need to iterate through it:
<body>
{% for headline in headline_news %}
<h1>{{ headline.headline }}</h1>
<img src="{{ headline.image.url }}">
{% endfor %}
</body>
Note also, as I show above, you need to explicitly use the .url attribute on an ImageField to get the value for the src.
the attribut url search images uploaded inside media by default folder, and you can call it using {{ headline.image.url }}