Reputation: 347
I have a small newsletter signup form at the footer of every page. The footer is part of base.html
.
I use Ajax to submit the form. Right now Ajax code calls a view defined in app1
and the corresponding URL is defined in the urls.py
of the same app.
Here's the AJAX code (this code is saved in a separate js
file and included in the base.html
):
$('#newsletterForm').submit(function(e){
e.preventDefault()
$('#loader').css("display", "block")
$.ajax({
type : "POST",
url : "/subscribe/",
data : {
subscriber_email : $('#e-mail').val(),
csrfmiddlewaretoken : csrftoken,
datatype : "json",
},
success: function(){
$('#loader').css("display", "none"),
$('#subscribed').css("display", "block"),
$('#subscribed').delay(3000).fadeOut("slow")
},
failure: function(){
alert('An error has occurred. Please try again.')
},
});
});
The view (defined in app1):
def subscribe(request):
if request.is_ajax():
subscriber = Subscriber(email=request.POST.get('subscriber_email'))
subscriber.save()
return JsonResponse({}, status=200)
else:
return redirect('homepage:index')
The URL (defined in app1):
path('subscribe/', views.subscribe, name='subscribe'),
Now, the problem is when I'm in app2
, Django looks for /subscribe/
in that app which doesn't exist.
So is there any way to solve this issue by including the appname
in the url
of AJAX code? or I have to include /subscribe/
in urls.py
and views.py
of every app?
Upvotes: 0
Views: 157
Reputation: 190
I don't fully understand your problem. Do you want to use the same url in app1 in app2? If this is your request, as far as I know, such a thing is not possible because a related views function is connected to each url in the urls.py file.
-- UPDATED --
As I understand you want to make the URL field in the AJAX code dynamic. This is how I solve this problem. I either add an attribute to the form tag or add a hidden input field within the form field and bring the relevant url from the views function to the html file related to the context and add it to one of the fields I specified, and finally, I take the value of the relevant attribute or input field by javascript and assign it to the url information of the AJAX code.
Upvotes: 2