How to copy register with DetailView and get pk (Django) - django

Consider my template:
entry_detail.html
<form class="navbar-form navbar-right" action="." method="get">
<!-- add -->
<!-- <p name="filter_link" class="pull-right">Produtos em baixo estoque</p> -->
<a name="new_customer" href="{% url 'proposal_list' %}">
<button type="button" class="btn btn-primary">
<span class="glyphicon glyphicon-plus"></span> Criar Orçamento
</button>
</a>
</form>
And considerer my view:
views.py
class EntryDetail(DetailView):
template_name = 'core/entry/entry_detail.html'
model = Entry
def create_proposal(self, employee_pk=8):
if 'new_customer' in self.request.GET:
employee = Employee.objects.get(pk=employee_pk)
num_last_proposal = NumLastProposal.objects.get(
pk=1) # sempre pk=1
entry = Entry.objects.get(pk=self.request.GET[self.id])
obj = Proposal(
num_prop=num_last_proposal.num_last_prop + 1,
type_prop='R',
category=entry.category,
description=entry.description,
work=entry.work,
person=entry.person,
employee=employee,
seller=entry.seller,
)
obj.save()
entry.is_entry = True
entry.save()
num_last_proposal.num_last_prop += 1
num_last_proposal.save()
Question: How to make this work this. How to get entry.pk in DetailView for use in
entry = Entry.objects.get(pk=self.request.GET[self.id])
In manage.py shell its work
shell_create_proposal.py
from core.models import Entry, Proposal, Employee, NumLastProposal
employee = Employee.objects.get(pk=8)
num_last_proposal = NumLastProposal.objects.get(pk=1)
entry = Entry.objects.get(pk=1)
obj = Proposal(
num_prop=num_last_proposal.num_last_prop + 1,
type_prop='R',
category=entry.category,
description=entry.description,
work=entry.work,
person=entry.person,
employee=employee,
seller=entry.seller,
)
obj.save()
entry.is_entry = True
entry.save()
num_last_proposal.num_last_prop = num_last_proposal.num_last_prop + 1
num_last_proposal.save()

Specify the pk in the url and the detail view should handle it for you
url(r'^yourview/(?P<pk>\d+)/' , YourDetailView.as_view() , name='your_view_name' ),
Look at the get_object method here:
http://ccbv.co.uk/projects/Django/1.8/django.views.generic.detail/DetailView/
it gets the pk as follows:
pk = self.kwargs.get(self.pk_url_kwarg, None)

Related

why my django slug is not working properly

I want to allow user to search in database for the topic. and show the topic name in url.
I already created slug field in database but when i am trying to fetch the data from the database the url is not showing correctly.
url is showing:
http://127.0.0.1:8000/topic/<slug:topicname>/
what I want to show:
http://127.0.0.1:8000/topic/introduction-to-python/
My urls.py file
from django.urls import path
from . import views
urlpatterns = [
path('', views.apphome),
path('topic/<slug:topicname>/', views.searchtopic, name = 'searchtopic'),
]
My model for the project
class blogposts(models.Model):
topic = models.CharField(max_length = 200)
slug = models.SlugField(max_length = 150, null=True, blank = True)
post = models.TextField(max_length = 500)
def __str__(self):
return self.topic
This is my view
def searchtopic(request,topicname):
if request.method == 'POST':
topicname = request.POST.get('searchtopicname')
mypost = mypostlist.objects.filter(slug = topicname)
context = {
'mypost':mypost,
}
return render(request, 'blog/result.html',context)
My form for searching topic
<form action="topic/<slug:topicname>/" method="POST">
{% csrf_token %}
<input type="search" placeholder="Search topics or keywords" name="searchtopicname">
<button type="submit">Search</button>
</form>
You can use 'GET' method insted of 'POST'
replace form with:
<form action="{%url 'searchtopic' %}" method="GET">
{% csrf_token %}
<input type="search" placeholder="Search topics or keywords" name="searchtopicname">
<button type="submit">Search</button>
</form>
replace urls.py:
urlpatterns = [
path('', views.apphome),
path('topic/', views.searchtopic, name = 'searchtopic'),
]
replace views:
def searchtopic(request):
if request.method == 'GET':
topicname = request.GET['searchtopicname']
mypost = mypostlist.objects.filter(slug = topicname)
context = {
'mypost':mypost,
}
return render(request, 'blog/result.html',context)

