My browser (chrome and firefox) doesn`t autofill my Datefield, but in safari working example
I inspected my html
HTML field have value
my view.py
def get(self, request, slug):
order = get_object_or_404(Order, order_number=slug)
form = DirectorForm(instance=order)
return render(request, 'edit_order.html', context={'form': form})
my forms.py
widgets = {'order_date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'})}
Well you don't need datefield widget for this you have to import datetime module in your models.py and use it to fill date or time
To be more specific here is my github link to a simple django project i did when i first started : https://github.com/AYUSHJD098/Django-Notes
and the site is : http://www.djangonotes.tk
you just need to add " date = models.DateField(auto_now_add=True, null=True) " in your models.py
like this
models.py
from django.db import models
from django.contrib.auth.models import User
class note(models.Model):
title = models.CharField(max_length=512, null=True)
note = models.TextField(null=True)
date = models.DateField(auto_now_add=True, null=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
The value will get added automatically when you save data to your database
here is a example:
home.html
{% if notes %}
{% for note1 in notes %}
<div class="container">
<div class="row justify-content-center">
<div class="col">
<div class="jumbotron">
<h1 class="display-4">{{note1.title}}</h1>
<p class="lead">{{ note1.date }}</p>
<hr class="my-4">
<p class="lead">{{ note1.note }}</p>
<a class="btn btn-outline-info" href="{% url 'view_note' pk=note1.id %}">Open</a>
</div>
</div>
</div>
</div>
forms.py
from django.forms import ModelForm, TextInput, Textarea
from .models import *
class noteForm(ModelForm):
class Meta:
model = note
fields = ('title', 'note')
widgets = {
'title': TextInput(attrs={'class': 'form-control', 'placeholder':'title'}),
'note': Textarea(attrs={'class': 'form-control', 'rows':'16','placeholder':'note'})
}
P.s sorry if i sound like a complete idoit i am very bad at explainging and i am kinda new to programming
Thanks,
ayush :)
Related
I am very new to web development and specifically using Django Framework.
I am trying to find a clean, efficient and non external package dependant implementation for an autocomplete-datalist form field inside a Generic class based CreateView template in Django.
I have found numerous resources on various implementations, but most of them depend on external packages(autocomplete-light, jqueryCDN, etc.) and none of it is based on a class based generic CreateView.
I have been experimenting and I have managed to make the autocomplete-datalist work in a way but I am stuck in a very simple problem when I try to post my form with the data from the datalist element.
I get a validation error:
"city_name: This field is required"
I also noticed that the city object queried from the database inside the datalist has also the id of the city_name
models.py
from django.db import models
class City(models.Model):
name = models.CharField(max_length=50)
class Meta:
verbose_name_plural = "cities"
ordering = ['name']
def __str__(self):
return self.name
class Person(models.Model):
first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length=40)
address = models.CharField(max_length=150)
city_name = models.ForeignKey(City, on_delete=models.CASCADE)
def __str__(self):
return f'{self.first_name} {self.last_name}'
views.py
from django.views.generic import ListView, CreateView
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Person, City
from .forms import PersonForm
# Create your views here.
class PersonList(LoginRequiredMixin, ListView):
model = Person
template_name = "home.html"
paginate_by = 20
login_url = "/login/"
redirect_field_name = 'redirect_to'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
class PersonCreate(LoginRequiredMixin, SuccessMessageMixin, CreateView):
model = Person
template_name = "testform.html"
login_url = "/login/"
form_class = PersonForm
success_url = 'testapp/add/'
success_message = 'Person registered successfully!'
redirect_field_name = 'redirect_to'
forms.py
from django import forms
from .models import Person, City
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ["first_name", "last_name", "address", "city_name"]
testform.html
{% extends 'home.html' %}
{% load static %}
{% block content %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-success alert-dismissible fade show" role="alert">
<span style="font-size: 18px;padding: 1mm"><i class="fa-solid fa-circle-check"></i></span>{{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
{% endif %}
<form method="POST">
{% csrf_token %}
<div class="mb-3">
<label for="first_name charfield" class="form-label"> First Name</label>
{{form.first_name}}
</div>
<div class="mb-3">
<label for="last_name charfield" class="form-label">Last Name</label>
{{form.last_name}}
</div>
<div class="mb-3">
<label for="address charfield" class="form-label">Address</label>
{{form.address}}
</div>
<div class="mb-3">
<label for="city_name datalist" class="form-label">City Name</label>
<input type="text" list="cities" class="form-control">
<datalist id="cities">
{% for city in form.city_name %}
<option>{{ city }}</option>
{% endfor %}
</datalist>
</div>
<button class="btn btn-outline-primary" type="submit">Submit</button>
</form>
{{form.errors}}
{% endblock %}
Result:
I believe it is a necessary feature for all modern web applications to have this kind of functionality within their database query-autocomplete form fields system. It is a pity that although Django provides this feature for the AdminModels through its autocomplete_fields attribute, it makes it so hard to implement on Generic Class Based Views on the actual application models.
How can I approach this issue, and is there a efficient and more optimized way to implement it?
If you don't want a field required you can set the attribute blank=True in the model class. A question I have is why would you want to have a Foreignkey to just a city name. Or are you trying to use the a list of cities to populate the drop down? In that case the Foreign Key is definitely not the answer.
In my django project, users can create posts. but the admin has to approve the post first. Then the users can see the posts created by them in their timeline. The users can like or unlike post from the post-detail page. However, when the admin logs in from the django admin panel to approve post and click the save button, it shows that the 'like' field is required. How can I solve this problem so that the admin can approve the post?
blog/models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth import get_user_model
from django.urls import reverse
from ckeditor.fields import RichTextField # first I installed ckeditor by this command: pip install django-ckeditor
# Create your models here.
class Category(models.Model):
cid = models.AutoField(primary_key=True)
category_name = models.CharField(max_length=100)
def __str__(self):
return self.category_name
class Post(models.Model):
aid = models.AutoField(primary_key=True)
image = models.ImageField(default='blog-default.png', upload_to='images/')
title = models.CharField(max_length=200)
# content = models.TextField()
content = RichTextField()
created = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
cid = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='specialization')
approved = models.BooleanField('Approved', default=False)
like = models.ManyToManyField(get_user_model(), related_name='likes')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk':self.pk})
#property
def total_likes(self):
return self.like.count()
users/models.py
from django.db import models
from blog.models import Category
from django.contrib.auth.models import AbstractUser
# Create your models here.
class CustomUser(AbstractUser):
cid = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
profile_pic = models.ImageField(default='default_person.jpg', upload_to='profile_pics')
blog/forms.py
from django import forms
from .models import Post, Comment
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'content', 'image', 'cid']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'content': forms.Textarea(attrs={'class': 'form-control'}),
'image': forms.FileInput(attrs={'class': 'form-control'}),
'cid': forms.Select(attrs={'class': 'form-control'}),
}
class EditForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'content', 'image', 'cid']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'content': forms.Textarea(attrs={'class': 'form-control'}),
'cid': forms.Select(attrs={'class': 'form-control'}),
}
users/forms.py
from django import forms
from django.contrib.auth import get_user_model # I changed the default User model. So I need to change the way I access it The right way to use it is get_user_model()
from django.contrib.auth.forms import UserCreationForm # it is used to create a new user
from blog.models import Category
User = get_user_model()
class UserRegisterForm(UserCreationForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['specialization'].required = True
email = forms.EmailField()
categories = Category.objects.all()
specialization = forms.ModelChoiceField(queryset=categories)
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2', 'specialization']
blog/post-detail.html
{% extends 'users/base.html' %}
{% block content %}
<div class="card mb-3">
<img class="card-img-top" src="{{ object.image.url }}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{ object.title }}</h5>
<p class="card-text">{{ object.content|safe }}</p>
<p class="card-text"> <b> Specialization: </b> {{ object.cid }} </p>
{% if object.author == user %}
<div>
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' object.aid %}">Edit</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.aid %}">Delete</a>
</div>
{% endif %}
<hr>
<form action="{% url 'post-like' object.pk %}" method="POST">
{% csrf_token %}
{% if post_is_liked %}
<button type="submit" name="post_id" value="{{object.aid}}" class="btn btn-danger btn-sm">Unlike</button>
{% else %}
<button type="submit" name="post_id" value="{{object.aid}}" class="btn btn-info btn-sm">Like</button>
{% endif %}
- {{ post.like.count }} Likes
</form>
</div>
<div class="card-footer text-secondary">
<a class="mr-2" href="{% url 'other-people-profile' object.author.username %}">{{ object.author }}</a>||
{{ object.created|date:"F d, Y" }}
</div>
</div>
{% endblock content %}
The field like is not mark as optional.
like = models.ManyToManyField(get_user_model(), related_name='likes', blank=True)
I am very new on Django. I wanna make patient storage system but i'm stuck.
These things must be in project.
1-) In my project i want to add hundreds of patients and also some new patients can add their own infos via register.
2-) Every patients will answer more then 300 questions, so i wanna split the model for good user experience.
Here is the my problem.
I split the main models, and then i add some basic information from hastaekle.html and then when i looked the admin panel. I see this selection page on the image at below. How can it be automatically.
Here is my models.py
from django.db import models
from django.shortcuts import render
from django.urls import reverse
# Create your models here.
class HastaProfil(models.Model):
#id = models.IntegerField(primary_key=True)
hasta_ad = models.CharField(max_length=155)
hasta_soyad = models.CharField(max_length=155)
hasta_dogum_yeri = models.CharField(max_length=155)
def __str__(self):
return self.hasta_ad + ' ' + self.hasta_soyad
def get_absolute_url(self):
return reverse('hasta-aliskanlik')
class HastaAliskanlik(models.Model):
#id = models.IntegerField(primary_key=True)
sigara = models.CharField(max_length=155)
alkol = models.CharField(max_length=155)
uyusturucu = models.CharField(max_length=155)
def __str__(self):
return self.sigara
def get_absolute_url(self):
return reverse('hasta-listele')
class Hasta(models.Model):
#id = models.IntegerField(primary_key=True)
hastaprofil = models.ForeignKey(HastaProfil, on_delete=models.CASCADE, null=True)
hastaaliskanlik = models.ForeignKey(HastaAliskanlik, on_delete=models.CASCADE, null=True)
forms.py
from .models import HastaAliskanlik, HastaProfil, Hasta
from django import forms
class HastaProfilForm(forms.ModelForm):
class Meta:
model = HastaProfil
fields = '__all__'
widgets = {
'hasta_ad' : forms.TextInput(attrs={'class': 'form-control'} ),
'hasta_soyad' : forms.TextInput(attrs={'class': 'form-control'}),
'hasta_dogum_yeri' : forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Tıklayarak Seçiniz'}),
}
class HastaAliskanlikForm(forms.ModelForm):
class Meta:
model = HastaAliskanlik
fields = '__all__'
widgets = {
'sigara' : forms.TextInput(attrs={'class': 'form-control'} ),
'alkol' : forms.TextInput(attrs={'class': 'form-control'}),
'uyusturucu' : forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Tıklayarak Seçiniz'}),
}
class HastaForm(forms.ModelForm):
class Meta:
model = Hasta
fields = '__all__'
widgets = {
'hastaprofil' : forms.TextInput(attrs={'class': 'form-control'} ),
'hastaaliskanlik' : forms.TextInput(attrs={'class': 'form-control'}),
#'uyusturucu' : forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Tıklayarak Seçiniz'}),
}
views.py
from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic import CreateView
from .forms import HastaProfilForm, HastaAliskanlikForm, HastaForm
from .models import HastaProfil, HastaAliskanlik, Hasta
# Create your views here.
class HastaProfil(CreateView):
model = HastaProfil
form_class = HastaProfilForm
template_name = 'hastaekle.html'
class HastaAliskanlik(CreateView):
model = HastaAliskanlik
form_class = HastaAliskanlikForm
template_name = 'hasta_aliskanlik.html'
def HastaListele(request):
tum_hasta = Hasta.objects.all()
return render(request, 'hasta_listele.html', {'tum_hasta': tum_hasta})
def Home(request):
return render(request, 'home.html')
hastaekle.html
<html>
<head>
<title>Hasta Ekle </title>
</head>
<body>
Anasayfa <br>
Hasta Listele
<h1>Hasta Ekle </h1>
<form action="" method="POST">
{% csrf_token %}
<h3>Hasta Profil Ekle:</h3>
Hasta Ad: <input type="text" name="hasta_ad"/><br/>
Hasta Soyad: <input type="text" name="hasta_soyad"/><br/>
Hasta Doğum Yeri: <br/>
<textarea cols="35" rows="8" name="hasta_dogum_yeri">
</textarea><br/>
<input type="submit" value="Post"/>
</form>
</body>
</html>
hasta_aliskanlik.html
<html>
<head>
<title>Alışkanlıklarınız </title>
</head>
<body>
Anasayfa <br>
Hasta Listele
<h1>Hasta Ekle </h1>
<form action="" method="POST">
{% csrf_token %}
<h3>Alışkanlıklarınız:</h3>
Sigara: <input type="text" name="sigara"/><br/>
Alkol: <input type="text" name="alkol"/><br/>
Uyuşturucu: <br/>
<textarea cols="35" rows="8" name="uyusturucu">
</textarea><br/>
<input type="submit" value="Post"/>
</form>
</body>
</html>
hasta_listele.html
<h1>Hastalar</h1>
Anasayfa <br>
Hasta Ekle
<ul>
{% for post in tum_hasta %}
<li>{{ post.hastaprofil.hasta_ad }} {{ post.hastaprofil.hasta_soyad }}
{% endfor %}
</ul>
I think you can not do it in this way because the problem what if multi users post data in same time in HastaProfil and HastaAliskanlik and for example one user post on HastaProfil and another one on HastaAliskanlik, how you will now this information for any user?
you should add on those model special field like user or link between those model, after that you can use access data in easy way
You need to use OneToOneField
class HastaAliskanlik(models.Model):
hasta_profil = models.OneToOneField(
HastaProfil,
on_delete=models.CASCADE,
primary_key=True,
)
sigara = models.CharField(max_length=155)
...
Good morning, I'm new to Django, I'm trying to include a template form, but it does not show the fields, just the save button.
Use Django 2.1. I summarize the code, so please can you help me. since you need to reuse the form in other templates.
models.py
from django.db import models
class Area(models.Model):
nombre = models.CharField(max_length=45)
descripcion = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return self.nombre
views.py
class AreaCreate(CreateView):
model = Area
form_class = AreaForm
template_name = 'area/area_form.html'
class AreaList(ListView):
model = Area
template_name = 'area/area_list.html'
forms.py
class AreaForm(forms.ModelForm):
class Meta:
model = Area
fields = (
'nombre',
'descripcion',
)
widgets = {
'nombre': forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Area'}),
'descripcion': forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Descripción'}),
}
area_form.html
<form action="" method="POST"> {% csrf_token %}
<div class="form-row">
<div class="col-sm-4 campoform">
{{ form.nombre }}
</div>
<div class="col-sm-6 campoform">
{{ form.descripcion }}
</div>
<div class="col-sm-2 campoform">
<button class="btn btn-primary" type="submit" style="width:100%">Guardar</button>
</div>
</div>
</form>
area_list.html --- I am not adding the complete list.html code for a better understanding.
<div>{% include "area/area_form.html" %}</div>
The result in area_list.html is that it shows only the button.
Sorry for the delay in responding. I solved it by calling the form with a modal. Using the library "bootstrap_modal_forms".
#View
class GestionarAreas(generic.ListView):
model = Area
context_object_name = 'areas'
template_name = 'areas/gestionar_areas.html'
paginate_by = 10
class CrearArea(generic.CreateView):
template_name = 'areas/crear_area.html'
form_class = AreaForm
success_url = reverse_lazy('gestionar_areas')
#urls
path('', login_required(views.GestionarAreas.as_view()),name='gestionar_areas'),
path('crear/', login_required(views.CrearArea.as_view()), name='crear_area'),
#HTML
<div class="col-sm-auto">
<button class="crear-area btn btn-primary" type="button"name="button">
<span class="fa fa-plus mr-2"></span>Crear Area</button>
</div>
#Script
// Boton Crear Area
$(".crear-area").modalForm({formURL: "{% url 'crear_area' %}", successURL: ""});
// Boton Actualizar Area
$(".editar-area").each(function () {
$(this).modalForm({formURL: $(this).data('id'), successURL: ""});
});
I try to make a simple illustration of my question click to view
I have a task to make a quiz.
I try to solve a problem :
Taking items in cycle by "Metrix" model there I get Questions for Quiz
It is no way to get data from "User_metrix" model while using {% for item in metrix_list %} cycle by "Metrix" model.
My models:
from django.db import models
from django.conf import settings
class Metrix(models.Model):
title = models.CharField(max_length=256, verbose_name='Question')
metrix_category = models.ForeignKey(
'category',
related_name='Question_category',
on_delete=models.CASCADE,
verbose_name='Category',
)
is_published = models.BooleanField(default=False)
def __str__(self):
return self.title
class Category(models.Model):
title = models.CharField(max_length=256,
verbose_name='Question_category')
is_published = models.BooleanField(default=False)
def __str__(self):
return self.title
class User_metrix(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="user_metrix",
verbose_name='User')
metrix = models.ForeignKey('Metrix', on_delete=models.CASCADE,
verbose_name='Question')
value = models.DecimalField(max_digits=12, decimal_places=2,
verbose_name='Value')
My view:
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from metrix.models import Metrix, User_metrix
#login_required
def metrix_view(request, pk=None):
metrix_category = {
'pk': 4
}
#Get questions by category
metrix_list = Metrix.objects.filter(is_published=True,
metrix_category__pk=pk)
context = {
'metrix_list': metrix_list
}
return render(request, 'metrix/metrix.html', context)
Template:
I list the questions in template, by cycle "metrix_list"
How to save answers to values and if answers exists return values to template?
<!--cycle for metrix-->
{% for item in metrix_list %}
<div class="row metrix_quiestion_line justify-content-center">
<div class="metrix_quiestion">
<h2>
{{ item }}
</h2>
</div>
<div class="metrix_value">
<input type="number" name="{{ item.id }}" value=" ">
</div>
</div>
{% endfor %}
<!--END cycle -->