Reputation: 13
I am learning Django, and I am sure the solution is very simple but I can't find it;
I have a model "profile" that needs to be filtered by a request. Requests and answers need to be kept in database. But I don't want the user to see all the profiles at any moment.
So I wrote two models : the first one contains the requests (MyRequest), the second the potential answers (Profile). Profiles are created importing csv in Django admin.
I wrote a code that is working fine BUT I can't figure out how to send my response in a template to use all the customizations and securities as csrf_token.
Currently it is showing the response in the same url than the request and I am blocked there
I have tried to use get_succes_url with HttpResponseRedirect, usually I can do such things using (?P\d+)/$' in the success url but it doesn't work maybe because the two models don't share any key? I have tried to put and in success url but I think I did something wrong
"""Models"""
class Profile(models.Model):#probgerme probpvt probservice probATCDpvt probATCDbmr probNB
profname= models.CharField(max_length=20)
bq = models.ForeignKey(Bq, on_delete=models.CASCADE)#, blank=True
test1 = models.CharField(max_length=100)
test2 = models.CharField(max_length=100)
test3 = models.CharField(max_length=100)
class MyRequest(models.Model):#probgerme probpvt probservice probATCDpvt probATCDbmr probNB
reqname = models.CharField(max_length=20)
bq = models.ForeignKey(Bq, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL,default=0, related_name="user2")
test1 = models.CharField(max_length=100)
test2 = models.CharField(max_length=100)
"""Forms"""
class MyRequestCreateForm(forms.models.ModelForm):
class Meta:
model = MyRequest
fields = ('bq','test1','test2')
def save(self, *args, **kwargs):
myrequest = super().save(*args, **kwargs)
myrequest.save()
"""URL """
url(r'^essai_create/$', views.MyRequestCreateView.as_view(), name='my_request'),
"""Views"""
class MyRequestCreateView(LoginRequiredMixin, generic.CreateView):
form_class = MyRequestCreateForm
model = MyRequest
def get_queryset(self):
queryset = super().get_queryset().filter(user=self.request.user)
return queryset
def get_form(self, form_class=None):
form = super().get_form(form_class)
form.fields['test1'].required = True
return form
def form_valid(self, form):
form.instance.user = self.request.user
self.object = form.save()
data = form.cleaned_data
test1 = data['test1']
test2 = data['test2']
print('data',data)
try:
Profile.objects.get(test1 = test1, test2 = test2 )
tested3= Profile.objects.get(test1 = test1, test2 = test2).test3.split(',')
except ObjectDoesNotExist:
tested3 = ['nothing']*5
reponse = "Votre requête : test1 = " + test1 + ", test2 = " + test2 + "<br>val1, "+tested3[0] + "<br>val2, "+tested3[1] + "<br>val3 " + tested3[2]+ "<br>val4, " + tested3[3]
return HttpResponse(reponse)
"""Template myrequest_form.html"""
{% extends 'base2.html' %}
{% load bootstrap %}
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
<div class="container ">
<form method="POST" enctype="multipart/form-data" id="project-form">
{% csrf_token %}
<form method="post" >
{% csrf_token %}
{{ form.bq|as_crispy_field }}
<br>
<div class="col-6">
Information sur le test1 {{ form.test1 }} <br>
</div>
<br>
<div class="col-6">
Information sur le test2 {{ form.test2 }}<br>
</div>
<br>
<br><br>
<button id = "submitRequest" aria-pressed="true" class="btn btn-primary active" onclick="showPleaseWait()" type="submit" >Check for best answer</button>
</form>
</form>
</div>
{% endblock %}
Currently after clicking "Check for best answer" button in the template opened in http://localhost:8000/myapp/essai_create/, this same url
http://localhost:8000/myapp/essai_create/
shows:
Votre requête : test1 = nouveau, test2 = Rouge
val 1, 7
val 2, 12
val 3, 4
val 4, 5
Upvotes: 1
Views: 2174
Reputation: 13
@Daniel Roseman solution (creating a simple ProfileDetail view) is great! I only had to change the path (I am using Django 2.11) for
url(r'profiledetail/(?P<pk>\d+)$', views.ProfileDetail.as_view(), name='profile')
and needed to change the createview
def form_valid(self, form):
form.instance.user = self.request.user
self.object = form.save()
data = form.cleaned_data
test1 = data['test1']
test2 = data['test2']
profile=ProbasProfile.objects.get(test1 = test1, test2=test2)
return redirect('profile', pk=profile.id)
then in the new template created for the answer
{{profile.test1}}{{profile.test2}}{{profile.test3}}
and of course the class ProfileDetail as he wrote it
Upvotes: 0
Reputation: 600041
I'm still finding it quite hard to understand what you want, unfortunately. Perhaps what you want is to find the Profile matching the submitted data, and then redirect to it? In which case you need to do that redirect inside form_valid
, and define a DetailView for Profile that you redirect to. So:
class MyRequestCreateView(LoginRequiredMixin, generic.CreateView):
...
def form_valid(self, form):
form.instance.user = self.request.user
obj = form.save()
try:
profile = Profile.objects.get(test1=obj.test1, test2=obj.test2)
return redirect('profile', pk=profile.id)
except Profile.DoesNotExist:
return redirect('/') # or wherever
class ProfileDetail(LoginRequiredMixin, generic.DetailView):
model = Profile
and the URL:
path('profile_detail/<int:pk>', ProfileDetail, name='profile')
Upvotes: 1