How to save class results in django cache and use it in other class

Html search file
<div class="content-section">
<h1 class="mb-3">{{ user.username }}</h1>
<form method="GET" action="{% url 'doctor:search' %}">
<input name ="q" value="{{request.GET.q}}" placeholder="search..">
<button class="btn btn-success" type="submit">
Search
</button>
</form>
</div>
VIEWS.py i like to save 'query' value in cache and use it later in different views.py class
class SearchResultsView(ListView):
model = User
template_name = 'all_users/doctor/search.html'
def get_queryset(self): # new
*query = self.request.GET.get('q')*
object_list = User.objects.filter(Q(username__icontains=query))
return object_list
You can use render_to_response for returning multiple objects like that:
def get_queryset(self): # new
query = self.request.GET.get('q')
object_list = User.objects.filter(Q(username__icontains=query))
another_object_list = Doctor.objects.filter(Q(username__icontains=query))
context = {
'object_list': object_list,
'another_object_list': another_object_list
}
return render_to_response('search.html', context)
And you can call this context in your template:
{{ object_list }}
{{ another_object_list }}

django 2.1 HTML form submitting to db error

i am trying to post the data from html form to my db, however i get the error that the url does not exist. what am trying to do is later on turn the test form into dynamic add fields using HTML and Jquery rather than using formset for ease UI designing and handle it in dango back end.
also note that am assigning the foreign key which is the startup_name by passing it through the url to test view.
the code is as following:
models.py:
class Startup(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
startup_name = models.CharField('Startup Name', max_length = 32, null = False, blank = False)
class Team (models.Model):
str_team = models.ForeignKey(Startup, on_delete=models.CASCADE)
name = models.CharField('Name',max_length = 32, null = False, blank = False)
position = models.CharField('Title/Position', max_length = 32, null = False, blank = False)
qualification = models.CharField('Degrees/Qualifications', max_length=32,null=False,blank=False)
views.py:
def create_startupform(request):
if request.method == 'POST':
form = startupform(request.POST)
if form.is_valid():
result = form.save(commit=False)
result.author = request.user
result.save()
return redirect('test', startup_id = result.pk)
else:
form = startupform()
return render(request, 'str_name.html', {'form': form})
def test (request, startup_id):
e = Startup.objects.values('startup_name')
if request.method == 'POST':
na = request.POST.get("name")
po = request.POST.get("position")
qu = request.POST.get("qualification")
ref = Team(name = na, position = po, qualification = qu, str_team = e)
ref.save()
return redirect('str_dashboard')
return render(request, 'test.html')
forms.py:
class startupform(forms.ModelForm):
class Meta:
model = Startup
fields = ('startup_name',)
widgets = {
'startup_name': forms.TextInput(attrs = {'class':'form-control'}),
}
def clean(self):
super ( ).clean ( )
startup_name = self.cleaned_data.get ( 'startup_name' )
startup_qs = Startup.objects.filter ( startup_name = startup_name )
if startup_qs.exists ( ):
raise forms.ValidationError ( 'This Startup Already Exist!' )
test.html:
<form id="add-extra" class="form" method="post" action = "{% url 'test' %}">{% csrf_token %}
<div class="form-row profile-row">
<div class="col-md-8 col-lg-12">
<hr />
<h4>Startup Core Team</h4>
<div class="form-row">
<div class="col-sm-12 col-md-6 col-lg-12">
<div class="form-group">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Qualification</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="form-control" type="text" name="candidate_name" /></td>
<td><input class="form-control" type="text" name="position"/></td>
<td><input class="form-control" type="text" name="qualification"/></td>
<td><button class="btn btn-primary d-lg-flex align-items-lg-center" type="button" style="margin-top: 4px;margin-left: 15px;background-color: rgb(24,130,7);"><i class="fas fa-plus"></i></button></td>
</tr>
<tr></tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<hr />
<div class="form-row">
<div class="col-md-12 content-right"><button class="btn btn-primary text-center border rounded d-lg-flex justify-content-lg-end align-items-lg-center form-btn" type="post" style="margin-left: 1040px;padding: 6px;">SAVE </button></div>
</div>
</div>
</div>
URLS:
from django.urls import path
from . import views
urlpatterns = [
path ( 'str_dashboard/' , views.str_dashboard , name = 'str_dashboard' ),
path ( 'create_startupform/' , views.create_startupform, name = 'create_startupform' ),
path('test/', views.test, name='test'),
]
Error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/test/
Using the URLconf defined in sourcing.urls, Django tried these URL patterns, in this order:
You are trying an url which is not in the urls.py:
urlpatterns = [
...
path('test/<int:startup_id>/', views.test, name='test'),
path('test/', views.test, name='test_base'), # add this
]
The url 'http://127.0.0.1:8000/test/' won't match because it would need to have 'startup_id' attached with your urls.py.
http://127.0.0.1:8000/test/1 would work.
If you do like i wrote above, make sure that your view is taking startup_id as optional. Or use another function for the call without startup_id.

UpdateView is missing a QuerySet Error

As of today, my UpdateView no longer works. Whenever I select the icon to edit an item I get the following error:
EntryUpdate is missing a QuerySet. Define EntryUpdate.model, EntryUpdate.queryset, or override EntryUpdate.get_queryset().
I have never had to have a QuerySet within my UpdateView before, so I am unsure why it is asking for one now. My understanding of the Generic UpdateView is that the self-query was built in, but I may be wrong.
Any help would be much appreciated.
views.py
class IndexView(generic.ListView):
template_name = 'argent/index.html'
# paginate_by = 10
def get_queryset(self):
return Entry.objects.all()
def get_context_data(self, **kwargs):
ctx = super(IndexView, self).get_context_data(**kwargs)
# TODAY'S ENTRY
ctx['entry_qs'] = Entry.objects.filter(date=today_date)
# CURRENT SAVINGS TOTALS
ctx['savings_qs'] = Savings.objects.filter(id=1)
# MONTHLY TOTALS
# November
ctx['November16_qs'] = MonthYear.objects.filter(month='November')
# December
ctx['December16_qs'] = MonthYear.objects.filter(month='December')
# January
ctx['January17_qs'] = MonthYear.objects.filter(month='January')
# February
ctx['February17_qs'] = MonthYear.objects.filter(month='February')
# March
ctx['March17_qs'] = MonthYear.objects.filter(month='March')
# # April
# ctx['April_qs'] = MonthYear.objects.filter(month='April')
# # May
# ctx['May_qs'] = MonthYear.objects.filter(month='May')
return ctx
class DetailView(generic.DetailView):
model = Entry
template_name = 'argent/detail.html'
#
# def get_context_data(self, **kwargs):
# ctx = super(DetailView, self).get_context_data(**kwargs)
# ctx['savings_qs'] = Savings.objects.filter(id=1)
# return ctx
class EntryCreate(CreateView):
form_class = EntryForm
template_name = 'argent/entry_form.html'
def form_valid(self, form):
if form.save(self):
# total_euros_spent
sum_euros = Entry.objects.aggregate(s=Sum('euros_sum')).get('s')
sum_euros_f = "{0:.2f}".format(sum_euros)
# total_dollars_spent
sum_dollars = Entry.objects.aggregate(s=Sum('dollars_sum')).get('s')
sum_dollars_f = "{0:.2f}".format(sum_dollars)
# total_sum
sum_savings = Entry.objects.aggregate(s=Sum('daily_savings_dollars')).get('s')
sum_format = "{0:.2f}".format(sum_savings)
# total_sum_format
sum_abs_savings = Entry.objects.aggregate(s=Sum('daily_savings_dollars')).get('s')
absolute = abs(sum_abs_savings)
sum_abs = "{0:.2f}".format(absolute)
Savings.objects.filter(id=1).update(total_savings=sum_format, total_savings_display=sum_abs,
total_spent_dollars=sum_dollars_f, total_spent_euros=sum_euros_f)
return super(EntryCreate, self).form_valid(form)
else:
return self
class EntryUpdate(UpdateView):
form_class = EntryForm
template_name = 'argent/entry_form.html'
def form_valid(self, form):
if form.save(self):
# total_euros_spent
sum_euros = Entry.objects.aggregate(s=Sum('euros_sum')).get('s')
sum_euros_f = "{0:.2f}".format(sum_euros)
# total_dollars_spent
sum_dollars = Entry.objects.aggregate(s=Sum('dollars_sum')).get('s')
sum_dollars_f = "{0:.2f}".format(sum_dollars)
# total_sum
sum_savings = Entry.objects.aggregate(s=Sum('daily_savings_dollars')).get('s')
sum_format = "{0:.2f}".format(sum_savings)
# total_sum_format
sum_abs_savings = Entry.objects.aggregate(s=Sum('daily_savings_dollars')).get('s')
absolute = abs(sum_abs_savings)
sum_abs = "{0:.2f}".format(absolute)
Savings.objects.filter(id=1).update(total_savings=sum_format, total_savings_display=sum_abs, total_spent_dollars=sum_dollars_f, total_spent_euros=sum_euros_f)
return super(EntryUpdate, self).form_valid(form)
else:
return self
urs.py
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'entry/detail/(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'entry/add/$', views.EntryCreate.as_view(), name='entry-add'),
url(r'entry/update/(?P<pk>[0-9]+)/$', views.EntryUpdate.as_view(), name='entry-update'),
]
template
{% if object_list %}
{% for Entry in object_list %}
<div class="col-md-3 col-sm-4 col-xs-6">
<div class="thumbnail" style="background: #ebebeb" >
<h3 align="center" style="font-weight: bold; color: #337ab7;">{{ Entry.date }}</h3>
<div class="caption">
<h4 align="center" style="color: #FF5A09">€{{ Entry.euros_sum }}
<!-- View Details -->
<a href="{% url 'argent:detail' Entry.id %}"><button type="button" class="btn btn-link btn-lg">
<span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span>
</button></a>
<!-- Update -->
<a href="{% url 'argent:entry-update' Entry.id %}"><button type="button" class="btn btn-link btn-lg" style="padding: 0">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
</button>
</a>
</h4>
</div>
</div>
</div>
{% endfor %}
{% endif %}
SOLUTION:
Fixed it. It turns out I accidentally deleted model=Entry from the view. Once I added it back, it started to work again.
class EntryUpdate(UpdateView):
model = Entry
form_class = EntryForm
template_name = 'argent/entry_form.html'
def form_valid(self, form):
....

