django open specific html tab in response - html

I have a django view which render a html page in response to a POST request. I want to open a specific tab in that html page when rendered.
My view:
def internalManifest(request):
form = forms.TrackingID(request.POST or None)
if request.method == 'POST':
tracking_id = request.POST.get('tid')
messages.warning(request, 'Tracking Id Already Scanned')
return render(request, 'orders/order.html')
I want like:
return render(request, 'orders/order.html#demo-lft-tab-5')
How to do that?
EDIT: I know i can set the tag active in <div class=""... but that will make the tab active in all the redirects. I want to set it as active for this particular method.

You need to pass the active tab to the template context, for example:
render(request, 'orders/order.html', {'active_tab':'demo-lft-tab-5'})
Then in your template, check the active_tab variable, and add the "active" css to the correct tab. For example:
<div class ="demo-lft-tab-5 {% if active_tab == 'demo-lft-tab-5' %} active{% endif %}">

Related

How Do I Properly Submit Two Forms Within One HTML Structure?

I am trying to submit a create view with two forms. The code below works fine if everything is filled out and the form submitted. However if fields are omitted in form2...the form submission fails and the field that was filled out for "form"..."name"....gets reset. I've read you can do multiple forms and I've largely got this working...I just need to figure out how to incorporate form2 into the if_valid().... Here's my view...
def tasklist_detail_view(request, id):
context = {}
context["tasklist"] = TaskList.objects.get(id=id)
context["tasks"] = Task.objects.filter(task_list=id).all()
obj = get_object_or_404(TaskList, id=id)
form = UpdateTaskListForm(request.POST or None, instance=obj)
form2 = TaskForm(request.POST or None)
context["task_list_id"] = id
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse("MyTaskLists:my_task_list_main_menu"))
context["form"] = form
context["form2"] = form2
return render(request, "my_task_list_tasklist_detail.html", context)
My HTML...
<form method="POST" enctype="multipart/form-data" id="forms">
{% csrf_token %}
{{ form.name }}
{% include "my_task_list_task_create_form1.html" with tasklist=tasklist %}
<button type="submit" class="button66" name="status" value="Submitted">Submit</button>
</form>
And then in my include HTML...
<div id="task-list-form" hx-target="this" hx-swap="outerHTML">
<button class="button35" hx-post="{% url 'MyTaskLists:task-create' id=task_list_id %}">Save</button>
{{ form2 }}
I did try to do something like....
if form.is_valid() and form2.is_valid():
form.save()
return HttpResponseRedirect(reverse("MyTaskLists:my_task_list_main_menu"))
But then nothing happens...the forms are not accepted at all even if the fields are filled out properly....From what I've read I understand the POST is being applied to both forms....if one is not filled out properly that is why the other errors out? I just can't quite figure out how to process them both properly.
Thanks in advance for any thoughts.
If you want the two forms to behave like one form, and save two objects only if both forms are valid, then the logic is
if form.is_valid() and form2.is_valid():
form.save()
form2.save()
return HttpResponseRedirect(reverse("MyTaskLists:my_task_list_main_menu"))
context["form"] = form
context["form2"] = form2
return render(request, "my_task_list_tasklist_detail.html", context)
If there is any field with the same name in form and form2 you need to use a prefix to remove the ambiguity.
form = UpdateTaskListForm(request.POST or None, instance=obj, prefix='form1')
form2 = TaskForm(request.POST or None, prefix='form2')

Image is not editing after click on update button

I am going through a Django tutorial and My blog post image is not editing for edit post in my blog app. I use Django==3.1.2.
views.py
def edit_post(request, post_id):
post = BlogPost.objects.get(id=post_id)
if request.method != 'POST':
form = UpdatePost(request.POST or None, request.FILES or None, instance=post)
else:
form = UpdatePost(instance=post, data=request.POST)
if form.is_valid():
form.save()
return redirect('mains:posts')
context = {'post':post,'form':form}
return render(request, 'mains/edit_post.html', context)
forms.py
class UpdatePost(forms.ModelForm):
class Meta:
model = BlogPost
fields = ['blog_post_title','blog_description','image']
edit_post.html
{% block content %}
<div class="container">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<button type="submit">Save Changes</button>
</form>
</div>
{% endblock content %}
The Problem
I am trying to edit my post in my blog app, Everything is working fine ( Blog title and Blog description is changing ) - when i change image it returns ( redirect ) fine BUT image not changing.
I am stuck with this problem and have no idea what is wrong.
What have i tried.
1). When i first create the view then i didn't add (request.POST or None, request.FILES or None), BUT
when i notice that, this may be effecting from editing then i added and it still not editing the image.
2). I have also changed template before BUT nothing works.
3). I have also changed form before BUT nothing workes.
Help me in this. I will really appreciate your Help. Thank you in advance !!
try this...
def edit_post(request, post_id):
post = BlogPost.objects.get(id=post_id)
if request.method != 'POST':
form = UpdatePost(request.POST or None, request.FILES or None, instance=post)
else:
form = UpdatePost(instance=post, data=request.POST, files=request.FILES)
if form.is_valid():
form.save()
return redirect('mains:posts')
context = {'post':post,'form':form}
return render(request, 'mains/edit_post.html', context)

why does my link to logout not work in my Django app?

