Hi all its my code if i choice in select list django work but i want after submit choices not be change.
After submit first choices again seeing.
My Form
class PostSorguForm(forms.Form):
HIKAYE_CHOICES=(('1','En Son Çıkanlar'),('2','En Çok Okunanlar'))
sorgu_form = forms.ChoiceField(choices=HIKAYE_CHOICES,required=False)
My view
class ArticleListView(FormMixin,ListView):
context_object_name = 'articles'
template_name = 'includes/article/article-list.html'
paginate_by = 15
form_class= PostSorguForm
def get_queryset(self):
queryset = Article.objects.all()
if self.request.GET.get("sorgu_form"):
selection = self.request.GET.get("sorgu_form")
if selection == "2":
queryset = Article.objects.all().order_by('-hit_count_generic__hits')
else:
queryset=Article.objects.filter(published=True).order_by('created_date').reverse()
return queryset
my template
<form method="GET" action="">
<div class="form-group">
<select class="form-control" name="sorgu_form" id="id_sorgu_form" onchange="this.form.submit()">
{% for x,y in form.fields.sorgu_form.choices %}
<option value="{{x}}">{{y}}</option>
{% endfor %}
</select>
</div>
</form>
i want after query option selected
i search a hours and i found now it's work
if you have another idea please write
<option value="{{x}}" {% if '?sorgu_form=2' in request.get_full_path %}selected{% endif %}>{{y}}</option>
Related
I have created a search function. However, it searches for all elements that contain the entered value. For example, there are the following elements: 44564, 76436, 445. When I enter "445", it shows "44564" and "445", but I need only 445. Or if I enter "64", then nothing should be shown, but "44564" and "76436" are shown. How to fix it?
case_list.html
<div>
<h3>Search</h3>
<form method="GET" action="{% url 'case_search' %}">
<input type="search" type="text" name="q" prequired placeholder="Put value">
<button type="submit">Find</button>
</form>
</div>
<div>
{% for case in object_list %}
<div>
<p>{{ case.name }}</p>
</div>
{% endfor %}
</div>
Views.py
class CaseView(ListView):
model = Case
template_name = 'case_list.html'
class CaseSearch(ListView):
template_name = 'case_list.html'
def get_queryset(self):
return Case.objects.filter(name__icontains=self.request.GET.get("q"))
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context["q"] = self.request.GET.get("q")
return context
Urls.py
path('case_list/', CaseView.as_view(), name='case_list'),
path('case_list/search/', CaseSearch.as_view(), name="case_search"),
Use iexact for exact matches. Check out the docs https://docs.djangoproject.com/en/4.1/ref/models/querysets/#iexact
Case.objects.filter(name__iexact=self.request.GET.get("q"))
Am trying to customize my checkbox inputs to look like this [what i want to archive]
so i tried this...
profile.html
<ul class="wt-accountinfo">
{% for key, value in form.interests.field.choices %}
<li>
<div class="wt-on-off pull-right">
<input type="checkbox" id="{{ value }}" value="{{ key }}" name="interests">
<label for="{{ value }}"><i></i></label>
</div>
<span>{{ value | title }}</span>
</li>
{% endfor %}
</ul>
which renders the html fine but highlight the select fields from the database
but using {{ form.interest }} highlights the selected checked boxes from the database
here is the forms.py
class ProfileForm(forms.ModelForm):
interests = forms.ModelMultipleChoiceField(
queryset=JobsCategories.objects.all(), widget=forms.CheckboxSelectMultiple(),
required=False
)
class Meta:
model = Profile
fields = ['interests']
and here is the models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,
interests = models.ManyToManyField(Categories, related_name='interests', null=True, blank=True)
def __str__(self):
return f'{self.user.first_name} {self.user.last_name}'
in the views.py
def dashboard_profile(request):
if request.method == 'POST':
form = ProfileForm(request.POST, request.FILES, instance=request.user.profile)
account_form = AccountForm(request.POST, instance=request.user)
if form.is_valid() and account_form.is_valid():
f_interests = form.save(commit=False)
for i in request.POST.getlist('interest'):
f_interests.interest.update(i)
f_interests.save()
form.save_m2m()
account_form.save()
return redirect('index')
else:
form = ProfileForm(instance=request.user.profile)
account_form = AccountForm(instance=request.user)
context = {
'form': form,
'account_form': account_form,
}
return render(request, 'dashboard_profile.html', context)
NOTE!!! if i select the options i want and click save, it saves the options i checked to the database
this is it
this is it in the admins section
admin section
admin section 2
and also when i use {{ form.interests }} in the the template it renders fine and highlights the checked option from the database but its not styled
[how it looks like when i use {{ form.interests }}]
i know am missing somtehing in the profile.html so please help me out Thanks.
You're missing logic within your input tag to apply the existing value of the field choice.
<ul class="wt-accountinfo">
{% for key, value in form.interests.field.choices %}
<li>
<div class="wt-on-off pull-right">
<input type="checkbox"
id="{{ value }}"
value="{{ key }}"
name="interests"
{% if value %}checked{% endif %}>
<label for="{{ value }}"><i></i></label>
</div>
<span>{{ value | title }}</span>
</li>
{% endfor %}
</ul>
I am having trouble with my Search API. Results of the queryset could not get through my template even though the query set fetched data from the model.
If the search is empty the queryset should return all the Models associated to the current project, otherwise, it should return models that qualify the criteria in the query.
I have tested the result of the query and it returns records from the model but could not display the instances into the template.
My SEARCH ListView:
class ModelSearchListView(ListView):
model = Model
template_name = 'predictions/model_listview.html'
context_object_name = 'models'
paginate_by = 2
def get_queryset(self):
query = self.request.GET.get('q')
proj_pk = self.kwargs.get('pk')
proj = get_object_or_404(Project, id=proj_pk)
if query:
result = Model.objects.filter(Q(project=proj.id) & (Q(name__contains=query) |
Q(algorithm_type__contains=query) |
Q(predictors__contains=query) |
Q(target_column__contains=query))).order_by('-date_created')
# print('result: ', result)
else:
result = Model.objects.filter(project=proj.id).order_by('-date_created')
print('result: ', result)
return result
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project = Project.objects.filter(id=self.kwargs.get('pk')).first()
context['current_project'] = project.id
MY SEARCH FORM:
<form class="form my-2 my-lg-0" method="GET"
action="{% if current_project %}
{% url 'model-search-listview' current_project %}
{% else %}
{% url 'model-search-listview' object.project.id %}
{% endif %}">
<div class="input-group">
<input class="form-control " type="text" name="q" value="{{ request.GET.q }}" aria-label="Search"
placeholder="Search">
<span class="input-group-btn">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit" value="Search">
Search
</button>
</span>
</div>
</form>
The TEMPLATE:
{% if not models %} #Always TRUE because models is empty
<h5>No prediction models created for this project!</h5>
{% else %}
#Loop never executed
{% for model in models %} # models HERE ALWAYS returns empty
[SOME CODE HERE]
{% endfor %}
{% endif %}
You need to return the new context
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project = Project.objects.filter(id=self.kwargs.get('pk')).first()
context['current_project'] = project.id
return context
I'm trying to create a TimeInput field in a form and noticed that the widget isn't showing correctly. But when I check the localhost:8000/admin, I see the widget showing up correctly.
My code is as follows. For models.py,
class TimeLimit(models.Model):
before = models.TimeField(blank=True, default=time(7, 0)) # 7AM
after = models.TimeField(blank=True, default=time(23, 0)) # 11PM
For views.py,
class UpdateTimeLimitView(LoginRequiredMixin, FormView):
model = TimeLimit
template_name = 'accounts/update_time_limit.html'
form_class = UpdateTimeLimitForm
def get_success_url(self):
return reverse_lazy('accounts:user_profile') + '?username=' + self.request.GET['username']
def get_context_data(self, **kwargs):
data = super(UpdateTimeLimitView, self).get_context_data(**kwargs)
data['username'] = self.request.GET['username']
return data
For forms.py,
class UpdateTimeLimitForm(forms.Form):
time_error = {'required': 'This field is required.',
'invalid': 'Please enter valid Hour:Minute values.'}
before = forms.TimeField(widget=forms.TimeInput(format='%H:%M'))
after = forms.TimeField(widget=TimeInput(format='%H:%M'))
class Meta:
model = TimeLimit
Finally, the relevant part for fields in update_time_limit.html,
<div class="container">
<form method="post">
{% csrf_token %}
<p>
{% for field in form %}
{{ field.errors }}
<label for="{{ field.id_for_label }}">{{ field.label }}({{ field.help_text }}):</label>
<br />
{{ field }}<br /><br /> and
{% endfor %}
</p>
<input class="btn btn-primary done-btn" type="submit" value="Update Time Limit">
</form>
</div>
Is there anything that I'm missing or doing wrong? Thank you.
The Django admin uses AdminTimeWidget to display time fields, not the TimeInput widget that you are using in your code.
There isn't a documented way to reuse the AdminTimeWidget outside of the Django admin. Getting it to work is very hacky (see the answer on this question, which is probably out of date), so it's probably better to use a different widget.
convert datetime.time(7, 0) to string work for me.
data['before'] = data['before'].strftime('%H:%M:%S')
I have a page that display all the objects acorrding to the catergory the students pick.
I implemented a pagination on the site to split the objects at different pages.
The problem occurs when the students pick a catergory from the dropbox and tries to flick through the pagination for new and old entries.
The reason this happens because everytime the user picks a catergory from the dropbox , the dropbox get reset once it retrieve the objects. So when users try to flick through objects using the pagination . The pagination doesn't know what data to retrieve because the dropbox catergory get reset and redirec the users to a blank page.
A solution to this is to program the dropbox to remain static for the choices the users make so when the users flicks through the data split by the pagination , the pagination know can retrieve objects according to the dropbox.
I can't figure out how to make this dropbox remain static for the choices the users make.
my views.py
def BoardFinder(request):
form = BoardFinderForm(request.POST)
fo = BoardFinderForm()
if form.is_valid():
Category = form.cleaned_data['Category']
posts = Board.objects.filter(Category=Category)
paginator = Paginator(posts, 1)
try: page = int(request.GET.get("page", '1'))
except ValueError: page = 1
try:
posts = paginator.page(page)
except (InvalidPage, EmptyPage):
posts = paginator.page(paginator.num_pages)
return render(request,"boardfinder.html",{"posts":posts,"fo":fo})
return render(request,"boardfinder.html",{"fo":fo})
My models.py
class Board(models.Model):
MATH = 'MATH'
ENGLISH = 'ENGLISH'
SCIENCE = 'SCIENCE'
LANGUAGE = 'LANGUAGE'
CATEGORY = (
(MATH, 'Math'),
(ENGLISH, 'English'),
(SCIENCE, 'Science'),
(LANGUAGE, 'Language'),
)
Category =models.CharField(max_length=30,choices=CATEGORY)
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
picture = models.OneToOneField('Picture',related_name='picture',blank=True,null=True)
def __unicode__(self):
return self.name
class BoardFinderForm(forms.ModelForm):
class Meta:
model = Board
fields = ('Category',)
Important parts of my boardfinder.html
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ fo.as_p }}
<input type = "submit" value= "Find WhiteBoard" />
</form>
{% for post in posts.object_list %}
<div class="title">{{ post.name }}</div>
{% endfor %}
<form method="GET">
<p><select name="category">
<option value=""
{% if not request.session.category %}selected{% endif %}>
(All subjects)
</option>
<option value="ENGLISH"
{% if request.session.category == "ENGLISH" %}selected{% endif %}>
English
</option>
<option value="LANGUAGE"
{% if request.session.category == "LANGUAGE" %}selected{% endif %}>
Language
</option>
<option value="MATH"
{% if request.session.category == "MATH" %}selected{% endif %}>
Math
</option>
<option value="SCIENCE"
{% if request.session.category == "SCIENCE" %}selected{% endif %}>
Science
</option>
</select></p>
<input type = "submit" value= "Find WhiteBoard" />
</form>
def BoardFinder(request):
category = request.GET.get('category')
if category:
request.session['category'] = category
posts = Board.objects.filter(Category=category)
paginator = Paginator(posts, 1)
try: page = int(request.GET.get("page", '1'))
except ValueError: page = 1
try:
posts = paginator.page(page)
except (InvalidPage, EmptyPage):
posts = paginator.page(paginator.num_pages)
return render(request,"boardfinder.html",{"posts":posts,"fo":fo})
return render(request,"boardfinder.html",{"fo":fo})