I would like you to help me change the default text in the forms created by django in the foreign key fields for a custom text.
Description of part of the content of Models.py
class Historial(models.Model):
id_historial=models.AutoField(primary_key=True)
id_equipo=models.ForeignKey("Equipo", on_delete=models.CASCADE, verbose_name="Numero Serial de la computadora")
id_usuario=models.ForeignKey("Usuario", on_delete=models.CASCADE, verbose_name="Nombre del usuario")
fecha_entrega = models.DateField ('Fecha de entrega', auto_now=True , auto_now_add=False)
fecha_devolucion = models.DateField('Fecha de devolucion', auto_now=True , auto_now_add=False)
qr_code = models.ImageField(upload_to="CodigosQR")
recibido=models.BooleanField(default=False)
class Meta:
verbose_name="Historial"
verbose_name_plural="Historial"
def __str__(self):
return f"{self.id_equipo}"
Description of part of the content of Forms.py
class HistorialForm(forms.ModelForm):
id_equipo = forms.ModelChoiceField(queryset=Equipo.objects.filter(Prestado=False).filter(basura_electronica=False))
id_usuario = forms.ModelChoiceField(queryset=Usuario.objects.filter(allow=True).filter(activo=True))
def __init__(self, *args, **kwargs):
super(HistorialForm, self).__init__(*args,**kwargs)
self.fields['id_equipo'].widget.attrs['class'] = 'form-control'
self.fields['id_equipo'].widget.attrs['placeholder'] = 'Numero serial de la computadora'
self.fields['id_usuario'].widget.attrs['class'] = 'form-control'
self.fields['id_usuario'].widget.attrs['placeholder'] = 'Nombre del usuario'
class Meta:
model = Historial fields = [
"id_equipo", "id_usuario",
]
labels={
"id_equipo":"Numero serial de la computadora",
"id_usuario": "Nombre del usuario",
}
Description of part of the content of Views.py
class ListadoHistorial(ListView):
model=Historial
form_class=HistorialForm
template_name="prestamos/listar_prestamos.html"
context_object_name="prestamos"
queryset=None
def get_queryset(self):
return self.model.objects.all()
def get_context_data(self, **kwargs):
contexto={}
contexto["prestamos"]=self.get_queryset()
contexto["form"]=self.form_class
return contexto
def get(self, request, *args,**kwargs):
return render(request, self.template_name, self.get_context_data())
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
form.save()
return redirect("equipo:listar_prestamos")
Description of part of the content of prestamo.html
{% extends "index.html" %}
{% block titulo %}
Crear nuevo prestamo
{% endblock titulo %}
{% block body %}
<form method="POST">
{% csrf_token %}
{% if error %}
<h2>{{ error }}</h2>
{% else %}
{{ form.as_p }}
<button type="submit">Guardar</button>
</form>
{% endblock body %}
{% block extrajs %}
{% endblock extrajs %}
Capture of the form with default text in the foreign keys
Capture
I would like it to appear like this:
If you need to know more code or an image go ahead ask to attach what is necessary
Use initial on your form.
yourForm(initial={}), put value as dictionary between curly braces.
If you want to do it directly in Model.
class Items(models.Model):
name = models.CharField(max_length=10)
def getItem():
item = Items.objects.get(pk=1)
return item
class MyItem(models.Model):
item = models.ForeignKey(Items, on_delete=models.CASCADE, default=getItem)
For future people I attach the answer which is in self.fields['id_equipo'].label = 'Serial number of the computer'. I'm not sure though because filtering doesn't work.
Forms.py
class HistorialForm(forms.ModelForm):
id_equipo = forms.ModelChoiceField(queryset=Equipo.objects.filter(Prestado=False).filter(basura_electronica=False))
id_usuario = forms.ModelChoiceField(queryset = Usuario.objects.filter(allow = True).filter(activo=True), initial="Nombre del usuario")
def __init__(self, *args, **kwargs):
super(HistorialForm, self).__init__(*args,**kwargs)
self.fields['id_equipo'].widget.attrs['class'] = 'form-control'
self.fields['id_equipo'].widget.attrs['placeholder'] = 'Numero serial de la computadora'
self.fields['id_equipo'].widget.attrs['label'] = 'Numero serial de la computadora'
self.fields['id_equipo'].label = 'Numero serial de la computadora'
self.fields['id_usuario'].widget.attrs['class'] = 'form-control'
self.fields['id_usuario'].widget.attrs['placeholder'] = 'Nombre del usuario'
class Meta:
model = Historial
fields = [
"id_equipo", "id_usuario",
]
labels={
"id_equipo":"Numero serial de la computadora",
"id_usuario": "Nombre del usuario",
}
Related
I have an addpage form where users have to add their card for boots model. Below i will show to you my code.
SO! The problem is my images are not saving at my media directory at all. And so one of the
consequences Card.model doesn't take this images, but rest of the form fields working perfictly. Sorry for my bad english and asking for support!!
Models.py
class Card(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория')
brand = models.ForeignKey(Brand, on_delete=models.PROTECT, verbose_name='Бренд')
boots_model = models.CharField(max_length=100, db_index=True, verbose_name='Модель бутс')
description = models.TextField(verbose_name='Описание')
slug = AutoSlugField('URL', max_length=70, db_index=True, unique_with=('created', 'boots_model', 'size', 'color', 'price'), populate_from=instance_boots_model, slugify=slugify_value)
price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Цена')
# image = models.ImageField(upload_to="photos/%Y/%m/%d/", blank=True, verbose_name='Загрузите фотографии')
created = models.DateTimeField(auto_now_add=True, db_index=True)
updated = models.DateTimeField(auto_now=True)
size = models.DecimalField(max_digits=4, decimal_places=1, verbose_name='Размер')
NEW = 'new'
USED = 'old'
STATEMENT_CHOICES = [
(NEW, 'Новые'),
(USED, 'Б/У')
]
statement = models.CharField(max_length=3, choices=STATEMENT_CHOICES, default=USED, verbose_name='Состояние')
color = models.CharField(max_length=100, db_index=True, verbose_name='цвет')
class Meta:
ordering = ('-created',)
verbose_name = 'Объявление'
verbose_name_plural = 'Объявления'
def __str__(self):
return self.boots_model
def save(self, *args, **kwargs):
self.slug = uuslug(self.slug, instance=self)
super(Card, self).save(*args, **kwargs)
def get_absolute_url(self):
category = self.category
brand = self.brand
return reverse('card', args=[str(category.slug), str(brand.slug), str(self.slug)])
class ImagePhoto(models.Model):
directory = models.ForeignKey(Card, on_delete=models.CASCADE)
image = models.ImageField(upload_to=upload_custom_directory, blank=True, verbose_name='Фотографии')
def __str__(self):
return str(self.image)
class Meta:
verbose_name = 'Фотографии'
verbose_name_plural = 'Фотографии'
forms.py
class AddCardForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['category'].empty_label = "Категория не выбрана"
self.fields['brand'].empty_label = "Бренд не выбран"
# self.fields['boots_model'].help_text = "Старайтесь вводить полное название обуви"
class Meta:
model = Card
fields = ['category', 'brand', 'boots_model', 'description', 'price', 'size', 'statement', 'color']
help_texts = {
'boots_model': 'Название на английском языке с цифрами\nНапример: PREDATOR 18.3 FG',
}
widgets = {
'description': forms.Textarea(attrs={'cols': 30, 'rows': 5, 'placeholder': 'Введите что-нибудь'}),
}
def clean_boots_model(self):
cyrillic_letters = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'
boots_model = self.cleaned_data['boots_model']
for c in boots_model:
if c in cyrillic_letters:
raise ValidationError('Допускается название только на английском языке и цифры')
return boots_model
class AddimgForm(forms.ModelForm):
class Meta:
model = ImagePhoto
fields = ['image']
widgets = {
'image': forms.ClearableFileInput(attrs={'multiple': True}),
}
and finally views.py
def add_page(request):
MyFormSet = inlineformset_factory(Card, ImagePhoto, fields=('image',), extra=0)
if request.method == 'POST':
form = AddCardForm(request.POST)
formset = MyFormSet(request.POST, request.FILES,)
if form.is_valid() and formset.is_valid():
c = form.save(commit=False)
c.save()
for f in formset:
pic = ImagePhoto(directory=c, image=f.cleaned_data('image'))
pic.save()
return redirect('home')
else:
form = AddCardForm()
formset = MyFormSet(queryset=ImagePhoto.objects.none())
return render(request, 'mysite/addpage.html', {'formset': formset, 'form': form, 'title': 'Добавить объявление'})
also addcard.html
<form action="{% url 'addpage' %}" method="post" enctype="multipart/form-data" class="addpage-form">
{% csrf_token %}
<h1>Разместить объявление</h1>
{% for p in form %}
{% if p.help_text %}<p class="help-text">{{ p.help_text|linebreaksbr }}{% endif %}
<p><label class="form-label" for="{{ form.id_for_label }}">{{ p.label }}: </label>{{ p }}</p>
{% endfor %}
{{ formset.management_form }}
<input type="file" name = "files" multiple />{% for f in formset %}
<div class="form-error">{{ f.errors }}</div>
{% endfor %}
<div class="addpage-button-submit">
<button type="submit">Добавить объявление</button>
</div>
</form>
I made a list of events registered today in the inventory template, and I would like to show the total rating of the events(registered today).
I called it from the template by making the sum of the scores a function, but it is not visible. Does anyone know?
views.py
class CalendarView(generic.ListView):
model = Event
template_name = 'cal/calendar.html'
def get_queryset(self, **kwargs):
return Event.objects.all().filter(start_time__date=date.today())
def filter_event_rating_sum(self):
filtered_event = Event.objects.all().filter(start_time__date=date.today())
sum_rating = 0
for each_event in filtered_event:
sum_rating += each_event.rating
return sum_rating
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
d = get_date(self.request.GET.get('month', None))
cal = Calendar(d.year, d.month)
# issue self.request.user
html_cal = cal.formatmonth(self.request.user, withyear=True)
context['calendar'] = mark_safe(html_cal)
context['prev_month'] = prev_month(d)
context['next_month'] = next_month(d)
return context
templates.html
<p class="today">Today</p>
{% for list in object_list %}
<div class="today_list_item">
<span>{{ list.title }}</span>
<span class="each_rating">{{ list.rating }}</span>
</div>
{% endfor %}
<p class="total">TOTAL</p>
{{ sum_rating }}
</div>
models.py
class Event(models.Model):
title = models.CharField(max_length=200)
start_time = models.DateTimeField(default = timezone.now, blank = True)
# default = timezone.now,
profile=models.ForeignKey(Profile, related_name='event',on_delete=models.CASCADE)
rating = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)], blank=True, default='enter your value')
def __str__(self):
return '{}/ {}/ {}'.format(self.id, self.title, self.start_time, self.rating)
you can only use those variables which are in the dictionary returned by get_context_data function. Add this code in get_context_data function like this
queryset['sum_rating'] = self.filter_event_rating_sum()
I am trying to create a online Phone Book for my locality. I am getting problem with the app's entry creation view.
Here is my PhoneEntry model:
# coding=utf-8
from django.urls import reverse_lazy
from django.db import models
from django.template.defaultfilters import slugify
from phonenumber_field.modelfields import PhoneNumberField
class PhoneEntry(models.Model):
# Name of the organisation
org_name = models.CharField(max_length=100, verbose_name="Organisation's Name")
org_details = models.CharField(max_length=500, blank=True, verbose_name="Organisation's Details")
slug = models.SlugField(default='slug', unique=True)
# Verified or not
verified = models.BooleanField(default=False, blank=True)
# Dates when the entry was added and verified
added_date = models.DateField(auto_now_add=True, editable=False)
verified_date = models.DateField(auto_now_add=True)
last_edited_date = models.DateField(blank=True, null=True, auto_now_add=True)
# The phone numbers of the organisation
primary_ph_number = PhoneNumberField(verbose_name="Primary Phone Number")
secondary_ph_number = PhoneNumberField(verbose_name="Secondary Phone Number", blank=True)
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
super(PhoneEntry, self).save(force_insert, force_update, using, update_fields)
self.slug = slugify(self.org_name+"-"+str(int(self.id)))
super(PhoneEntry, self).save(force_insert, force_update, using, update_fields)
#staticmethod
def get_absolute_url():
return reverse_lazy('phbook:index')
def __str__(self):
return self.org_name+"-"+str(self.primary_ph_number)
class Meta:
verbose_name_plural = "Phone Entries"
And this the EntryCreateForm:
class EntryAddForm(forms.ModelForm):
"""org_name = forms.CharField(max_length=100, label="Enter your organisation name: ")
org_details = forms.CharField(max_length=100, widget=forms.Textarea,
label="Enter your organisation details: ", required=False)"""
primary_ph_number = PhoneNumberField(label="Enter your primary phone number: ")
secondary_ph_number = PhoneNumberField(label="Enter your secondary phone number: ", required=False)
class Meta:
model = PhoneEntry
exclude = ['slug', 'last_edited_date', 'added_date', 'verified_date', 'verified']
And this the EntryAddView:
class EntryCreateView(CreateView):
model = PhoneEntry
form_class = EntryAddForm
template_name = 'phbook/form.html'
success_url = 'phbook:index'
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
print("Data is", form.instance)
model = form.save(commit=False)
print(model.org_name, model.org_details, model.primary_ph_number, model.secondary_ph_number)
model.save()
return self.get_success_url()
And the template form.html
{% extends 'base.html' %}
{% block head %}
<title>Add your Organisation's Entry | PhoneBook</title>
{% endblock %}
{% block body %}
{% load crispy_forms_tags %}
<form method="post" action="{% url 'phbook:add' %}" enctype="multipart/form-data">
<button type="submit" value="Submit">Submit</button>
{% csrf_token %}
{% crispy form %}
</form>
{% endblock %}
The base.html contains only the static links for the foundation css and js files.
In the EntryCreateView, when the line print("Data is ", form.instance) is executed it produced this result
Please tell me what I am doing here??
You've overridden post on the view, and are therefore bypassing all the calls to validation that the CreateView would normally do. There is rarely any good reason to override the get or post methods; you should always define a more specific method; in this case, form_valid would be more appropriate, if all you want to do is print out the submitted data. If that's just for debugging, then you may not need to override any methods at all.
I am beginner in django (using django 1.7) and trying to create a form using crispy-forms in order to add new product to db. The problem is, form is working but it is not creating new product in database.
when I logged, if i click to save button nothing happen and shows below in address bar.
http://127.0.0.1:8000/add_product/?csrfmiddlewaretoken=kfGpEA6ZC32Lad9m9uwWZEhElwBGLHPA&csrfmiddlewaretoken=kfGpEA6ZC32Lad9m9uwWZEhElwBGLHPA&Category_IDCategory=66&DealType=Rent&Title=kkjkj&Price=78&Description=kjjk&save=Save
if I logged out and click to save button it directs me to the homepage as I provide in form but still no new product in database.
The problem looks like related to user and csrf, but still couldnt figure out the exact problem even I searched need your help.
models.py
class Product(models.Model):
DealType_Choice = (
("Sale", "Sale"),
("Rent", "Rent"),
("Swap", "Swap"),
("Free", "Free"),
("Announ", "Announ"),
)
DealType = models.CharField(max_length=11, blank=True, choices=DealType_Choice)
Title = models.CharField(max_length=70)
Description = models.TextField(blank=False)
Price = models.IntegerField(max_length=11, null=True)
User_IDUser = models.ForeignKey(User)
Category_IDCategory = models.ForeignKey(Category)
PubDate = models.DateField("Publication Data")
def __str__(self):
return self.Title
views.py
def add_product(request):
product_form= ProductForm(request.POST)
if product_form.is_valid():
form=product_form.save(commit=False)
form.User_IDUser= request.user
form.save()
return HttpResponseRedirect('/')
else:
product_form= ProductForm()
return render(request, 'add_productts.html', {'product_form':product_form})
forms.py
class ProductForm(forms.ModelForm):
Category_IDCategory=forms.ModelChoiceField(queryset=Category.objects.all(), label="Category")
DealType=forms.ChoiceField(widget=forms.Select, choices=Product.DealType_Choice, label="DealType")
Title=forms.CharField(label='Title', max_length=70)
Price=forms.IntegerField(min_value=0, label='Price')
Description=forms.CharField(widget=forms.Textarea(), label="Description")
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_method = "POST"
self.helper.form_action= "/"
self.helper.layout= Layout(
Field('Category_IDCategory',css_class='input-sm'),
Field('DealType',css_class='input-sm'),
Field('Title',css_class='input-sm'),
Field(PrependedText('Price', 'TL', '.00'),css_class='input-sm'),
Field('Description',css_class='input-sm', rows=5),
FormActions(
Submit('save', 'Save', css_class='btn btn-labeled btn-info'))
)
super(ProductForm, self).__init__(*args, **kwargs)
class Meta:
model=Product
fields= ['Category_IDCategory','DealType', 'Title','Price', 'Description']
template
{% extends "index.html" %}
{% load crispy_forms_tags %}
{% block content %}
<h1>Add Product</h1>{% csrf_token %}
{% crispy product_form %}
{% endblock %}
urls.py
urlpatterns = patterns('',
...
url(r'^add_product/$', add_product),
...
)
I think this is wrong:
self.helper.form_action= "/"
form_action should refer to add_product function:
self.helper.form_action= "/add_product/"
I want to show the data of a user which he has entered. This is my model
class IgaiaContent(models.Model):
CONTENT_CHANNELS = (
('YouTube','Youtube'),
('FaceBook','FaceBook'),
('Flickr','Flickr'),
('Instagram','Instagram'),
)
content_name = models.CharField(max_length=255, primary_key=True)
content_type = models.CharField(max_length=255,null=True)
content_source = models.CharField(max_length=255,null=True, choices=CONTENT_CHANNELS)
content_location = models.CharField(max_length=255,null=True)
content_latitude = models.DecimalField(max_digits=20,decimal_places=2,null=True)
content_longitude = models.DecimalField(max_digits=20,decimal_places=2,null=True)
content_embed_code = models.TextField(null=True)
content_description = models.TextField(null=True)
content_tags_user = models.CharField(max_length=255,null=True)
content_time_uploaded = models.DateTimeField(auto_now_add=True)
content_time_updated = models.DateField(null=True)
def __unicode__(self):
return self.content_name
return self.content_type
return self.content_source
return self.content_location
return self.content_latitude
return self.content_longitude
return self.embed_code
return self.description
return self.tags_user
return self.time_uploaded
return self.time_updated
tagging.register(IgaiaContent)
My view
def create_page(request):
if request.method == 'POST':
form = AuthorForm1(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/thanks/')
else:
form = AuthorForm1()
c = {}
c.update(csrf(request))
return render_to_response('portal/form1.htm',{'form':form},context_instance=RequestContext(request))
My form template:
<form method="post" style="height: 553px; width: 594px">
<div class="style12">
{% csrf_token %}
</br>{{ form.as_p }}
</div>
</form>
thats how i am showing my model values
employee_info1 = {
"queryset" : IgaiaContent.objects.all(),
"template_name" : "portal/emp1.html",
}
urlpatterns = patterns('',
(r'^view5/', list_detail.object_list, employee_info1),
)
emp1.html
{% if object_list %}
<table>
<ul>
{% for item in object_list %}
<li>{{item.content_name}}</li>
<li>{{item.content_type}}</li>
<li>{{item.content_source}}</li>
<li>{{item.content_location}}</li>
<li>{{item.content_latitude}}</li>
<li>{{item.content_longitude}}</li>
<li>{{item.content_embed_code}}</li>
<li>{{item.content_description}}</li>
<li>{{item.content_tags_user}}</li>
<li>{{item.content_time_uploaded}}</li>
<li>{{item.content_time_updated}}</li></ul>
{% empty %}
<td colspan="11">No items.</td>
{% endfor %}
</table>
{% endif %}
It is not displaying specific user value means it is displaying me everything.
can anyone tell me how to show specific user values/data?
You need to update your model so that it contains a field to store the user -
from django.contrib.auth.models import User
class IgaiaContent(models.Model):
#...
user = models.ForeignKey(User)
Then you need to create a ModelForm as described here.
class IgaiaContentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
return super(MyModelForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
kwargs['commit']=False
obj = super(MyModelForm, self).save(*args, **kwargs)
if self.request:
obj.user = self.request.user
obj.save()
class Meta:
model = IgaiaContent
Now update your view so that that you use your new ModelForm
def create_page(request):
if request.method == 'POST':
form = IgaiaContentForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/thanks/')
else:
form = IgaiaContentForm()
#...
Now in your object_list view you do something like -
from django.shortcuts import render_to_response
def object_list(request):
#....
object_list = IgaiaContent.objects.filter(user=request.user)
return render_to_response('object_list_template.html', {'object_list': object_list})