Prevent anchor link to adding to the url in Django - html

I have a project where I can list distributions. I have a homepage where I have the options to click on the lecture or lecturer. Now I want that when I am on the lecturers page that I can click on one anchor tag which redirects me to the target page. However the URL does only add the new slug. I will post the urls and templates. Hope you can help me, Thanks in advance.
urls.py
app_name='distribution'
urlpatterns=[
path('',views.Index.as_view(),name='home'),
path('<slug:slug>/',views.LecturerDistribution.as_view(),name='lecturer_distribution'),
path('dersler/<slug:slug>/',views.LectureDistribution.as_view(),name='lecture_distribution'),
]
this my part in the lecture code template
<p style="text-align:center;"><a style="text-decoration:none" href="{% url 'distribution:lecture_distribution' slug=i.lecturer.slug%}">{{i.lecturer}}</a> | {{i.semester}}</p>
and here is my cbv for the lecture_distribution
class LectureDistribution(generic.DetailView):
model=Lecture
template_name='lecture.html'
def get_success_url(self):
return reverse('lecture_distribution', kwargs={'slug': self.object.slug})
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context ['distribution_'] = Distribution.objects.filter(lecture=self.object).order_by('-created_on')
return context
my url when I am clicking on the anchor tag is this:
http://127.0.0.1:8000/dagilimlar/dersler/mehmet-cem-guclu/
But it should
http://127.0.0.1:8000/dagilimlar/mehmet-cem-guclu/
as you see the "dersler" field is there which should not it is only for the lectures.

Related

Angular ver. 14.0.2, How to create anchors that redirect to certains blocks of the page?

