google app engine render check box from database model - python

I am developing my first Google App Engine project and I think I am misunderstanding something fundamental about the database and form models. I have the following python code:
class RegData(db.Model):
title = db.StringProperty()
forename = db.StringProperty()
surname = db.StringProperty()
interest = db.StringListProperty(choices=['TV','COMPUTING','SOCCER'])
class RegForm(djangoforms.ModelForm):
class Meta:
model = RegData
What I want to do is have the form render the 'interest' property as a set of check boxes instead of a text area. Is this possible?
Thanks.

from django import forms as form
you must add the above module in models.py
models.py
interest=(
('Tv', 'TV'),
('Computing', 'COMPUTING'),
('Soccer', 'SOCCER'),
)
class RegData(db.Model):
title = db.StringProperty()
forename = db.StringProperty()
surname = db.StringProperty()
interest = db.StringListProperty()
class RegForm(djangoforms.ModelForm):
interest= form.CheckboxSelectMultiple(choices=interest)
class Meta:
model = RegData
RegData is the table in your database (entity) , RegForm is that the user will see this form on your page.
main.py
class ShowForm(webapp.RequestHandler):
def get(self):
show(self)
def post(self):
show(self)
def show(self):
get = self.request.GET
post = self.request.POST
data = models.RegData()
if post:
form = models.RegForm(data=post, instance=RegDate)
if form.is_valid():
entity = form.save(commit=False)
entity.put()
else:
form = models.RegForm(instance=RegDate)

Related

There is a way to get a value from views.py into nodels.py?(Django)

