I have a problem with menu in html in django
the problem is in index page menu works perfectly fine, but in other apps such as projects or blog pages menu loads ok but when you scroll down and scroll up menu dissapears and i have to reload the page, i have added menu in database so i can add things in admin panel, here is my codes:
views.py
def proindex(request):
setting = Setting.objects.all().get()
menu = SettingMenu.objects.all().get()
proj = Project.objects.all()
context = {'setting': setting, 'menu': menu, 'proj': proj, 'navbar': 'projects'}
return render(request, "projects.html", context)
models.py
class Setting(models.Model):
Website_Title = models.CharField(max_length=200)
Footer_Text = models.CharField(max_length=10000)
Header_Text1 = models.CharField(max_length=200, default="Text")
Header_Text2 = models.CharField(max_length=200, default="Text")
Banner_Text1 = models.CharField(max_length=200, default="Text")
Banner_Text2 = models.CharField(max_length=200, default="Text")
Banner_Button = models.CharField(max_length=200, default="Text")
def __str__(self):
return "Website Settings"
class SettingMenu(models.Model):
Admin_Panel = models.CharField(max_length=200)
Admin_Link = models.CharField(max_length=200)
Menu_Item1 = models.CharField(max_length=200)
Menu_Link1 = models.CharField(max_length=200)
Menu_Item2 = models.CharField(max_length=200)
Menu_Link2 = models.CharField(max_length=200)
Menu_Item3 = models.CharField(max_length=200)
Menu_Link3 = models.CharField(max_length=200)
Menu_Item4 = models.CharField(max_length=200)
Menu_Link4 = models.CharField(max_length=200)
Menu_Item5 = models.CharField(max_length=200)
Menu_Link5 = models.CharField(max_length=200)
Menu_Item6 = models.CharField(max_length=200)
Menu_Link6 = models.CharField(max_length=200)
Menu_Item7 = models.CharField(max_length=200)
Menu_Link7 = models.CharField(max_length=200)
Menu_Item8 = models.CharField(max_length=200)
Menu_Link8 = models.CharField(max_length=200)
def __str__(self):
return "Menu Settings"
base.html
<!-- ***** Header Area Start ***** -->
<header class="header-area header-sticky">
<div class="container">
<div class="row">
<div class="col-12">
<nav class="main-nav">
<!-- ***** Logo Start ***** -->
<a href="{% url 'main:index' %}" class="logo">
<img src="{% static 'assets/images/logo.png' %}" alt="">
</a>
<!-- ***** Logo End ***** -->
<!-- ***** Menu Start ***** -->
<ul class="nav">
<li>صفحه اصلی</li>
{% if user.is_superuser %}
<li>پنل مدیریت</li>
{% endif %}
<li>پروژه ها</li>
<li>وبلاگ</li>
<li>{{ menu.Menu_Item4 }} <img src="{% static 'assets/images/profile-header.jpg' %}" alt=""></li>
</ul>
<a class='menu-trigger'>
<span>Menu</span>
</a>
<!-- ***** Menu End ***** -->
</nav>
</div>
</div>
</div>
</header>
<!-- ***** Header Area End ***** -->
Related
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
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']
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'am using bootstrap Tab panes and i need to show posts with specific tag in each pane without reloading the page of course
for more detail i'm using Django with Wagtail CMS my app based on models file
EDIT : add tag dict to context
models.py:
class BlogIndex(Page):
intro = RichTextField(blank=True)
def get_context(self, request):
base_tags = ['foo','boo','voo']
# Update context to include only published posts, ordered by reverse-chron
context = super(BlogIndex, self).get_context(request)
blogpages = self.get_children().live().order_by('-first_published_at')
context['blogpages'] = blogpages
context['base_tags'] = base_tags
return context
class BlogPageTag(TaggedItemBase):
content_object = ParentalKey('BlogPage', related_name='tagged_items')
class BlogPage(Page):
#info
tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
#contentpanel ....
note: i am using taggit but it seems that i didn't well handle it
blog_index.html
<div>
<ul class="nav nav-tabs" role="tablist">
{% for tag in base_tags %}
<li role="presentation" ><a href="#{{tag}}" aria-controls="{{tag}}"
role="tab" data-toggle="tab">{{tag}}</a></li>
{% ednfor %}
</ul>
<!-- Tab panes -->
<div class="tab-content">
{% for tag in base_tags %}
<div role="tabpanel" class="tab-pane" id="{{tag}}">
#this is what i'am thinking of
#for posts in blogpages :
# if post tag == "{{tag}}":
# show post
</div>
</div>
</div>
If you have a few specific tags, you can call them in the template by define them below.
On the other hand if tags will increase continuously, It might be better to create a new model for tags.
class PostListView(ListView):
model = Post
def get_context_data(self, **kwargs):
context = super(PostListView, self).get_context_data(**kwargs)
all_list = Post.objects.all()
news_list = Post.objects.filter(tag='news')
context = {
'all_list': all_list,
'news_list': news_list,
}
return context
Edit:
You can show like this;
{% for object in news_list %}
{{ object.title }}
{{ object.timestamp }}
{% endfor %}
I am having trouble uploading the image in Django Form.
The following form fails to validate due to some issue in the image uploading
Here is the code :
forms.py
from django import forms
from .models import Description, Bill
class DForm(forms.ModelForm):
class Meta:
model = Description
fields = ('desc', 'billing', 'length', 'quality', 'rate')
class BForm(forms.ModelForm):
party = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Party'}))
inovice = forms.FloatField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Invoice#'}))
amount = forms.FloatField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Bill-Amount'}))
image = forms.ImageField()
image_caption = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Description for bill'}))
class Meta:
model = Bill
fields = ('party', 'inovice', 'amount','image','image_caption')
models.py
from __future__ import unicode_literals
#from django.utils.encoding import python_2_unicode_compatible
from django.db import models
##python_2_unicode_compatible
class Description(models.Model):
desc = models.CharField(max_length = 200,default = "Suits")
billing = models.FloatField(max_length = 200)
length = models.FloatField(max_length = 200)
quality = models.CharField( max_length=200,default = "custom")
rate = models.FloatField(max_length = 200)
def __str__(self):
return self.desc
class Bill(models.Model):
party = models.CharField(max_length = 200)
inovice = models.FloatField(max_length = 200)
amount = models.FloatField(max_length = 200)
image = models.ImageField(upload_to='images/products/main',null=True, blank=True)
image_caption = models.CharField(max_length=200,default = "null")
def __str__(self):
return self.party+','+str(self.inovice)+','+str(self.amount)
def bill_id(self):
return self.id;
index.html
{% load staticfiles %}
<!-- test -->
<html>
<head>
<title></title>
<link href="{%static "./styles/bootstrap.min.css" %}" rel="stylesheet" />
</head>
<body>
<h1 style="text-align: center;">Rahul's Shop</h1>
<h2 style="text-align: center;">Inventory</h2>
<form enctype="multipart/form-data" id="bill" action ="{% url 'front:commitbill' %}" method = "post" class="form-horizontal">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label for="party" class="control-label col-md-3">{{ field.name }}</label>
<div class="col-md-4">
{{ field }}
</div>
<div class="col-md-5">
<span id="one" style="position:relative; top:5px; color:red "></span>
</div>
</div>
{% endfor %}
<div class="container">
<div class="row">
<input type="button" id="add_items" class="col-md-offset-5 col-md-2 btn btn-success" value="Add items" \>
</div>
</div>
</form>
and views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Description, Bill
from django.http import Http404
from .forms import DForm
from .forms import BForm
import pprint
def bill(request):
try:
billinfo = Description.objects.all()
context = {'billinfo': billinfo}
except Description.DoesNotExist:
raise Http404("No Bills")
return render(request, 'front/bill.html', context)
def commitvalues(request):
if request.method == "POST":
form = DForm(request.POST)
if form.is_valid():
Description = form.save()
print Description
return HttpResponse("Hello;You're at the front index.Commit's done!")
print form.errors
return HttpResponse("Fail")
def commitbill(request):
form = BForm()
if request.method == "POST":
form = BForm(request.POST,request.FILES)
if form.is_valid():
Bill = form.save()
return HttpResponse(str(Bill.bill_id()))
else:
print form.errors
form = BForm()
return render(request, 'front/index.html', {
'form': form
})
The print form.errrs returns the following two errors :
<ul class="errorlist"><li>image<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
The forms starts working fine when i remove the image = forms.ImageField() from my forms.py, just the image doesn't uploads, otherwise when i include image = forms.ImageField(), the form never saves due to the above Error