I have a page where the customer name in the cards is not rearrange in ascending order via alphabetical order Ex: B,M,S. How do I make it to arrange in alphabetical order so that the cards with the customer name Bangkok airways will appear first follow by the cards with malaysia airlines will appear next and so on?
views.py
def outgoinggallery(request):
user = request.user
category = request.GET.get('category')
if category == None:
alloutgoinglru = OutgoingLRU.objects.filter(category__user=user)
else:
alloutgoinglru = OutgoingLRU.objects.filter(category__name=category, category__user=user)
# if query:
# return OutgoingLRU.objects.filter(title__icontains=query)
categories = Category.objects.filter(user=user)
context = {'categories': categories, 'alloutgoinglru': alloutgoinglru}
return render(request, 'Outgoing/outgoinggallery.html', context)
outgoinggallery.html
{% extends "logisticbase.html" %}
{% block content %}
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<style>
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
border-radius: 15px;
}
.image-thumbail {
height: 200px;
object-fit: cover;
}
.list-group-item a {
text-decoration: none;
color: black;
}
</style>
<br>
<div style="padding-left:16px">
<div class="row">
<div class="col-md-9">
<div class="row">
<h5>View Outgoing LRU</h5>
<div class="col-md-7">
</div>
<br>
<div class="col-md-9">
<div class="row">
{% for OutgoingLRU in alloutgoinglru %}
<div class="col-md-4">
<div class="card my-4">
<img class="image-thumbail" src="{{OutgoingLRU.image.url}}" >
<div class="card-body">
<small>Customer Name: {{OutgoingLRU.category.name}}</small>
<br>
<small>Delivery Order: {{OutgoingLRU.Deliveryor}}</small>
</div>
View
<form action="{% url 'deleteoutgoing' OutgoingLRU.id %}" method="post">
{% csrf_token %}
<button type="submit" style="width:270px" class="btn btn-sm btn-danger">Delete</button>
</form>
</div>
</div>
{% empty %}
<h3>No photos...</h3>
{% endfor %}
</div>
</div>
</div>
</div>
{% endblock %}
models.py
class OutgoingLRU(models.Model):
class Meta:
verbose_name = 'OutgoingLRU'
verbose_name_plural = 'OutgoingLRUs'
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True)
image = models.ImageField(null=False, blank=False)
equipmentimages = models.ImageField(null=False, blank=False)
boximages = models.ImageField(null=False, blank=False)
documentimage = models.ImageField(null=False, blank=False)
datetime = models.DateTimeField() # datetime is the date and time the form was created
serialno = models.TextField() # serialno stand for serial number
partno = models.TextField() # partno stand for part number
Deliveryor = models.TextField() # deliveryor stand for delivery order
MCO = models.TextField()
descriptionequipment = models.TextField() # A short description about the equipment (*Optional)
descriptionequipmentbox = models.TextField() # A short description of the equipment in the box (*optional)
descriptionbox = models.TextField() # A short description of the box (*optional)
document = models.TextField() # A short description of the delivery note document (*optional)
def __str__(self):
return self.descriptionequipment
Ascending:
alloutgoinglru = alloutgoinglru.order_by('category__name')
Descending:
alloutgoinglru = alloutgoinglru.order_by('-category__name')
models.py
class Category(models.Model):
user = models.ForeignKey(
User, on_delete=models.SET_NULL, null=True, blank=True)
name = models.CharField(max_length=100, null=False, blank=False)
class Meta:
ordering = ('name',)
verbose_name = 'Category'
verbose_name_plural = 'Categories'
def __str__(self):
return self.name
class OutgoingLRU(models.Model):
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True)
image = models.ImageField(null=False, blank=False)
equipmentimages = models.ImageField(null=False, blank=False)
boximages = models.ImageField(null=False, blank=False)
documentimage = models.ImageField(null=False, blank=False)
datetime = models.DateTimeField() # datetime is the date and time the form was created
serialno = models.TextField() # serialno stand for serial number
partno = models.TextField() # partno stand for part number
Deliveryor = models.TextField() # deliveryor stand for delivery order
MCO = models.TextField()
descriptionequipment = models.TextField() # A short description about the equipment (*Optional)
descriptionequipmentbox = models.TextField() # A short description of the equipment in the box (*optional)
descriptionbox = models.TextField() # A short description of the box (*optional)
document = models.TextField() # A short description of the delivery note document (*optional)
class Meta:
verbose_name = 'OutgoingLRU'
verbose_name_plural = 'OutgoingLRUs
ordering = ('category__name',)
def __str__(self):
return self.descriptionequipment
after that:
1)run python manage.py makemigrations
2)run python manage.py migrate
Related
I have authentication app with
models:
LIVING_COUNTRIES = [
('AFGANISTAN', 'Afganistan'),
('ALBANIA', 'Albania'),
('ALGERIA', 'Algeria'),
('ANGORRA', 'Andorra'),
('ANGOLA', 'Angola')]
class Employee(models.Model):
first_name = models.CharField(max_length=100, blank=True)
last_name = models.CharField(max_length=100, blank=True)
username = models.CharField(max_length=30, blank=True)
email = models.EmailField(max_length=140, blank=True)
# phone_number = PhoneNumberField(null=True)
date_of_birth = models.DateField(blank=True, default='1929-22-22')
education = models.CharField(max_length=50, blank=True)
country_living = models.CharField(max_length=50, choices=LIVING_COUNTRIES, default='UNITEDSTATESOFAMERICA', blank=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True)
password = models.CharField(max_length=30, null=True)
Now I want to display country_living field in my html form.
I have tried like this:
<select name="category" id="id_category">
{% for category in living_countries.country_living %}
<option value="{{ category.country_living }}">{{ category.country_living }</option>
{% endfor %}
</select>
def get(self, request):
context = {}
living_countries = models.Employee.objects.all()
context['living_countries'] = living_countries
return render(request, 'authentication/employee_register.html', context)
But it doesn't work. Does anyone know how to access and display this field?
LIVING_COUNTRIES is a list in your models.py file but it is outside the Employee model, so there's no way for it to show up inside your view and from your view to your template.
to resolve that in your views, you can do from from .models import *
this way the model and list will be available to us.
Better way of working would be to have a model for LivingCountries and use that as one-to-one relationship with Employee model.
Next, in views, you need to correct the query from models.Employee.objects.all() to Employee.objects.all()
the view function can be simplified as following and the list should be passed within the function as following
def get(request):
employees = Employee.objects.all()
living_countries_list = LIVING_COUNTRIES
return render(request, 'authentication/employee_register.html', {
'employees': employees,
'living_countries_list': living_countries_list
})
since now you have employee data and living countries list being sent to template, you can do following to get list of countries
in your template
<select name="category" id="id_category">
{% for each in living_countries_list %}
<option value="{{ each.0 }}">{{ each.1 }</option>
{% endfor %}
</select>
I have the following django models / forms / views / html setup.
So I am rendering the InputFileForm in the html and the user should select from dropdown list a face_file that is saved in the Face model (preloaded via fixtures). I would like to have the face_file images to be rendered in the dropdown (alternatively a radio select would be fine as well) instead of the image str names - as it currently looks like the following:
Image of current dropdown
So in short: I would like to have an image rendered in the dropdown instead of the "Face 1", "Face 2",...
Thanks in advance for your help!
class Face(models.Model):
face_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=64)
face_file = models.ImageField(upload_to='../media/faces', blank=True, null=True)
def __str__(self):
return self.name
class InputFile(models.Model):
input_id = models.AutoField(primary_key=True)
input_flatlay_file = models.ImageField(upload_to='../media/flatlays', blank=True, null=True)
input_face_file = models.ForeignKey(Face, null=True, blank=True, on_delete=models.CASCADE, related_name="inputs_using_this_face")
input_user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE, related_name="user_inputs")
class Prediction(models.Model):
prediction_id = models.AutoField(primary_key=True)
prediction_inputs = models.ForeignKey(InputFile, null=True, blank=True, on_delete=models.CASCADE, related_name="prediction_inputs")
output_lookbook_file = models.ImageField(upload_to='../media/lookbooks', blank=True, null=True)
prediction_user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE, related_name="user_predictions")
I have a ModelForm for InputFile:
class MyModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return mark_safe('<img src="%s">' %obj.face_file.url)
class InputFileForm(forms.ModelForm):
class Meta:
model = InputFile
fields = ['input_flatlay_file','input_face_file']
widgets = {
'input_face_file': MyModelChoiceField(queryset=Face.objects.all()),
}
In my views.py:
def prediction(request):
form=forms.InputFileForm()
if request.method == 'POST':
form = forms.InputFileForm(request.POST or None, request.FILES or None)
if form.is_valid():
new_input = form.save(commit=False)
new_input.input_user = request.user
new_input.save()
output_lookbook_file = util.prediction(new_input.input_flatlay_file, new_input.input_face_file.face_file)
new_prediction = Prediction(output_lookbook_file = output_lookbook_file, prediction_user = request.user, prediction_inputs=new_input)
new_prediction.save()
return render(request, "modelgan/prediction.html", {"form": form,
"new_input":new_input, "new_prediction": new_prediction })
else:
return render(request, "modelgan/prediction.html", {"form": form })
return render(request, "modelgan/prediction.html", {"form": form })
In my html I am rendering the ModelForm as following:
{% if user.is_authenticated %}
<form action="{% url 'prediction' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<form action="" method="POST">
{% csrf_token %}
{{ form.as_table }}
<input type="submit" value="Generate lookbook image">
</form>
</form>
You can override label_from_instance - see ModelChoiceField.iterator
See also Overriding the default fields
And than you can do something like following:
from django.utils.safestring import mark_safe
from django.forms import ModelChoiceField
class MyModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return mark_safe('<img width="60" src="%s">' % obj.face_file.url)
class InputFileForm(forms.ModelForm):
input_face_file = MyModelChoiceField(
queryset=Face.objects.all(), required=False,
widget=forms.RadioSelect)
class Meta:
model = InputFile
fields = ['input_flatlay_file','input_face_file']
I wanted to create a blog site where an author and editor can both have the edit option and the editors will be assigned by author. Now my model field looks like this :
class Editor(models.Model):
name = models.OneToOneField(Author, on_delete=models.CASCADE, null=True, blank=True)
class Blog(models.Model):
title = models.CharField(max_length=150, null=True, blank=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True, blank=True)
editor = models.ManyToManyField(Editor, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
article = models.TextField(blank=True, null=True)
genre = models.ManyToManyField(Genre, blank=True)
def __str__(self):
return self.title
and views.py :
def blog(request, pk):
if request.user.is_authenticated:
blogs = Blog.objects.get(id=pk) //for dynamic url
editors = Editor.objects.all()
context = {'blogs':blogs,'editors':editors}
return render(request, 'blog/blog.html', context)
then I wanted to check if the person who is accessing if author or editor or not, so I written an if condition :
{% if request.user.author == blogs.author or blogs.editor %}
Edit
{% endif %}
but unfortunately the edit button can be accessed by everyone. what should I do?
First of all.
{% if request.user.author == blogs.author or blogs.editor %}
Edit
{% endif %}
In this piece of code, the condition is not very good defined. My suggestion is that you make this in this way:
{% if request.user.author == blogs.author or request.user.author == blogs.editor %}
Edit
{% endif %}
This is one suggestion.
Now another posibility is to use JavaScript.
In order to do that, I give you some code example of my own.
<script type="text/javascript">
var editor = '{{user.author.editor}}'
if (editor == 'False'){
document.getElementById('edit').innerHTML = ''
}
</script>
In this code, I'm defining that if the user is not a editor, I will not hide the element (In html) with id 'edit'. So in your template, set an id to your element.
<a id="edit" href="#" class="btn btn-warning">Edit</a>
For this, you will have to set a boolean field in your model.
You can do it like this:
class Editor(models.Model):
name = models.OneToOneField(Author, on_delete=models.CASCADE, null=True, blank=True)
editor = models.Boolean()
So I'm loading my registration form into my html and then using a for loop to iterate over those fields. I am wondering where I can add form control to show a green box around my username field so that a user knows if a username is taken before hitting the submit button. I tried adding it to the form tag and setting a div tag around {{field}} but neither of those work. Furthermore, how can I make it ONLY for Username?
registration.html
{% block content %}
<br>
<h1 class="text-center" style="color:#f5387ae6">Register to fall in love today!</h1>
<form method="post" style="width:700px;margin:auto" action="{% url 'dating_app:register' %}" enctype="multipart/form-data" class= "form" >
{% bootstrap_form registration_form%}
{% csrf_token %}
{% for field in bootstrap_form %}
<p>
<div class="form-control is-valid">
{{field.label_tag}}
{{field}}
</div>
{% if field.help_text %}
<small style="color:grey;">{{field.help_text}}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red;">{{error}}"</p>
{% endfor %}
</p>
{% endfor %}
<div class="form-check">
<input type="checkbox" id="accept-terms" class="form-check-input">
<label for="accept-terms" class="form-check-label">Accept Terms & Conditions</label>
</div>
<div>
<br>
<button type="submit">Register</button>
</div>
</form>
{% endblock content %}
reg_form
class RegistrationForm(UserCreationForm):
class Meta:
model = Profile
fields = ("username","email","description","photo","password1","password2")
models.py
class ProfileManager(BaseUserManager):
def create_user(self, username, email,description,photo, password=None):
if not email:
raise ValueError("You must creat an email")
if not username:
raise ValueError("You must create a username!")
if not description:
raise ValueError("You must write a description")
if not photo:
raise ValueError("You must upload a photo")
user = self.model(
email=self.normalize_email(email),
username = username,
description= description,
photo= photo,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email,description,photo, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
description=description,
photo=photo,
)
user.is_admin=True
user.is_staff=True
user.is_superuser=True
user.save(using=self._db)
return user
class Profile(AbstractBaseUser):
class Meta:
swappable = 'AUTH_USER_MODEL'
email = models.EmailField(verbose_name="email")
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
#what I added
description = models.TextField()
photo = models.ImageField(upload_to='profile_photo',blank=False, height_field=None, width_field=None, max_length=100)
matches = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='+', blank=True)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['description','photo','email']
objects = ProfileManager()
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self,app_label):
return True
class Conversation(models.Model):
members = models.ManyToManyField(settings.AUTH_USER_MODEL)
class UserVote(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
voter = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='given_vote', on_delete=models.CASCADE)
vote = models.BooleanField(default=False)
class Meta:
unique_together = (('user', 'voter'))
class InstantMessage(models.Model):
sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE )
receiver = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'receiver',on_delete=models.CASCADE )
conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE)
message = models.TextField()
date = models.DateTimeField(verbose_name="Data creation",default=timezone.now, null=False)
viewed = models.BooleanField(default=False, db_index=True)
def __unicode__(self):
return self.message
#tests to see if messages are exclusive between sender, receiver (won't work with new model)
#classmethod
def find_messages_exclusive_to_profile(cls,sender,receiver):
#members = receiver AND sender, not receiver or sender
exclusive_conversations = Conversation.objects.filter(members= receiver ).filter(members= sender)
exclusive_messages = InstantMessage.objects.filter(conversation__in=exclusive_conversations)
return exclusive_messages
You will need to setup a view which, given a string can check to see if that object exists in the database:
# views.py
from django.contrib.auth.models import User
from django.http import JsonResponse
def check_if_username_exists_view(request, username):
name_taken = User.objects.filter(username=username).exists()
data = {
'name_taken ': name_taken
}
return JsonResponse(data)
Then within your login page you will need some javascript similar to the below:
$("#username").change(function(val){
$.get( {% url 'user_exists_view' %} + val, function( data ) {
alert( "username taken: " data.name_taken );
});
})
I have a problem using ModelMultipleChoiceField. I have a Model named Instrumentation and other named InstTemplate:
class Instrumentation(models.Model):
code = models.CharField(max_length=70, unique=True)
marca = models.CharField(max_length=70)
modelo = models.CharField(max_length=70)
familia = models.CharField(max_length=150)
subfamilia = models.CharField(max_length=150)
calibration_date = models.DateField()
#test = models.ForeignKey(Test)
notes = models.TextField(max_length=170, blank=True)
utilization = models.DateField(blank=True)
def is_free(self):
return (self.utilization == None)
def is_calibrated(self):
return (self.calibration_date > date.today())
class InstTemplate(models.Model):
name = models.CharField(max_length=70)
equipo = models.ManyToManyField(Instrumentation)
boards = models.CharField(max_length=20)
project = models.ForeignKey(Project)
notes = models.TextField(max_length=170, blank=True)
I would like to implement a multiple select with checkboxes in field "equipo" which is a ManyToManyField. This multiple selection, as I have read, is implemented in forms.py:
class InstTemplateForm(forms.ModelForm):
BOARD_CHOICES = (('1','ML801/AP815'),('2','ML455/AP455'),('3','ML801/AP801'),('4','ML801/AP836i'), ('5','ML801/AP809'), ('6','CANHEAD'), ('7','ML74/AP74'),('8','ML74/AP75'))
boards = forms.MultipleChoiceField(BOARD_CHOICES, widget=forms.CheckboxSelectMultiple())
equipo = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=Instrumentation.objects.all())
class Meta:
model = InstTemplate
But in HTML, with the following code, I only get the database "id" field and the name "Instrumentation object" for all the objects that the queryset gets. Therefore, the queryset is working, but I only get "Instrumentation object".
{% block page %}
<div id="form" class="tab-content clearfix" style="display: block;">
<h4><strong>New instrumentation template: project {{ project.ref }}</strong></h4>
<hr class="alt1"/>
<form class="vertical" action="{% url "new_instrumentation" project.ref %}" method="post"> {% csrf_token %}
{{ form.as_ul }}
</form>
</div>
{% endblock %}
How can I get the fields of the Instrumentation object??
Define __unicode__ method in Instrumentation model for human-readable representation of the model object:
class Instrumentation(models.Model):
code = models.CharField(max_length=70, unique=True)
marca = models.CharField(max_length=70)
modelo = models.CharField(max_length=70)
familia = models.CharField(max_length=150)
subfamilia = models.CharField(max_length=150)
calibration_date = models.DateField()
#test = models.ForeignKey(Test)
notes = models.TextField(max_length=170, blank=True)
utilization = models.DateField(blank=True)
def is_free(self):
return (self.utilization == None)
def is_calibrated(self):
return (self.calibration_date > date.today())
def __unicode__(self):
return self.code # or self.marca what ever you want