I'm making a little Django project of money management, I'm using a table layout, inside the tables there are many transactions. I have two SQL tables: "Table" and "Transactions" and I need that when I open the link of one specific table, I need to get just the items which were created in the table page.
Example:
I open 'table1' and inside it I create 'value1', 'value2','value4'
after, I open 'table2' and inside it I create 'value3' and 'value5'
after that, when I open the 'table1' page I need to show
'value1','value2' and 'value4'
and when I open 'table2', I need 'value3' and 'value5'
I wonder if there is a way to take the id of the table I'm inside in the moment and write it into the transactions form to make some kind of 'id', so I can filter the values by it id
Here are my files:
urls.py
from django.urls import path
import tables1.views as vw
urlpatterns = [
path('admin/', admin.site.urls, name = 'admin'),
path('mytables/', vw.mytables, name = 'mytables'),
path('',vw.home),
path('table/<int:pk>',vw.table, name = 'tableurl'),
path('newtable/',vw.newtable,name = 'newtable')
]
views.py
from .models import Table
from .forms import TableForm
def home(request):
now = {}
return render(request,'tables1/home.html',now)
def mytables(request):
data = {}
data['tables'] = Table.objects.all()
return render(request, 'tables1/mytables.html', data)
def table(request,pk):
form = TableForm(request.POST or None)
data = Table.objects.get(idd = pk)
print(data)
if form.is_valid():
form.save()
return redirect('mytables')
return render(request,'tables1/table.html',{'data':data, 'form':form}),pk
def newtable(request):
form = TableForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('mytables')
return render(request,'tables1/newtable.html',{'form':form})
models.py
from .views import table
class Table(models.Model):
idd = models.AutoField(primary_key=True, default= None)
name = models.CharField(max_length=100)
date = models.DateField(auto_now_add=True)
time = models.TimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'Tables'
def __str__(self):
return self.name
class Transacao(models.Model):
mod = models
date = models.DateTimeField()
desc = models.CharField(max_length=200)
value = models.DecimalField(max_digits=7,decimal_places=2)
obs = models.TextField(null=True,blank=True)
class Meta:
verbose_name_plural = 'Transacoes'
def __str__(self):
return self.desc
forms.py
from .models import Table
from .models import Transacao
class TableForm(ModelForm):
class Meta:
model = Table
fields = ['name']
class TransacaoForm(ModelForm):
class Meta:
model = Transacao
fields = ['desc','date','value','obs'] ```
From my understanding of your question, you want a relation between Table and Transaction, where each Table contains (possibly 0 or more) transactions. This is a many-to-one relation that can be done by a Foreign Key. Read more.
I modified your code and added the foreign key to it. By adding the foreign key field name to the form you can set the table for each transaction when you create it. And when you need to get the transactions for a table you can do table.transacoes. The name transacoes is defined in the related-name attribute of the foreign key.
models.py
from .views import table
class Table(models.Model):
idd = models.AutoField(primary_key=True, default= None)
name = models.CharField(max_length=100)
date = models.DateField(auto_now_add=True)
time = models.TimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'Tables'
def __str__(self):
return self.name
class Transacao(models.Model):
# Forein key defined here
table = models.FogeinKey(Table, related_name='transacoes')
# Also I don't know what this is, you probably don't need it
mod = models
date = models.DateTimeField()
desc = models.CharField(max_length=200)
value = models.DecimalField(max_digits=7,decimal_places=2)
obs = models.TextField(null=True,blank=True)
class Meta:
verbose_name_plural = 'Transacoes'
def __str__(self):
return self.desc
forms.py
from .models import Table
from .models import Transacao
class TableForm(ModelForm):
class Meta:
model = Table
fields = ['name']
class TransacaoForm(ModelForm):
class Meta:
model = Transacao
# table added here
fields = ['desc', 'date', 'value', 'obs', 'table']
I managed to solve my problem by instead of saving the form data automatically in database with "form.save()", i """manually""" got the data from form using form.cleaned_data for each one of the form fields and saved that data into database using Transaction.objects.create() so that i could save the pk variable into the transactions table with the name of "tableid", that way, the app could link the primary key of each table page and link it to the transactions registered inside that page.

Stuck on linking ManytoMany relationships with Modelform

I'm pretty new to Django and I am working on a project that currently requires the following:
I have two basic structures: a Project model and a TeamMember model- both related to each other through a ManytoMany relationship. Then I have an TMAssigned 'through' class. The team member will have many projects assigned to it over time.
I have a ModelFrom which creates a Project model through the creation of the form.
My question is, How do I link the team member to the newly created project upon the submission of the form?
Here is a bit of my model & form code:
TeamMember
class TeamMember(models.Model):
firstname = models.CharField(max_length=100, default= "First Name")
lastname = models.CharField(max_length=100, default= "Last Name")
fullname = models.CharField(max_length=100, default= "Full Name")
email = models.EmailField(max_length=254)
cellphone = PhoneNumberField(null=False, blank=False, unique=True)
numberofcases = models.IntegerField(max_length=10000, default=0)
#property
def fullnamefunc(self):
fullname = "{} {}".format(self.firstname, self.lastname)
return fullname
def __str__(self):
return self.fullname
Project
class Project(models.Model):
pursuitname = models.CharField(max_length=500)
datecreated = models.DateTimeField(auto_now=True)
bdmember = models.ManyToManyField('team.TeamMember')
Views.py
class bdFormView(TemplateView):
template_name = os.path.join(BASE_DIR, "templates/masterform/bdform.html")
def get(self,request):
form = bdForm()
return render (request, self.template_name, {'form': form})
def post(self, request):
form = bdForm(request.POST)
if form.is_valid():
print("form is valid")
project = form.save(commit=False)
project.save()
text = form.cleaned_data['briefcard']
Form.py
class bdForm(forms.ModelForm):
bdmemberlist = TeamMember.objects.all().order_by('lastname')
pursuitname = forms.CharField()
bdmember = forms.ModelChoiceField(queryset= bdmemberlist)
addbdteam = forms.ModelMultipleChoiceField(
queryset=TeamMember.objects.all().order_by('lastname'), widget=Select2MultipleWidget, required=False)
class Meta:
model = Project
fields = ['pursuitname','addbdteam','bdmember',]
def __init__(self, *args, **kwargs):
if kwargs.get('instance'):
initial = kwargs.setdefault('initial', {})
initial['projects'] = [t.pk for t in
kwargs['instance'].project_set.all()]
forms.ModelForm.__init__(self, *args, **kwargs)
def save(self, commit=True):
instance = forms.ModelForm.save(self, False)
old_save_m2m = self.save_m2m
def save_m2m():
old_save_m2m()
for project in self.cleaned_data['bdmember']:
instance.teammember_set.add(project)
Thanks in advance!!
Edit- after doing some more research, I've removed the "Through" model from the script and am trying to rely on the form.py save method to do the join. However, when I do this- the two are still not linking up properly.
Since only your admin (superusers?) will log in, you can start off by using the in-built Django Admin.
I would recommend this for you, at least for now, because you're a beginner and the Admin Form is stunningly simple to use. Then, you can create a custom form later on when you're more comfortable. :-)
With this in mind, you can try eliminating the 'through' table (you may need to reset your migrations), and try this.
Admin.py
from django.contrib import admin
from .models import TeamMember, TMAssigned, Project,
TeamMembersInLine(admin.TabularInline):
model = TeamMember
extra = 1
#admin.register(Project):
class ProjectAdmin(admin.ModelAdmin):
list_display = ('pursuitname', 'bdmember ', 'datecreated')
inlines = [TeamMembersInLine]
Here's another answer that delves into the through table. It was asked by someone in your situation and the answer is relevant too.

Uploading image using mongoengine.Imagefield in Djangorest won't save

I am trying to make an image field using mongoengine in DJango. The form shows up, I upload the image, all other fields are saved except the image but it keeps saying "This field is required" for the thumbnail_new field. Here is my model
class VideoMain(Document):
"""This class represents the Video Meta data model."""
video_id = fields.SequenceField()
ytlink = fields.StringField()
title = fields.StringField()
description =fields.StringField()
show = fields.StringField()
published_at = forms.DateTimeField()
views = fields.IntField()
thumbnail = fields.StringField()
**thumbnail_new = fields.ImageField(size=600,thumbnail_size=None)**
channel_name = fields.StringField()
channel_description = fields.StringField()
guests = fields.ListField(fields.StringField(max_length=30))
anchors = fields.ListField(fields.StringField(max_length=30))
tags = fields.ListField(fields.StringField(max_length=30))
And here is the Django form
from django import forms
from .models import *
class ShowDetailsForm(forms.Form):
shows = Show.objects.all()
title = forms.CharField()
description = forms.CharField()
channel = forms.CharField()
publishingdate = forms.CharField()
views = forms.IntegerField()
thumbnail = forms.CharField()
thumbnail_new = forms.ImageField()
#show = forms.ChoiceField(shows)
class Meta:
model = VideoMain
fields="__all__"
And finally the view function where the form has to be stored
def show_video_data(request):
"""
View function for renewing a specific BookInstance by librarian"""
if request.method == 'POST':
#print("I am post")
form = ShowDetailsForm(request.POST,request.FILES)
if form.is_valid():
newfile=FileUploadHandler(title='anything', file=request.FILES['thumbnail_new'])
newfile.save()
print (form.photo)
# do saving #
form.save()
return HttpResponseRedirect('/fetchvideodata')
I am new to django, so please bear If there is a silly mistake. I couldn't find a solution or tutorial that uses both mongoengine and django forms. Also I got error while specifying collection_name="thumbs",**kwargs in the model thumbnail_new = fields.ImageField(size=600,thumbnail_size=None).

Pass array of objects to another model call django

I am trying to select all class for a user and then load all of the classes objects that are corresponding. Here is my model.py file:
from django.db import models
from django.contrib.auth.models import User
class Class(models.Model):
name = models.CharField(max_length=150)
description = models.TextField()
teacher = models.ForeignKey(User)
class UserClasses(models.Model):
class_name = models.ForeignKey(Class)
user = models.ForeignKey(User)
And here is the call i'm making:
def index(request):
#grab all classes for a user
users_classes = UserClasses.objects.filter(user=request.user)
#pass the array of class objects and get their info
classes = Class.objects.select_related(self=users_classes)
context_dict = {}
return render(request, 'dashboard/index.html', context_dict)
How can I achieve the above?
You can do
users_classes = UserClasses.objects.filter(user=request.user)
classes = Class.objects.filter(class_name__in=users_classes)
Now classes objects contains all class which user belongs to.

Google App Engine Django BooleanProperty not binding to table

I have the following,
class Company(db.Model):
companyvalid = db.BooleanProperty(required=True)
class AddCompanyForm(djangoforms.ModelForm):
class Meta:
model = Company
exclude = ['companyentrytime']
exclude = ['companylatlong']
however I cannot get the o/p from the Django stored in the database. I can also only add a record when the checkbox is checked, but this is not reflected in the underlying table when saving the record. What is the smartest way to do this? Thanks
class AddCompanyCategoriesHandler(webapp.RequestHandler):
def get(self):
memcache.flush_all()
form_requirements = AddCompanyCategoriesForm()
path = os.path.join(os.path.dirname(__file__), 'addcompanycat.html')
self.response.out.write(template.render(path, {'form': form_requirements}))
def post(self):
form_requirements = AddCompanyCategoriesForm(data=self.request.POST)
if form_requirements.is_valid():
myname = form_requirements.clean_data['categoryname']
entity = form_requirements.save(commit=False)
entity.put()
=========================================================================================
I'm trying to use the BooleanField, but this fails to work, with the server giving out a 504 error. Here is my model. I've been experimenting with this BooleanFields format, but I'm not sure how this relates to my model. My model is
class Company(db.Model):
companyurl = db.StringProperty(required=True)
companyname = db.StringProperty(required=True)
companydesc = db.TextProperty(required=True)
companyaddress = db.PostalAddressProperty(required=True)
companypostcode = db.StringProperty(required=True)
companyemail = db.EmailProperty(required=True)
companycountry = db.StringProperty(required=True)
companyvalid = db.BooleanProperty()
#companyvalid = db.BooleanField(required=True, label="Check this")
companyentrytime = db.DateTimeProperty(auto_now_add=True)
companylatlong = db.GeoPtProperty()
#property
def catname(self):
return self.companycategory.name
companycategory = db.ReferenceProperty(CompanyCategory, collection_name='compcategory')
and the following
class AddCompanyForm(djangoforms.ModelForm):
class Meta:
model = Company
#companyvalid = model.BooleanField(default=False)
exclude = ['companyentrytime']
exclude = ['companylatlong']
So my question is that if I have to use this BooleanField, how should I put it in the AddCompanyForm and should there be an entry in the model?
Try using BooleanField (https://docs.djangoproject.com/en/dev/ref/models/fields/#booleanfield) rather than Boolean Property in your model?

Categories

Resources