Can't load a form in Django

I need to make a simple form. I can't understand why I don't see it. When I press a button which must show it, I see POST not GET request in my console. Which is not correct. Here is code:
form:
class DeviceAddForm(django.forms.Form):
name = django.forms.CharField(widget = django.forms.TextInput(attrs = {'size':'2','value':'1','class':'device',}))
device_slug = django.forms.CharField(widget = django.forms.HiddenInput())
model_name = django.forms.CharField(widget = django.forms.TextInput(attrs = {'size':'2','value':'1','class':'device',}))
platfrom = django.forms.ComboField(widget = django.forms.CheckboxInput())
sdk = django.forms.ComboField(widget = django.forms.CheckboxInput())
def __init__(self,request=None,*args,**kwargs):
self.request = request
super(DeviceAddForm,self).__init__(*args,**kwargs)
def clean(self):
if self.request:
if not self.request.session.test_cookie_worked():
raise django.forms.ValidationError("Cookies must be enabled")
return self.cleaned_data
saving data:
DEVICE_ID_SESSION_KEY = 'device_id'
def _device_id(request):
if request.session.get(DEVICE_ID_SESSION_KEY,'') == '':
request.session[DEVICE_ID_SESSION_KEY] = _generate_device_id()
return request.session[DEVICE_ID_SESSION_KEY]
def _generate_device_id():
device_id = ''
chars = '0123456789'
device_id_len = 5
for i in range (device_id_len):
device_id +=chars[random.randint(0,len(chars)-1)]
def get_device(request):
return Device.objects.filter(device_id= _device_id(request))
def add_device(request):
postdata = request.POST.copy()
device_slug = postdata.get('device_slug','')
name = postdata.get('name','')
model_name = postdata.get('model_name','')
platform = postdata.get('platform','')
sdk = postdata.get('SDK','')
d = get_list_or_404(Device, slug = device_slug)
dev = Device()
# dev = d
dev.name = name
dev.model_name = model_name
#dev.sdkID
#dev.plID
dev.id = _device_id(request)
dev.save()
view:
#csrf_exempt
def show_device(request, template_name = "onep_web/deviceForm.html"):
d = get_list_or_404(Device,slug = DeviceAddForm.device_slug)
if request.method == 'POST':
postdata = request.POST.copy()
form = DeviceAddForm(request,postdata)
if form.is_valid():
device.add_device(request)
if request.session.test.cookie_worked():
request.session.delete_test_cookie()
url = urlresolvers.reverse('show_device')
return HttpResponseRedirect(url)
else:
form = DeviceAddForm(request=request, label_suffix=':')
form.field['device_slug'].widget.attr['value'] = DeviceAddForm.device_slug
request.session.set_test_cookie()
# return render_to_response(template_name, locals(),csrf(context_instance RequestContext(request)))
return render_to_response(template_name, {'form':form})
urls:
urls form the app
urlpatterns = patterns('onep_web.views',
(r'^$','show_device',{'template_name':'onep_web/deviceForm.html'},'show_device'))
and some more urls:
urls.py from project
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
#url(r'^$', 'welcome_page.home', name='home'),
#url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^welcome_page/', 'one_web.views.welcome_page'),
url(r'^onep_web/', include('onep_web.urls')),
url(r'^device_page/', 'one_web.views.device_page'),
url(r'^configuration_page/', 'one_web.views.configuration_page'),
url(r'^log_page/', 'one_web.views.log_page'),
)
templates :
it's one from which I call the form
<title>OnePK Web Tool - {%block page %}{% endblock %}</title>
</head>
<body>
<div >
<br>
<div> Welcome to OnePK web-tool</div>
</div>
<form >
<br>
<br>
<br>Username:
<input type="text" name="Username">
<br>Password:
<input type="password" name="pwd">
<br>
<br>
{% block content %}
<h4>List of devices and IP addresses:</h4>
<table border="1">
<tr>
<td>Dev1</td>
<td>Dev2</td>
<td>Dev3</td>
<td>Dev4</td>
</tr>
<tr>
<td>{{a.getIP}}</td>
<td>{{a.getIP}}</td>
<td>{{a.getIP}}</td>
<td>{{a.getIP}}</td>
</tr>
</table>
{% endblock %}
<br>
<br>
<br>
<button type="button" onclick="ping()">Ping elenent</button>
<script>
function ping()
{
}
</script>
<br>
<br>
<label>Connection status</label>
<br>
<button type="button" onclick="openDev()">Connect to element</button>
<script>
function openDev()
{
window.open("p2t.html");
}
</script>
</form>
<form method = "post" action = "." class = "device">
{% csrf_token %}
{{form.as_p}}
<br />
<input type="submit" value="Add a new network device" name="submit" alt="Add a new network device"/>
</form>
<div class="cb"></div>
</body>
</body>
</html>
deviceForm:
{ % extends "p1t.html" % }
{ %block content% }
<h1> Add a new Device </h1>
Device info: { { device_data} }
<label for="name">Name</label><input type="text" id = "name" value = ""/>
{ %endblock% }