django 2.1 HTML form submitting to db error - django

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.

Related

Django cant return a class based view user id

My goal is to update the view using ajax. when the user enters a value in those 3 fields and save those fields to the database with for this user.
I have a user model with 3 text field as follow
class Q3Sign(models.Model):
title = models.CharField(max_length =255,blank =True)
title2 = models.CharField(max_length =255, blank = True)
title3 = models.CharField(max_length =255,blank =True)
user = models.ForeignKey(User, on_delete=models.CASCADE )
class Meta:
db_table = "Q3sign"
and my view is as fellow, I am getting the following error when I try to populate the fields.
django.db.utils.IntegrityError: NOT NULL constraint failed: Q3sign.user_id
class Createcourse(generic.CreateView):
model = Q3Sign
fields = ['title','title2','title3']
template_name = 'Q3canA/create_course.html'
success_url = reverse_lazy('create_course')
def create_course(self, request):
members = Q3Sign.objects.all()
return render (request,'Q3canA/create_course.html' , {'members':members})
def insert(request):
member = Q3Sign(title=request.POST['title'], title2=request.POST['title2'],
title3=request.POST['title3'], user=request.POST['user.id'])
member.save()
return redirect('create_course')
and here is my html
<div class="container">
<h2>Courses</h2>
<form method=post>
{% csrf_token %}
{{ form.as_p}}
<input type="submit" value="Create course" />
</form>
</div>
<form method="post">
{% csrf_token %}
<div class="form-inline">
<label>Course 1</label>
<input type="text" id="title" name="title" class="form-control"/>
</div>
<br />
<div class="form-inline">
<label>Course 2</label>
<input type="text" id="title2" name="title2" class="form-control"/>
<label>Course 3</label>
<input type="text" id="title3" name="title3" class="form-control"/>
</div>
<br />
<div class="col-md-4"></div>
<div class="col-md-4 form-group">
<button type="button" class="btn btn-primary form-control" id="submit">Submit</button>
</div>
</form>
<hr style="border-top:1px solid #000; clear: both;" />
<table class"table table-bordered">
<thead class = "alert-warning">
<tr>
<th>Course 1</th>
<th>Course 2</th>
<th>Course 3</th>
</tr>
</thead>
<tbody>
{% for member in members %}
<tr>
<td></td>
<td>{{member.user.id}}</td>
<td>{{member.title}}</td>
<td>{{member.title2}}</td>
<td>{{member.title3}}</td>
</tr>
{% endfor%}
</tbody>
</table>
{% endblock %}
Update now the fields disappeared :
Here is my URLs
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.home, name='home'),
#Auth
path('signup', views.Signup.as_view(), name = 'signup'),
path('login', auth_view.LoginView.as_view(), name = 'login'),
path('logout', auth_view.LogoutView.as_view(), name = 'logout'),
#Q3Course
path('createcourse',views.Createcourse.as_view(), name = 'create_course'),
url(r'^create_course', views.Createcourse.createcourse, name='create_course'),
]
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
thanks to #Fifon the code now working.
The only issue I need to understand is why the if statement is not working.
if the fields are empty or if it contains a test it still saves it in the database and not raising the alert in the if clause?
$(document).ready(function(){
$('#submit').on('click', function(){
$title = $('#title').val();
$title2 = $('#title2').val();
$title3 = $('#title3').val();
$user = $('#user').val();
if($title.toLowerCase().indexOf('test') == -1 || $title2 == "" || $title3 == "" || $user = ""){
alert("Please complete field");
}else{
$.ajax({
type: "POST",
url: "/create_course",
data:{
title: $title,
title2: $title2,
title3: $title3,
user: $user,
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
success: function(){
alert('Save Data');
$('#title').val('');
$('#title2').val('');
$('#title3').val('');
$('#user').val('');
window.location = "/create_course";
}
});
}
});
});
Firstly, there is no need for your insert() method. As you have a CreateView, you should use this, which will handle creating your objects and inserting them into the database. You should make use of the form this CreateView provides for you, rather than manually creating HTML for the form. This will make your life easier and ensure proper validation takes place. Something like this:
<form method="POST" id="create-course-form">
{% csrf_token %}
{{ form.as_p}}
<input type="submit" value="Create course" />
</form>
Your HTML is a little bit confusing right now – there is a form rendered using the {{ form.as_p }} template tag, and a manually rendered form. Take care here.
In your AJAX call, you should submit the form data, to the URL associated with your CreateView. I can't see your urls.py, but for example:
$.ajax({
type: "POST",
url: "{% url 'course-create' %}",
data: $('#create-course-form').serialize(),
...
You also need to make sure the form doesn't get submitted with an ordinary POST request (you want to use AJAX), by using preventDefault():
$('#create-course-form').submit(function(e){
e.preventDefault();
...
Putting it all together, back in your Createcourse view, you should define the form_valid(self) method, so that you can add in the user info. As you are using AJAX, you need to return a JsonResponse. E.g.:
def form_valid(self, form):
if self.request.is_ajax():
self.object = form.save(commit=False)
self.object.user = request.user
self.object.save()
return JsonResponse({'success':True})
else:
return super(CreateView, self).form_valid(form)
You also need to handle the situation in which your form is invalid as follows:
def form_invalid(self, form):
if self.request.is_ajax():
return JsonResponse(form.errors, status=400)
else:
return super(CreateView, self).form_invalid(form)
Finally, you will need to handle the response in your JavaScript. Success doesn't necessarily mean the form was valid and the course was created. If there are errors, you will need to display them to the user.
Update: You have two URLs both called 'create_view'. Remove the second one. Everything can be done from the one CreateView (Createcourse). In order to still have access to 'members', define get_context_data() as follows:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["members"] = Q3Sign.objects.all()
return context

The NoReverseMatch error in Django updateView

I am writing and Update View for a model that I have created. The model is a Product Backlog Item. The UpdateView is unable to find a reverse match for my view.
The NoReverseMatch error is saying that Django cannot find a matching url pattern.
My code as below:
UpdatePBI View
class updatePBI(LoginRequiredMixin, UpdateView):
pk_url_kwarg = 'pbipk'
kwargs={'pk_url_kwarg': 'pbipk'}
model = PBI
fields = ['priority', 'summary', 'story_points', 'effort_hours']
login_url = '/accounts/login'
redirect_field_name = '/home'
template_name = 'backtrack/PBIdetail.html'
def dispatch(self, request, *args, **kwargs):
print(kwargs)
return super().dispatch(request, *args, **kwargs)
def get_success_url(self):
return "{}?all=0".format(reverse('pb', kwargs={'pk': self.kwargs['pk']}))
def get_object(self, queryset=None):
obj = get_object_or_404(self.model,pk=self.kwargs['pbipk'])
return obj
def form_valid(self, form):
PBIList = getPBIfromProj(self.kwargs['pk'], '0')
remove = []
priorityData = form.cleaned_data['priority']
if int(priorityData) < self.object.priority:
# Remove all PBI with priority higher than post data priority
# and lesser or equal than current PBI priority
for PBIObj in PBIList:
if PBIObj.priority < int(priorityData) or PBIObj.priority >= self.object.priority:
remove.append(PBIObj.priority)
PBIList = [
PBIObj for PBIObj in PBIList if PBIObj.priority not in remove]
# Increase each objects priority by one
for PBIObj in PBIList:
PBIObj.priority += 1
PBIObj.save()
else:
# Remove all PBI with priority higher than post PBI priority
# and lesser than and equal to Post data priority
for PBIObj in PBIList:
if PBIObj.priority <= self.object.priority or PBIObj.priority > int(priorityData):
remove.append(PBIObj.priority)
PBIList = [
PBIObj for PBIObj in PBIList if PBIObj.priority not in remove]
# Decrease each objects priority by one
for PBIObj in PBIList:
PBIObj.priority -= 1
PBIObj.save()
return super().form_valid(form)
model.py
from django.urls import reverse
# Create your models here.
class PBI(models.Model):
status = models.CharField(max_length=1,
choices=[("N", "Not Done"), ("P", "In Progress"), ("D", "Done")], default="N")
story_points = models.FloatField()
effort_hours = models.FloatField()
summary = models.TextField(default = None)
priority = models.IntegerField(default=0)
Project = models.ForeignKey('Project', on_delete=models.CASCADE, related_name='pbi')
def __str__(self):
return self.summary
class Meta:
db_table = "PBI"
verbose_name = 'PBI'
verbose_name_plural = 'PBIs'
class Project(models.Model):
name = models.CharField(max_length=256)
def __str__(self):
return self.name
class Meta:
db_table = "Project"
urls.py
from django.conf.urls import url
from backtrack import views
from django.shortcuts import redirect
urlpatterns = [
path('', lambda x: redirect('1/'),name='home'),
path('<int:pk>/', views.HomeView.as_view(),name = 'home-project'),
path('<int:pk>/pb/', views.ProductBacklogView.as_view(),name='pb'),
path('<int:pk>/pb/add/', views.AddPBI.as_view(),name='add'),
path('<int:pk>/pb/<int:pbipk>/update', views.updatePBI.as_view(),name='detail'),
path('<int:pk>/pb/<int:pbipk>/delete', views.DeletePBI.as_view(),name='delete')
]
Product Backlog Page
{% block content %}
<h1 class="page-header"><i class="fa fa-file"></i> Product BackLog</h1>
<div class="row placeholders"></div>
{% if data|length == 0 %}
<h4>There are no PBIs</h4>
{% endif %}
<h2 class="sub-header">
<div class="dropdown">
<button class="btn btn-light dropdown-toggle pull-left" type="button" data-toggle="dropdown" style="margin-bottom: 10px;">Filter By
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>Priority</li>
<li>Story Points</li>
<li>Effort Hours</li>
</ul>
<div class="btn-group btn-toggle">
<button class="btn btn-xs btn-primary active toggle">NOT DONE</button>
<button class="btn btn-xs btn-default toggle">ALL</button>
</div>
<button type="button" class="btn btn-light" style="margin-bottom: 10px;"><i class="fa fa-plus" id="A"></i>ADD</button>
<button type="button" class="btn btn-light" style="margin-bottom: 10px;"><i class="fa fa-times" id="A"></i>DELETE</button>
</div>
</h2>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th> </th>
<th>Priority</th>
<th>Summary</th>
<th>Status</th>
<th>Story Points</th>
<th>Cumulative Story Points</th>
<th>Effort hours</th>
<th>Cumulative Effort hours</th>
</tr>
</thead>
<tbody>
{% for PBI in data %}
<tr>
<td><input type="checkbox"></td>
<td>
{% if PBI.status == "N" %}
{{PBI.priority}}
{% else %}
--
{% endif %}
</td>
<td><a style="text-decoration: none; color: cornflowerblue;" href={% url 'detail' pk=1 pbipk=PBI.id %}>{{PBI.summary}}</a></td>
<td>
{% if PBI.status == "N" %}
Not Done
{% elif PBI.status == "P" %}
In Progress
{% else %}
Done
{% endif %}
</td>
<td>{{PBI.story_points}}</td>
<td>{{PBI.sum_story_points}}</td>
<td>{{PBI.effort_hours}}</td>
<td>{{PBI.sum_effort_hours}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<script>
$.urlParam = function (name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)')
.exec(window.location.search);
return (results !== null) ? results[1] || 0 : false;
}
$(document).ready(function () {
if($.urlParam('all') == '1'){
$(this).find('.toggle').toggleClass('active');
if ($(this).find('.btn-primary').length>0) {
$(this).find('.toggle').toggleClass('btn-primary');
}
}
var getUrl = window.location;
var baseUrl = getUrl.protocol + "//" + getUrl.host + getUrl.pathname;
$('.btn-toggle').click(function(){
console.log($.urlParam('all') == '0')
if($.urlParam('all') == '0')
window.location.replace(baseUrl + "?all=1");
else
window.location.replace(baseUrl + "?all=0");
})
});
</script>
{% endblock content %}
I am getting this error
NoReverseMatch at /home/1/pb/50/update
Reverse for 'detail' with keyword arguments '{'pk': 1, 'pbipk': ''}' not found. 1 pattern(s) tried: ['home/(?P<pk>[0-9]+)/pb/(?P<pbipk>[0-9]+)/update$']
Update
I have found that the error is because I am setting the form action with the PBI.id but the Update view is not passing a PBI to my template. How do I fix this?
Okay. I found what I was doing wrong. I have to override the get_context_data() function of the template view mixin and pass the PBI in the context after calling super().get_context_data(form).

How get multiple BooleanFields in a form using Django

I have a form in my site to get a report about some "collective payment". It has 3 main field: Value, date of payment and who paid.
The field "who paid" is a table containing the name of all users and a checkbox.
Currently I'm looping over all users, adding their full names to the table with a single checkbox. But I don't know how to get this data in my form associating it with each user name (just the text).
How can I get multiple BooleanFields in my form ? Is there a way of associate each BooleanField with an user's name?
model.py
from django.db import models
#created_date attibute needs it
from django.utils import timezone
# This Model is a super class "Financial Transaction"
class GroupTransaction(models.Model):
name = models.CharField(max_length=257, default='')
who_paid = models.CharField(max_length=257, default='')
value = models.DecimalField(max_digits=6, decimal_places=2)
justification = models.CharField(max_length=257, default='')
created_date = models.DateTimeField(default=timezone.now)
date = models.CharField(max_length=257, default='')
receipt = models.FileField(upload_to='comprovantes', blank=True, null=True)
its_type = models.CharField(max_length=257, default='')
def __str__(self):
#INCOMPLETOreturn "%s fez a movimentação financeira de %d para %s no dia " % (self.name, self.restaurant)
return "%s - %s" % (self.name , self.who_paid)
view.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from deposit.forms import DepositForm,MonthlyDepositForm
from django.contrib.auth.models import User
# Create your views here.
#login_required
def deposito(request):
if request.method == 'POST':
form = DepositForm(request.POST, request.FILES)
if form.is_valid():
form.save()
HttpResponseRedirect('/historico/')
else:
print (str(form.errors.as_data()))
else:
form = DepositForm()
groupForm = MonthlyDepositForm()
return render(request, 'shell/app_shell.html', {
'is_deposit' : True,
'title' : 'Deposit',
'transaction' : form,
'groupTransaction' : groupForm,
'users': User.objects.all()
})
form.py
class MonthlyDepositForm(forms.ModelForm):
value = forms.DecimalField()
date = forms.CharField(widget=forms.TextInput(attrs={
'class':'datepicker picker__input',
'readonly':'',
'tabindex':'54',
'aria-haspopup':'True',
'aria-expanded':'false',
'aria-readonly':'false',
'aria-owns':'birthdate_root'
}))
who_paid = forms.BooleanField()
its_type = forms.CharField(widget=forms.HiddenInput(attrs={'readonly':True}),
initial='Deposito Mensal')
class Meta:
model = GroupTransaction
fields = ('value', 'date','who_paid','its_type')
template.html:
<form class="col s12">
{% csrf_token %}
{{ groupTransaction.its_type }}
<div class="row"></div>
<!-- Nome do evento -->
<div class="row">
<div class="input-field col s6">
<!-- <input id="nome_evento" type="number" value="10" step="any" min="0.05" max="400" class="validate" required> -->
{{ groupTransaction.value }}
<label for="nome_evento">Value</label>
</div>
<div class="input-field col s6">
<!-- <input type="text" class="datepicker picker__input" readonly="" tabindex="54" aria-haspopup="true" aria-expanded="false" aria-readonly="false" aria-owns="birthdate_root" required> -->
{{ groupTransaction.date }}
<label for="data-mensal" data-error="Data inválida">Date</label>
</div>
</div>
<!-- Petianos que irão para o evento -->
<table class="striped">
<thead>
<!-- Cabeçalho tabela -->
<tr>
<th>Who Paid</th>
<th>
<div class="switch">
<b class="center-align">Default</b>
<label>
<input type="checkbox">
<span class="lever"></span>
</label>
</div>
</th>
</tr>
<!-- ============= -->
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ user.get_full_name }}</td>
<td>
<div class="switch">
<label>
<!-- <input type="checkbox"> -->
{{ groupTransaction.who_paid }}
<span class="lever"></span>
</label>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="row"></div>
<div class="row"></div>
<!-- Botão de registrar saque (submit) -->
<div class="row">
<button class="btn waves-effect waves-light col s6 m3 offset-s6 offset-m9 blue" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</div>
</form>
How the form is:
You need to make who_paid a ManyToManyField(User). Then in the form you can set its widget like this:
class Meta:
model = GroupTransaction
fields = ('value', 'date','who_paid','its_type')
widgets = {
'who_paid': forms.CheckboxSelectMultiple(),
}
That will give you the right structure. Then you can render it manually if you want to change the display.

How to copy register with DetailView and get pk (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)

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% }