I'm currently using Angular for a few weeks for a small project and I wanted to add an anchor in my app.
So normally in order to add an anchor without using any framework, you'd create a block with an ID
<div id="top"> then you'd add an anchor tag <a href="#"> with the href attribute that would be equal to the ID of the block of the page we want to redirect the to.
ex:
<div id="top">...</div>
...
When we click on the link, it scrolls up to the page* to the block we defined the ID with.
*if we add in the CSS of the html or body tag scroll-behavior: smooth;
The issue is that when I add that inside my Angular template, it redirects me to the URL with the name of the ID on the href attribute!
If I take the previous example, here's what would happen:
localhost:4200/login → (click to the link) → localhost:4200/#top
Strangely it treats it as if it was a router link attribute
So I'm wondering how we could add an anchor in Angular
So I found a solution! (thanks to #Benjamin Looi for giving me the link to a relevant post)
So actually Angular has an issue with anchor tags when we want the user to another part of the same page
The solution is to use routerOptions of type extra options in the appRoutingModule and add in some options, here's the code:
const routes: Routes = [...];
const routerOptions: ExtraOptions = {
useHash: false,
anchorScrolling: 'enabled',
onSameUrlNavigation: 'reload' //Must have if you want to be able to use the anchor more than once
};
#NgModule({
imports: [RouterModule.forRoot(routes, routerOptions)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Then in the template, we have to add the anchor of the block we want to redirect the user in the attributes fragment with the name of the ID and routerLink with the page you're in (otherwise it will redirect to "/")
ex:
<a routerLink="/login" fragment="top"></a>
Now it will successfully redirect to the top of the page!
May be this might help
HTML code :
<button (click)="scrollToElement(target)"></button>
<div #target>Your target</div>
Ts code :
scrollToElement($element): void {
console.log($element);
$element.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
}
got it from this
Using HTML anchor link #id in Angular 6

Django sign in form, the stylizing with Bootstrap is not doing anything

I am having some troubles with Django. So, I wanted to use Bootstrap´s sign in template and use it in my project. So, I have been able to do it correctly, except the username and password fields, which are showing up as regular {{form.username}} even though I have used the form-control class. Let me show you:
forms.py
from django import forms
from django.forms import TextInput, PasswordInput
class LogINFO(forms.Form):
username= forms.CharField(label= 'Usuario: ', max_length=20, widget=forms.TextInput(attrs={"placeholder": "Username", 'style': 'width: 300px;', "class": "form-control"}))
password=forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'style': 'width: 300px;', 'class': 'form-control'}))
and my login.html
{% csrf_token %}
<div class="form-floating">
{{form.username}}
</div>
<div class="form-floating">
{{form.password}}
</div>
Well, it apparently omits everything and it just shows up as a regular form input.
I am not using model as I am using the auth application.
Authentication forms like login have a tendency to override customisations unless set up in a particular way.
Try the following
urls.py
from django.contrib.auth import views
from .forms import LogINFO
....
path('login/',
views.LoginView.as_view(
template_name="registration/login.html", #this is default, change as needed
authentication_form=LogINFO,
),
name='login'
),
views.py
from django.contrib.auth.forms import AuthenticationForm,
class LogINFO(AuthenticationForm):
username= forms.CharField(label= 'Usuario: ', max_length=20, widget=forms.TextInput(attrs={"placeholder": "Username", 'style': 'width: 300px;', "class": "form-control"}))
password=forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'style': 'width: 300px;', 'class': 'form-control'}))
def __init__(self, *args, **kwargs):
super(LogINFO, self).__init__(*args, **kwargs)
The key elements are:
making your form a subclass of the AuthenticationForm class (which makes sense as you are using Django's auth)
calling the super init function (which allows the subclass to use all the methods of the class)
and providing the class of the authentication_form in your URLs.py file
One final note, when I am overriding a template for another app like django.config.auth, I place the app in question before it in settings.py INSTALLED_APPS so that it finds my new template first.

a href in react opening subroute instead of new link

item.link = "www.youtube.com"
{item.about}
This tag is making a call to localhost:3000/www.youtube.com
If you add the "protocol" to link like item.link = "http://www.youtube.com
Will work as expected

How to call view function via button from template in Django?

I've searched some of the related questions and I couldn't figure out how to do it. That is why I am posting a new question here.
I have a base.html file and there is a button which should run a function from views.py file. Here is the button code:
<form role="form" action="" method="POST">
{% csrf_token %}
<input type="submit" class="btn" value="Click" name="mybtn">
</form>
And here is my function from views.py file:
def create_new_product(request):
if request.method == 'POST':
'''Execute the code here'''
return render (request, 'products/base.html')
And in my Products' urls.py file:
app_name = 'products'
urlpatterns = [
path('create-new-product/', views.create_new_product),
path('', views.IndexView.as_view(), name='base'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
]
Normally I have an IndexView class in views.py file which lists all the current products and what I expect from the above function is that it will generate new products and new products will also be listed in 'products' page.
The above function is not inside the IndexView class by the way.
You will stay on the same page with action="#"
Try instead action="" so you will stay on the same page but reloaded.
Update:
Read your comment.
The name argument is useful to call your url in Django template like :
path('create-new-product/', views.create_new_product, name='create_new_product')
The app_name = 'products' is very important. It tells Django where to check your path. So you can call your view everywhere in your project by:
...
<form action="{% url 'products:create_new_product' %}">...</form>
you can either use browser fetch api or jquery ajax to implement search functionality
include a js script to your template file
include this js snippet
$(elementSelector).on("click", async (e) => {
const fetchOptions = {}
const response = await fetch(YOUR_URL, {...fetchOptions});
const responseUrl = response.url // see fetch api docs
window.location = responseUrl // if you want to redirect
)

Call Django on HTML button click

I'm trying to make a basic sort function for a Django project, but I don't know how to call the sort function when I click the 'sort' button
Django view:
def sort_btn(request):
if request.GET.get('sort-btn'):
cits = Citizen.objects.all().order_by('name')
return render_to_response(request, 'civil_reg/index.html', {'cits': cits})
HTML button:
<button name="sort-btn" id="sort-btn">sort</button>
you need to wrap your <button> with <form> tag, as following snippet:
<form action='actionUrl' method='GET'>
<button type='submit'> sort me</button>
</form>
and in your urls.py module you should point the actionUrl with specific view from the views.py module as follow:
from django.urls import path
from . import views
urlpatterns = [
path(actionUrl, views.yourSort),
]
you should more read about request lifecycle on Django:
user submit request
Django tries to get the first match between request's URL and routes defined in urls.py
the request is passed to the matched view
the view get executed, usually this some model processing
a response (template) is returned by the view as HttpResponse
I don't know about your program but my implementation is the full as it is that worked.
<button name="button" type="submit" onclick="location.href='{% url "actionUrl" %}'"> Send</button>
I am trying to call a function in views named "sendEmail"
path('actionUrl/', views.sendEmail,name='actionUrl')
And above one is the line which I included in urls file.