So I'm trying to do a logout link in my Django app. I've set a view that logs out the user and then redirects him to a template paginaPrincinal.html that has two buttons for login and register.
The problem is that for some reason the link href that I'm creating in my index.html doesn't appear.
my views.py
def login_view(request):
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
user = form.get_user()
login(request, user)
return redirect('index')
else:
form = AuthenticationForm()
return render(request, 'registration/login.html', {'form': form})
def logout_view(request):
logout(request)
return redirect('paginaPrincipal')
my urls.py
path('principal/', views.intro, name='pagina_principal'),
path('registro/', views.registro_usuario, name='registro_usuario'),
path('login/', views.login_view, name="login"),
path('logout/', views.logout_view, name="logout"),
path('',views.index, name ='index'),
index.html
{% block contenido %}
<div>
<ul>
{% if user.is_authenticated %}
<li>Hola, {{user.username}}</li>
<li></li>
{% endif %}
</ul>
</div>
{% endblock %}
The error that appears if I inspect the code and try to go to the Href is this:
NoReverseMatch at /myapp2/logout/
Reverse for 'paginaPrincipal' not found. 'paginaPrincipal' is not a valid view function or pattern name.
The string you pass into redirect should be a url route name. The problem is that 'paginaPrincipal' != 'pagina_principal'
def logout_view(request):
logout(request)
return redirect('pagina_principal')
That should fix it.
You are redirecting to "paginaPrincipal", but you have defined "pagina_principal". You have to change your view function
def logout_view(request):
logout(request)
return redirect('pagina_principal')
NoReverseMatch Means you have to set app_name in the urls.py like
app_name= "app_name"
and in the templates
it should work

how to pass value from html to view in django?

I have made this HTML code:
<h3>your major is {{user.userprofile.major}}</h3>
This will correctly show the major on the webpage, but I want to use this string to get something from another table in view.
How would I pass this string to view?
edit:
Here is my view.py
def dashboardView(request):
obj = BooksFile.objects.all()
query = BooksFile.objects.filter(book_major='cs)
return render(request, 'dashboard.html', {'books': obj, 'major': query})
def registerView(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
profile_form = UserProfileForm(request.POST)
if form.is_valid() and profile_form.is_valid():
user = form.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
return redirect('login_url')
else:
form = UserCreationForm()
profile_form = UserProfileForm()
context = {'form': form, 'profile_form': profile_form}
return render(request, 'registration/register.html', context)
here is my template:
{% extends 'index.html' %}
{% block content %}
<h1>Welcome, {{user.username}}</h1>
<h2>Your major is {{user.userprofile.major}}</h2>
{% for book in books %}
<h3>Your book name is {{book.book_name}}</h3>
{% endfor %}
{% endblock %}
I am trying to show the book names from the booksfile table by corresponding major that user has. Right its showing the books that has "cs" attribute because I manually put "cs" in the get function in view. I am trying to send the major string from template to view, so that I can put what ever the user's major is in the get function. Or is there any other way to do it.
You need to use a form in your template and submit it to call your view. i.e.
<form action="your_view_url" method="POST">
<input type="text" name="major" value="{{user.userprofile.major}}"/>
<input type="submit"/>
</form>
an then in your view you access that with:
if request.POST:
major = request.POST.get('major')
As per documentation: https://docs.djangoproject.com/en/2.2/topics/forms/
First of all you have to get the value of model with help of queryset, and put it in the dictionary and then pass it with the template.
In views:
def get(self, request):
queryset = Model_name.objects.all()
ctx = {
'queryset': queryset,
}
return render(request, 'page_name(or template_name).html', ctx)
in template:
<form action="{%url'(your_view_name without brackets)'%}" method="POST">
{% for data in queryset%}
<span class="username">{{data.name(field of your model)}} .
</span>
<span class="email">{{data.email(field of your model)}} .
</span>
{% endfor%}
</form>

Working with links in Django

I am working in a small blog application using Django. Sorry if the question is obvious, but I am a newbie. Actually it is my third since I started an online course. I have the following Queryset:
def all(request):
allTiles = Post.objects.values('title')
allPosts = Post.objects.all()[:3]
context = {'Posts': allPosts,"Titles":allTiles}
template = "home.html"
return render(request, template, context)
and the follwing html code:
<ol class="list-unstyled">
{% for singleTile in Titles %}
<li>{{singleTile.title}}</li>
{% endfor %}
</ol>
As you can see every title creates an link. Lets assume a person decides to read one of the posts. How can I use the title name and send a request back to the database to get the content of the post.
It is better to use the id or slug field for such task.
But if you surely want to use the title as the GET parameter then apply the urlencode filter to the field's value:
<a href="{% url 'post_detail' %}?title={{ singleTile.title|urlencode }}">
{{ singleTile.title }}
</a>
And the view will be something like this:
def post_detail(request):
post = get_object_or_404(Post, title=request.GET.get('title'))
return render(request, 'post_detail.html', {'post': post})
UPDATE: If you decide to go with the id/slug option then you can use the generic DetailView:
<a href="{% url 'post_detail' singleTile.id %}">
{{ singleTile.title }}
</a
urls.py:
from django.views.generic.detail import DetailView
from app.models import Post
url(r'^post/(?P<pk>\d+)/$', DetailView.as_view(model=Post),
name='post_detail')
You have to configure url first like
{% url 'app.views.post_id' singleTile.id %}</li>
In your urls
url(r'^post/(?P<post_id>\d+)/$', views.by_id, name='post_id'),
And in your views
def post_id(request, post_id):
allTiles = Post.objects.get(id=post_id)
return render(request, template, context)