i have a redirect url problem when the user complete editing his profile informations ,i want to redirect to the profile page , but it display to me 404 error
this is My view.py file :
def ProfileView(request, pk=None):
prof = Profile.objects.all()
if pk:
pr = User.objects.get(pk=pk)
else:
pr = request.user
context= {
'pro':prof,
'profile':pr
}
return render(request,'profile.html',context)
def update_profile(request,id):
profile = get_object_or_404(Profile,id=id)
form = ProfileForm(request.POST or None ,request.FILES or None,instance=profile)
if request.method=='POST':
if form.is_valid:
form.save()
return redirect(reverse('profile-detail'))
context = {
'form':form
}
return render(request,'profile_update.html',context)
thi is my url.py file :
urlpatterns = [
path('admin/', admin.site.urls),
path ('',index),
path ('events_details/<id>',events_details,name="events_details"),
path ('evenements/',evenements,name="events"),
path ('projets/',projets,name="project"),
path ('project_detail/<id>/',project_detail,name="project-detail"),
path ('create_post',create_post,name="create_post"),
path ('project_detail/<id>/update_post',update_post,name="update_post"),
path ('project_detail/<id>/delete_post',delete_post,name="delete_post"),
#------------------------------------------------------------
path ('profile/',ProfileView,name="profile-detail"),
path ('profile_update/<id>',update_profile,name="profile-update"),
path('tinymce/', include('tinymce.urls')),
path('accounts/', include('allauth.urls')),
path('api-auth/', include('rest_framework.urls'))
]
The Error i got :
Request Method: POST
Request URL: http://127.0.0.1:8000/profile_update/
.
.
.
The current path, profile_update/, didn't match any of these.
The problem is that your url expects an id with the url (ie localhost:8000/profile_update/12), but when you are making a post request, you are not sending one.
So I am guessing you need to update the code like this:
def update_profile(request,id):
profile = get_object_or_404(Profile,id=id)
form = ProfileForm(request.POST or None ,request.FILES or None,instance=profile)
if request.method=='POST':
if form.is_valid:
form.save()
return redirect(reverse('profile-detail'))
context = {
'form':form,
'pk': id
}
return render(request,'profile_update.html',context)
And update the template as well:
<form name="form" method="post" action="{% url 'profile-update' pk %}">
Try changing the redirect line from
return redirect(reverse('profile-detail'))
to
return redirect('app-name:profile-detail')
where app-name is the name of your django app.
Related
I created a form. I want to when the user fills the form and then sends it, redirect a specific page.
But in my case, the form is saving successfully but does not redirect the page. How can I solve it?
views.py
def setup_wizard(request):
form = SetupForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
setup = form.save()
setup.user = request.user
setup.save()
redirect('dashboard')
else:
form = SetupForm()
context = {
'form': form,
}
return render(request, 'setup_wizard.html', context)
dashboard.urls.py
urlpatterns = [
path('', dashboard, name="dashboard"),
path('setup', setup_wizard, name="setup"),
]
mainproject.urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('dashboard/', include('dashboard.urls')),
... ]
When you're using the redirect method from Django shortcuts you need to return the function result. See this from Django docs
How can I send data ( the user_to_follow in this example ) to my views.py function ( follow ) to do some updates?
I'm trying to send the username from my JavaScript and then add the logged-in username to that username following list ( all done in my views.py function )
Views.py.
def follow(request, profile_to_follow):
try:
user_to_follow = User.objects.get(username=profile_to_follow)
user_to_following = Profile.objects.get(user=request.user.id)
except User.DoesNotExist:
return JsonResponse({"error": "Profile not found."}, status=404)
if request.method == "PUT":
user_to_following.following.add(user_to_follow)
return HttpResponse(status=204)
index.js
function follow_user(user_to_follow){
// How To send the user_to_follow to my views.py method.
// to add the current logged in user to the user_to_follow following list
console.log(user_to_follow)
}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
# API Routes
path("posts", views.compose_post, name="compose_post"),
path("posts/all_posts", views.show_posts, name="show_posts"),
path("posts/<int:post_id>", views.post, name="post"),
path("profile/<str:profile>", views.display_profile, name="profile"),
path("<str:profile_posts>/posts", views.display_profile_posts, name="profile_posts"),
path("follow/<str:user_to_follow>", views.follow, name="follow"),
]
The easiest method would be using an Ajax Query to send data from templates to your views.py
index.js
<script>
$(document).ready(function() {
function follow_user(user_to_follow){
$.ajax({
type: "PUT",
url: "{% url 'follow' user_to_follow %}",
data: {
user_data: user_to_follow,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function( data )
{
alert("Successful Added User to list");
}
});
});
});
</script>
views.py
def follow(request, profile_to_follow):
try:
user_to_follow = User.objects.get(username=profile_to_follow)
user_to_following = Profile.objects.get(user=request.user.id)
except User.DoesNotExist:
return JsonResponse({"error": "Profile not found."}, status=404)
if request.method == "PUT" and request.is_ajax():
user_to_following.following.add(user_to_follow)
return HttpResponse(status=204)
request.is_ajax()
This will return a boolean value based on whether the request is an AJAX call or not.
You can also refer to this documentation https://api.jquery.com/jQuery.ajax/#options
I'd like my login page to redirect a user to an instance of a page. Such an instance will be denoted as follows:
www.example.com/adminpage/username
This is what I have in my settings.py
LOGIN_REDIRECT_URL = 'leicunnadmin'
LOGOUT_REDIRECT_URL = 'login'
In the urls.py:
urlpatterns = [
path('', views.index, name='index'),
path('leicunnadmin/<str:user>', views.leicunnAdmin, name='leicunnadmin'),
]
The following is the code from the views.py script. My aim here was to check that the user is authenticated, get their username and append that to the URL. (The code)
#login_required
def leicunnAdmin(request, user):
username = None
User = get_user_model()
if request.user.is_authenticated:
username = request.user.username
get_logged_user = User.objects.get(username=user)
print('get_logged_user: '+username)
return render(request, 'leicunnadmin.html')
else:
return render(request, 'login')
Instead what I get when I log in is www.example.com/adminpage. When I type in the logged in username (www.example.com/adminpage/manuallytypedusername), it then redirects to the right page. Is there no way to automate this?
I am attempting to access a page in my application but I keep getting this error :
Page not found (404) Request Method: GET Request
URL: http://127.0.0.1:8000/nesting/Identity-nest/%7B%25%20url%20'nesting:Symptoms_nest_list'%7D
Using the URLconf defined in Identity.urls, Django tried these URL
patterns, in this order:
^admin/ ^Identity/
^nesting/ ^$[name='nesting']
^nesting/ ^Identity-nest/$[name='Identity_nest_list']
^nesting/ ^Symptoms-document/$[name='Symptoms_nest_list']
^$ [name='login_redirect']
The current URL, nesting/Identity-nest/{% url
'nesting:Symptoms_nest_list'}, didn't match any of these.
This is my main urls.py
from django.conf.urls import url, include
from django.contrib import admin
from Identity import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^Identity/', include('Identities.urls', namespace = 'Identities')),
url(r'^nesting/', include('nesting.urls', namespace = 'nesting')),
url(r'^$', views.login_redirect, name = 'login_redirect'),
]
This is my nesting urls.py
from django.conf.urls import url
from nesting.views import Identity_view, Identity_nest_list_view, Symptoms_document_view
from . import views
urlpatterns = [
url(r'^$', Identity_view.as_view(), name = 'nesting'),
url(r'^Identity-nest/$', Identity_nest_list_view.as_view(), name = 'Identity_nest_list'),
url(r'^Symptoms-document/$', Symptoms_document_view.as_view(), name = 'Symptoms_nest_list')
]
This is my views.py
class Symptoms_document_view(TemplateView):
model = Symptoms
template_name = 'nesting/Symptoms_list.html'
def get(self, request):
form = Symptom_Form()
Symptoms_desc = Symptoms.objects.all()
var = {'form':form, 'Symptoms_desc':Symptoms_desc}
return render(request, self.template_name, var)
def post(self, request):
form = Symptom_Form(request.POST or None)
Symptom_content = None
if form.is_valid():
Symptoms_description = form.save(commit = False)
Symptoms_description.user = request.user
Symptoms_description.save()
Symptoms_content = form.cleaned_data['Symptoms_description']
form = Symptom_Form()
redirect('nesting:nesting')
var = {'form': form, 'Symptoms_content': Symptoms_content}
return render(request, self.template_name, var)
This is the line in the HTML template that is the link the Symptoms_document_view view
<li class = "list-group-item"><a class = "nav-link" href="{%url 'nesting:Symptoms_nest_list'%}">{{Identity.First_Name}} {{Identity.Last_Name}} </a> <p>NIS: {{ Identity.NIS }}</p></li>
You need spaces around the url tag in your template:
href="{% url 'nesting:Symptoms_nest_list' %}">
Django's template parser is pretty basic and won't recognise a tag without the spaces.
Currently, im trying to make it so that I can complete a question on a page then when it's submitted to the database the next page will load. furthermore, every time I point it towards the templates folder it is piggybacking off the original one meaning that it can't find the new HTML page.
My idea is that when question1 is completed it will link to question2 where the def question2 code will execute and so on. But the forms won't display correctly and I believe it is due to the def question2 not running correctly.
def question1(request):
question_form1 = QuestionForm1()
if request.method == 'POST':
form = QuestionForm1(request.POST)
if form.is_valid():
form.save() # saves to database
return HttpResponse('question2.html')
else:
return render(request, 'music/failed.html')
return render(request, 'music/question1.html', locals())
def question2(request):
question_form2 = QuestionForm2()
if request.method == 'POST':
form2 = QuestionForm2(request.POST)
if form2.is_valid():
form2.save() # Saves to database
return render(request, 'music/question3.html', locals())
else:
return render(request, 'music/failed.html')
return render(request, 'music/question2.html', locals())
Edit:Added Urls.py
from django.conf.urls import url
from . import views
app_name = 'music'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^register/$', views.register, name='register'),
url(r'^login_user/$', views.login_user, name='login_user'),
url(r'^logout_user/$', views.logout_user, name='logout_user'),
url(r'^question1/$', views.question1, name='question1'),
url(r'^question2/$', views.question2, name='question2'),
]
from django.http import HttpResponseRedirect
from django.urls import reverse
# delete following line
return HttpResponse('question2.html')`
# replace with this one
return HttpResponseRedirect(reverse('view_name_here'))
# or if you are using any namespaces for your url
return HttpResponseRedirect(reverse('namespace:view_name_here'))