Django Restful Framework - Limit Results Based on Role/Group - python

I'm trying to build an API in Django Rest Framework (Python 3.x). As a requirement from our b2b partners we can only redistribute their content to certain users. Therefore, I'd like to edit the view to only return certain data based on a users group/role in the system.
For example, I have the following model:
class LocalDeals(models.Model):
deal_id = models.IntegerField(db_column='deal_ID', unique=True) # Field name made lowercase.
deal_url = models.CharField(db_column='deal_URL', max_length=600) # Field name made lowercase.
store_id = models.IntegerField(db_column='store_ID', blank=True, null=True) # Field name made lowercase.
store_online_id = models.IntegerField(db_column='storeOnline_ID', blank=True, null=True) # Field name made lowercase.
store_chain_id = models.IntegerField(db_column='storeChain_ID', blank=True, null=True) # Field name made lowercase.
deal_price = models.FloatField(db_column='dealPrice', blank=True, null=True) # Field name made lowercase.
deal_original_price = models.FloatField(db_column='dealOriginalPrice', blank=True, null=True) # Field name made lowercase.
deal_title = models.CharField(db_column='dealTitle', max_length=256) # Field name made lowercase.
store_name = models.CharField(db_column='storeName', max_length=64, blank=True, null=True) # Field name made lowercase.
image_small = models.CharField(db_column='smallImage', max_length=128, blank=True, null=True) # Field name made lowercase.
image_large = models.CharField(db_column='largeImage', max_length=128, blank=True, null=True) # Field name made lowercase.
store_url = models.CharField(db_column='storeURL', max_length=128, blank=True, null=True) # Field name made lowercase.
provider_name = models.CharField(db_column='providerName', max_length=64, blank=True, null=True) # Field name made lowercase.
provider_logo = models.CharField(db_column='providerLogo', max_length=128, blank=True, null=True) # Field name made lowercase.
user_provider_id = models.IntegerField(db_column='userProvider_ID', blank=True, null=True) # Field name made lowercase.
expiration_date = models.DateTimeField(db_column='expirationDate', blank=True, null=True) # Field name made lowercase.
create_date = models.DateTimeField(db_column='createDate', blank=True, null=True) # Field name made lowercase.
update_date = models.DateTimeField(db_column='updateDate') # Field name made lowercase.
yelp_rating = models.FloatField(db_column='yelp_rating',blank=True, null=True)
yelp_review_count = models.IntegerField(db_column='yelp_review_count',blank=True, null=True)
yelp_rating_img_url = models.CharField(db_column='yelp_rating_img_url',max_length=128, blank=True, null=True)
yelp_url = models.CharField(db_column='yelp_url',max_length=128, blank=True, null=True)
address1 = models.CharField(db_column='address1',max_length=64, blank=True, null=True)
city = models.CharField(db_column='city',max_length=64, blank=True, null=True)
state = models.CharField(db_column='state',max_length=32, blank=True, null=True)
zip = models.CharField(db_column='zip',max_length=10, blank=True, null=True)
country = models.CharField(db_column='country',max_length=32, blank=True, null=True)
latitude = models.FloatField(db_column='latitude',blank=True, null=True)
longitude = models.FloatField(db_column='longitude',blank=True, null=True)
deal_code = models.CharField(db_column='dealCode', max_length=32, blank=True, null=True) # Field name made lowercase.
event_date = models.DateTimeField(db_column='eventDate', blank=True, null=True) # Field name made lowercase.
is_now_deal = models.IntegerField(db_column='isNowDeal', blank=True, null=True) # Field name made lowercase.
business_type = models.IntegerField(db_column='businessType', blank=True, null=True) # Field name made lowercase.
scoring_base = models.FloatField(db_column='scoringBase', blank=True, null=True) # Field name made lowercase.
deal_type = models.CharField(db_column='dealType', max_length=16, blank=True, null=True) # Field name made lowercase.
deal_disclaimer = models.TextField(db_column='dealDisclaimer', blank=True, null=True) # Field name made lowercase.
submit_id = models.IntegerField(db_column='submit_ID', blank=True, null=True) # Field name made lowercase.
deal_date_time = models.DateField(db_column='deal_datetime',blank=True, null=True)
business_type_sub = models.IntegerField(db_column='businessTypeSub', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'local_deals'
app_label = 'api'
Which is called by the following view and serializer:
class LocalDealsViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows local_deals to be viewed.
"""
throttle_classes = (UserRateThrottle,)
queryset = LocalDeals.objects.all()
serializer_class = LocalDealsSerializer
class LocalDealsSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = LocalDeals
fields = ('deal_id','deal_url','deal_price','deal_original_price','deal_title',
'store_name','image_small','image_large','store_url','provider_name',
'expiration_date','create_date','update_date','address1','city','state',
'zip','country','latitude','longitude','deal_code',
'business_type','business_type_sub','deal_type','deal_date_time',)
If the user is not in the auth_group 'admin' (id 1) then I'd like to restrict the results so that it shows all results except where user_provider_id in [1,3]. How can I do this?

You should override get_queryset() method to restrict results based on admin auth group.
class LocalDealsViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows local_deals to be viewed.
"""
throttle_classes = (UserRateThrottle,)
serializer_class = LocalDealsSerializer
def get_queryset(self):
# check here if 'list' request and user not in admin auth group
if self.action == 'list' and self.request.user not in admin auth_group:
# exclude results with 'user_provider_id' in [1,3]
return LocalDeals.objects.all().exclude(user_provider_id__in=[1,3])
# Otherwise return all results
return LocalDeals.objects.all()

Related

RecursionError : maximum recursion depth exceeded while calling a Python object

I am getting an error in admin console while trying to open a model . How to fix it
Model.py
class TbSysEmailconfig(models.Model):
id = models.ForeignKey('self', models.DO_NOTHING, db_column='Id', primary_key=True) # Field name made lowercase.
emailtemplateid = models.ForeignKey(TbMasEmailtemplate, models.DO_NOTHING, db_column='EmailTemplateId')
emailfromname = models.CharField(db_column='EmailFromName', max_length=100, blank=True, null=True)
emailfrom = models.CharField(db_column='EmailFrom', max_length=100)
credential = models.CharField(db_column='Credential', max_length=100)
password = models.CharField(db_column='Password', max_length=100)
post = models.IntegerField(db_column='Post', blank=True, null=True)
host = models.CharField(db_column='Host', max_length=100)
priority = models.CharField(db_column='Priority', max_length=100, blank=True, null=True)
maximumday = models.IntegerField(db_column='MaximumDay', blank=True, null=True)
maximumminute = models.IntegerField(db_column='MaximumMinute', blank=True, null=True)
systemid = models.IntegerField(db_column='SystemId')
partfiletemplate = models.CharField(db_column='PartFileTemplate', max_length=500, blank=True, null=True)
comment = models.CharField(db_column='Comment', max_length=1000, blank=True, null=True)
ismaildefault = models.SmallIntegerField(db_column='IsMailDefault')
maildefault = models.CharField(db_column='MailDefault', max_length=4000, blank=True, null=True)
createddate = models.DateTimeField(db_column='CreatedDate')
createdbyuserid = models.IntegerField(db_column='CreatedByUserId')
updateddate = models.DateTimeField(db_column='UpdatedDate')
updatedbyuserid = models.IntegerField(db_column='UpdatedByUserId')
delflag = models.SmallIntegerField(db_column='DelFlag')
class Meta:
db_table = 'TB_SYS_EmailConfig'
admin.py
from django.contrib import admin
from .model import TbSysEmailconfig
#Modifire
admin.site.register(TbSysEmailconfig)
When I select some item
it show this error
Remove the id field from your model, as you have referenced it as a foreign key to the model itself. The id field is automatically generated if no field in the model is explicitly chosen.

How can I add a button inside DetailView template that sends ID to a form?

I have a App called "Properties" and I've created a DetailView that is working. Inside my Properties models I have a Property model and a Bedroom model with a ForeignKey to Property.
#views.py
class PropertyDetailView(DetailView):
template_name = 'properties/property-detail.html'
model = Property
def get_context_data(self, **kwargs):
contacts = ContactsOwner.objects.filter(owner__property=self.object)
context = super().get_context_data(**kwargs)
context['contact'] = contacts
return context
My models.py:
class Property(models.Model):
property_reference = models.CharField(db_column='Property_Reference', max_length=10) # Field name made lowercase.
address = models.CharField(db_column='Address', max_length=250, blank=True, null=True) # Field name made lowercase.
post_code = models.CharField(db_column='Post_Code', max_length=15, blank=True, null=True) # Field name made lowercase.
type = models.CharField(db_column='Type', max_length=25, blank=True, null=True, choices=HOUSE_TYPE_CHOICES) # Field name made lowercase.
bedrooms = models.IntegerField(db_column='Bedrooms', blank=True, null=True) # Field name made lowercase.
bathrooms = models.IntegerField(db_column='Bathrooms', blank=True, null=True) # Field name made lowercase.
usual_cleaning_requirements = models.CharField(db_column='Usual_Cleaning_Requirements', max_length=250, blank=True, null=True) # Field name made lowercase.
notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase.
feature_image = models.ImageField(null=True)
class Meta:
db_table = 'Property'
def __str__(self):
return self.property_reference
def get_absolute_url(self):
return reverse("properties:property_detail",kwargs={'pk':self.pk})
class Bedroom(models.Model):
type = models.CharField(db_column='Type', choices=BEDROOM_TYPE_CHOICES, max_length=50)
bed_dimensions = models.CharField(db_column='Bed_Dimension', choices=BED_DIMENSION_CHOICES, max_length=30)
image = models.ImageField(null=True, blank=True)
ensuite = models.BooleanField(default=False)
notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase.
property = models.ForeignKey(Property, null=False, on_delete=models.CASCADE, related_name='bedroom')
What I need is to create a button named "Add Bedroom" inside the template "property-detail.html" that sends me to a form with pre filled Foreign Key. Could you please help me on this?
You need to redirect that button submit to a view that gets the required info you want and then redirect that to another template with context the info you received (your Foreign key per se)

For loop issue writing multiple lines to database

The for loop below has an issue when writing to the database. Only the first record is coming through, i believe it's because report_name_sc = reportlist is writing the query set to the database. How can I get it to write a single line for each report_id?
checkedlist = request.GET.getlist('report_id')
reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True)
for i in checkedlist:
requestsave = QVFormAccessRequest(ntname_id = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title
,report_id = i, report_name_sc = reportlist, accesslevel_id = '7', phi = '1', access_beg_date = '2017-01-01', access_end_date = '2017-01-31')
requestsave.save()
Models.py added as requested, checked list is a collection of check boxes getting report_id:
from __future__ import unicode_literals
from django.utils import timezone
from django.contrib.auth.models import (AbstractBaseUser,PermissionsMixin)
from django.db import models
from django.conf import settings
from django.forms import ModelForm
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
username = models.CharField(max_length=7, unique=True)
formattedusername = models.CharField(max_length=11, unique=True, primary_key = True)
first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length=140)
date_joined = models.DateTimeField(default=timezone.now)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_cfo = models.BooleanField(default=False)
facility = models.CharField(max_length=140)
officename = models.CharField(max_length=100)
jobdescription = models.CharField(max_length=140)
positioncode = models.CharField(max_length = 100)
positiondescription = models.CharField(max_length=140)
coid = models.CharField(max_length=5)
streetaddress = models.CharField(max_length=140)
title = models.CharField(max_length=100)
USERNAME_FIELD = 'username'
class Meta:
app_label = 'accounts'
db_table = "user"
def save(self, *args, **kwargs):
self.formattedusername = '{domain}\{username}'.format(
domain='HCA', username=self.username)
super(User, self).save(*args, **kwargs);
def get_short_name(self):
return self.username
# REQUIRED_FIELDS = "username"
def __str__(self):
return '%s - %s %s' % (self.username, self.first_name, self.last_name)
class FacilityDimension(models.Model):
unit_num = models.CharField(db_column='Unit_Num', max_length=5, blank=True, null=True) # Field name made lowercase.
company_code = models.CharField(db_column='Company_Code', max_length=1, blank=True, null=True) # Field name made lowercase.
coid = models.CharField(db_column='Coid',primary_key=True, serialize=False, max_length=5) # Field name made lowercase.
coid_name = models.CharField(db_column='COID_Name', max_length=50, blank=True, null=True) # Field name made lowercase.
c_level = models.CharField(db_column='C_Level', max_length=6, blank=True, null=True) # Field name made lowercase.
company_name = models.CharField(db_column='Company_Name', max_length=50, blank=True, null=True) # Field name made lowercase.
s_level = models.CharField(db_column='S_Level', max_length=6, blank=True, null=True) # Field name made lowercase.
sector_name = models.CharField(db_column='Sector_Name', max_length=50, blank=True, null=True) # Field name made lowercase.
b_level = models.CharField(db_column='B_Level', max_length=6, blank=True, null=True) # Field name made lowercase.
group_name = models.CharField(db_column='Group_Name', max_length=50, blank=True, null=True) # Field name made lowercase.
r_level = models.CharField(db_column='R_Level', max_length=6, blank=True, null=True) # Field name made lowercase.
division_name = models.CharField(db_column='Division_Name', max_length=50, blank=True, null=True) # Field name made lowercase.
d_level = models.CharField(db_column='D_Level', max_length=6, blank=True, null=True) # Field name made lowercase.
market_name = models.CharField(db_column='Market_Name', max_length=50, blank=True, null=True) # Field name made lowercase.
f_level = models.CharField(db_column='F_Level', max_length=6, blank=True, null=True) # Field name made lowercase.
cons_facility_name = models.CharField(db_column='Cons_Facility_Name', max_length=50, blank=True, null=True) # Field name made lowercase.
lob_code = models.CharField(db_column='LOB_Code', max_length=3, blank=True, null=True) # Field name made lowercase.
lob_name = models.CharField(db_column='LOB_Name', max_length=20, blank=True, null=True) # Field name made lowercase.
sub_lob_code = models.CharField(db_column='Sub_LOB_Code', max_length=3, blank=True, null=True) # Field name made lowercase.
sub_lob_name = models.CharField(db_column='Sub_LOB_Name', max_length=20, blank=True, null=True) # Field name made lowercase.
state_code = models.CharField(db_column='State_Code', max_length=2, blank=True, null=True) # Field name made lowercase.
pas_id_current = models.CharField(db_column='PAS_ID_Current', max_length=8, blank=True, null=True) # Field name made lowercase.
pas_current_name = models.CharField(db_column='PAS_Current_Name', max_length=40, blank=True, null=True) # Field name made lowercase.
pas_id_future = models.CharField(db_column='PAS_ID_Future', max_length=8, blank=True, null=True) # Field name made lowercase.
pas_future_name = models.CharField(db_column='PAS_Future_Name', max_length=40, blank=True, null=True) # Field name made lowercase.
summary_7_member_ind = models.CharField(db_column='Summary_7_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
summary_8_member_ind = models.CharField(db_column='Summary_8_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
summary_phys_svc_member_ind = models.CharField(db_column='Summary_Phys_Svc_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
summary_asd_member_ind = models.CharField(db_column='Summary_ASD_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
summary_imaging_member_ind = models.CharField(db_column='Summary_Imaging_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
summary_oncology_member_ind = models.CharField(db_column='Summary_Oncology_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
summary_cath_lab_member_ind = models.CharField(db_column='Summary_Cath_Lab_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
summary_intl_member_ind = models.CharField(db_column='Summary_Intl_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
summary_other_member_ind = models.CharField(db_column='Summary_Other_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
pas_coid = models.CharField(db_column='PAS_COID', max_length=5, blank=True, null=True) # Field name made lowercase.
pas_status = models.CharField(db_column='PAS_Status', max_length=1, blank=True, null=True) # Field name made lowercase.
company_code_operations = models.CharField(db_column='Company_Code_Operations', max_length=3, blank=True, null=True) # Field name made lowercase.
osg_pas_ind = models.CharField(db_column='OSG_PAS_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
abs_facility_member_ind = models.CharField(db_column='ABS_Facility_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
abl_facility_member_ind = models.CharField(db_column='ABL_Facility_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
intl_pmis_member_ind = models.CharField(db_column='INTL_PMIS_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
hsc_member_ind = models.CharField(db_column='HSC_Member_Ind', max_length=1, blank=True, null=True) # Field name made lowercase.
loaddate = models.DateTimeField(db_column='LoadDate', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'Facility_Dimension'
class QvDatareducecfo(models.Model):
cfo_fname = models.CharField(db_column='CFO_FName', max_length=100, blank=True, null=True) # Field name made lowercase.
cfo_lname = models.CharField(db_column='CFO_LName', max_length=100, blank=True, null=True) # Field name made lowercase.
cfo_ntname = models.OneToOneField(settings.AUTH_USER_MODEL,db_column='CFO_NTName',max_length=11, primary_key=True) # Field name made lowercase.
cfo_type = models.IntegerField(db_column='CFO_Type', blank=True, null=True) # Field name made lowercase.
org_level_id = models.IntegerField(db_column='Org_Level_ID', blank=True, null=True) # Field name made lowercase.
org_level = models.CharField(db_column='Org_Level', max_length=255, blank=True, null=True) # Field name made lowercase.
unit_no = models.CharField(db_column='Unit_No', max_length=10, blank=True, null=True) # Field name made lowercase.
dr_code = models.CharField(db_column='DR_Code', max_length=255, blank=True, null=True) # Field name made lowercase.
dr_name = models.CharField(db_column='DR_Name', max_length=255, blank=True, null=True) # Field name made lowercase.
cfo_dr_code = models.CharField(db_column='CFO_DR_Code', max_length=255, blank=True, null=True) # Field name made lowercase.
cfo_dr_name = models.CharField(db_column='CFO_DR_Name', max_length=255, blank=True, null=True) # Field name made lowercase.
b_level = models.CharField(db_column='B_Level', max_length=6, blank=True, null=True) # Field name made lowercase.
group_name = models.CharField(db_column='Group_Name', max_length=255, blank=True, null=True) # Field name made lowercase.
load_date = models.DateTimeField(db_column='Load_Date', blank=True, null=True) # Field name made lowercase.
beg_date = models.DateTimeField(db_column='Beg_Date', blank=True, null=True) # Field name made lowercase.
end_date = models.DateTimeField(db_column='End_Date', blank=True, null=True) # Field name made lowercase.
active = models.IntegerField(db_column='Active', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'QV_DataReduceCFO'
def __str__(self):
return str(self.cfo_ntname)
class QvReportList(models.Model):
qv_dept_id = models.CharField(db_column='QV_Dept_ID', max_length=100) # Field name made lowercase.
report_id = models.CharField(db_column='Report_ID',primary_key=True, max_length=100, serialize=False) # Field name made lowercase.
report_name = models.CharField(db_column='Report_Name', max_length=255, blank=True, null=True) # Field name made lowercase.
report_name_sc = models.CharField(db_column='Report_Name_SC', max_length=255, blank=True, null=True) # Field name made lowercase.
qv_filename = models.CharField(db_column='QV_FileName', max_length=255, blank=True, null=True) # Field name made lowercase.
report_access = models.CharField(db_column='Report_Access', max_length=20, blank=True, null=True) # Field name made lowercase.
report_group_id = models.IntegerField(db_column='Report_Group_ID', blank=True, null=True) # Field name made lowercase.
report_sub_group_id = models.IntegerField(db_column='Report_Sub_Group_ID', blank=True, null=True) # Field name made lowercase.
load_date = models.DateTimeField(db_column='Load_Date', blank=True, null=True) # Field name made lowercase.
approver_fname = models.CharField(db_column='Approver_FName', max_length=255, blank=True, null=True) # Field name made lowercase.
approver_lname = models.CharField(db_column='Approver_LName', max_length=255, blank=True, null=True) # Field name made lowercase.
approver_ntname = models.CharField(db_column='Approver_NTName', max_length=255, blank=True, null=True) # Field name made lowercase.
beg_date = models.DateTimeField(db_column='Beg_Date', blank=True, null=True) # Field name made lowercase.
end_date = models.DateTimeField(db_column='End_Date', blank=True, null=True) # Field name made lowercase.
active = models.IntegerField(db_column='Active', blank=True, null=True) # Field name made lowercase.
approval_id = models.IntegerField(db_column='Approval_ID', blank=True, null=True) # Field name made lowercase.
role_based_id = models.IntegerField(db_column='Role_Based_ID', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'QV_Report_List'
class QVReportAccess(models.Model):
user_status = models.CharField(db_column='User_Status', max_length = 20) # Field name made lowercase.
ntname = models.OneToOneField(settings.AUTH_USER_MODEL,db_column='NTName', max_length=11,primary_key=True, serialize=False) # Field name made lowercase.
report_name = models.CharField(db_column='Report_Name', max_length=50, blank=True, null=True) # Field name made lowercase.
report_name_sc = models.CharField(db_column='Report_Name_SC', max_length=30, blank=True, null=True) # Field name made lowercase.
datareduce_report_code = models.IntegerField(db_column='DataReduce_Report_Code', blank=True, null=True) # Field name made lowercase.
role_based_id = models.IntegerField(db_column='Role_Based_ID', blank=True, null=True) # Field name made lowercase.
report_id = models.OneToOneField(QvReportList,db_column='Report_ID', max_length=100, blank=True, null=True) # Field name made lowercase.
report_group_id = models.IntegerField(db_column='Report_Group_ID', blank=True, null=True) # Field name made lowercase.
report_access = models.CharField(db_column='Report_Access', max_length=50, blank=True, null=True) # Field name made lowercase.
sr_datareduce_summary_code = models.CharField(db_column='SR_DataReduce_Summary_Code', max_length=10, blank=True, null=True) # Field name made lowercase.
sr_datareduce_patient_code = models.CharField(db_column='SR_DataReduce_Patient_Code', max_length=10, blank=True, null=True) # Field name made lowercase.
userid = models.IntegerField(db_column='UserID', blank=True, null=True) # Field name made lowercase.
user_group_id = models.IntegerField(db_column='User_Group_ID', blank=True, null=True)
access_level_id = models.IntegerField(db_column='Access_Level_ID', blank=True, null=True)
active = models.IntegerField(db_column='Active', blank=True, null=True)
qv_statusid = models.IntegerField(db_column='QV_StatusID', blank=True, null=True)
employee_status_id = models.IntegerField(db_column='Employee_Status_ID', blank = True, null = True)
new_user = models.IntegerField(db_column='New_User', blank = True, null = True)
new_access = models.IntegerField(db_column='New_Access', blank = True, null = True)
new_report = models.IntegerField(db_column='New_Report', blank = True, null = True)
changed_row = models.IntegerField(db_column='Changed_Row',blank = True, null = True)
last_change_date = models.DateTimeField(db_column='Last_Change_Date', blank=True, null=True) # Field name made lowercase.
access_beg_date = models.DateTimeField(db_column='Access_Beg_Date', blank=True, null=True) # Field name made lowercase.
access_end_date = models.DateTimeField(db_column='Access_End_Date', blank=True, null=True) # Field name made lowercase.
report_beg_date = models.DateTimeField(db_column='Report_Beg_Date', blank=True, null=True) # Field name made lowercase.
report_end_date = models.DateTimeField(db_column='Report_End_Date', blank=True, null=True) # Field name made lowercase.
qv_startdate = models.DateTimeField(db_column='QV_StartDate', blank=True, null=True) # Field name made lowercase.
load_date = models.DateTimeField(db_column='Load_Date', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'QV_ReportAccess'
class QVFormAccessRequest(models.Model):
ntname = models.CharField(max_length=11)
first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length=140)
coid = models.CharField(max_length=5)
facility = models.CharField(max_length=140)
title = models.CharField(max_length=100)
report_id = models.CharField(max_length=100)
report_name_sc = models.CharField(max_length=100, blank=True, null=True)
accesslevel_id = models.CharField(max_length=100)
phi = models.BooleanField(default=False)
access_beg_date = models.DateTimeField(blank=True, null=True) # Field name made lowercase.
access_end_date = models.DateTimeField(blank=True, null=True) # Field name made lowercase.
class Meta:
managed = True
db_table = 'QV_FormAccessRequest'
class DjangoMigrations(models.Model):
app = models.CharField(max_length=255)
name = models.CharField(max_length=255)
applied = models.DateTimeField()
class Meta:
managed = False
db_table = 'django_migrations'
class Sysdiagrams(models.Model):
name = models.CharField(max_length=128)
principal_id = models.IntegerField()
diagram_id = models.AutoField(primary_key=True)
version = models.IntegerField(blank=True, null=True)
definition = models.BinaryField(blank=True, null=True)
class Meta:
managed = False
db_table = 'sysdiagrams'
unique_together = (('principal_id', 'name'),)
Your QVFormAccessRequest model specifies ntname to be a primary key. So, there cannot be to model instances with the same primary key.
In your loop, you are iterating over checkedlist, but you always set the same ntname_id, so you are overwriting the previous object.
I suspect that you need to change your model to support what you want to achieve. Maybe, it is enough to remove the primary key constraint from ntname and let Django create a surrogate key (artificial key) for you.

Django models and join sql tables

i wanted to try using django instead of having to call my stored procedure on the DB.
So i created a new model, taking informations from two differents models
class TbMouvementinit(models.Model):
id = models.AutoField(db_column='Id', primary_key=True) # Field name made lowercase.
dateheurecreat = models.TextField(db_column='DateHeureCreat') # Field name made lowercase.
dateheureclot = models.TextField(db_column='DateHeureClot', blank=True, null=True) # Field name made lowercase.
id_pesee = models.BigIntegerField(db_column='Id_Pesee') # Field name made lowercase.
id_proteine = models.BigIntegerField(db_column='Id_Proteine', blank=True, null=True) # Field name made lowercase.
id_humidite = models.BigIntegerField(db_column='Id_Humidite', blank=True, null=True) # Field name made lowercase.
id_espece = models.BigIntegerField(db_column='Id_Espece', blank=True, null=True) # Field name made lowercase.
id_produit = models.BigIntegerField(db_column='Id_Produit', blank=True, null=True) # Field name made lowercase.
id_codeechantillon = models.BigIntegerField(db_column='Id_CodeEchantillon', blank=True, null=True) # Field name made lowercase.
id_traitement = models.BigIntegerField(db_column='Id_Traitement', blank=True, null=True) # Field name made lowercase.
id_circuit = models.BigIntegerField(db_column='Id_Circuit', blank=True, null=True) # Field name made lowercase.
code_source = models.CharField(db_column='Code_Source', max_length=20, blank=True, null=True) # Field name made lowercase.
code_destination = models.CharField(db_column='Code_Destination', max_length=20, blank=True, null=True) # Field name made lowercase.
nomos = models.CharField(db_column='NomOS', max_length=30, blank=True, null=True) # Field name made lowercase.
codesite = models.CharField(db_column='CodeSite', max_length=9, blank=True, null=True) # Field name made lowercase.
type_mouvement = models.CharField(db_column='Type_Mouvement', max_length=3, blank=True, null=True) # Field name made lowercase.
sous_domaine = models.CharField(db_column='Sous_Domaine', max_length=1, blank=True, null=True) # Field name made lowercase.
recolte = models.SmallIntegerField(db_column='Recolte', blank=True, null=True) # Field name made lowercase.
espece = models.CharField(db_column='Espece', max_length=9, blank=True, null=True) # Field name made lowercase.
code_variete = models.CharField(db_column='Code_Variete', max_length=10, blank=True, null=True) # Field name made lowercase.
code_tiers = models.CharField(db_column='Code_Tiers', max_length=9, blank=True, null=True) # Field name made lowercase.
num_bl_livreur = models.CharField(db_column='Num_Bl_Livreur', max_length=9, blank=True, null=True) # Field name made lowercase.
num_contrat_client = models.IntegerField(db_column='Num_Contrat_Client', blank=True, null=True) # Field name made lowercase.
num_oe = models.IntegerField(db_column='Num_OE', blank=True, null=True) # Field name made lowercase.
code_transporteur = models.CharField(db_column='Code_Transporteur', max_length=9, blank=True, null=True) # Field name made lowercase.
immat_transporteur = models.CharField(db_column='Immat_Transporteur', max_length=10, blank=True, null=True) # Field name made lowercase.
poids_charge = models.FloatField(db_column='Poids_Charge', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified
poids_vide = models.FloatField(db_column='Poids_Vide', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified
code_caract1 = models.CharField(db_column='Code_Caract1', max_length=5, blank=True, null=True) # Field name made lowercase.
val_caract1 = models.FloatField(db_column='Val_Caract1', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified
code_caract2 = models.CharField(db_column='Code_Caract2', max_length=5, blank=True, null=True) # Field name made lowercase.
val_caract2 = models.FloatField(db_column='Val_Caract2', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified
code_caract3 = models.CharField(db_column='Code_Caract3', max_length=5, blank=True, null=True) # Field name made lowercase.
val_caract3 = models.FloatField(db_column='Val_Caract3', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified
code_caract4 = models.CharField(db_column='Code_Caract4', max_length=5, blank=True, null=True) # Field name made lowercase.
val_caract4 = models.FloatField(db_column='Val_Caract4', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified
code_caract5 = models.CharField(db_column='Code_Caract5', max_length=5, blank=True, null=True) # Field name made lowercase.
val_caract5 = models.FloatField(db_column='Val_Caract5', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified
code_caract6 = models.CharField(db_column='Code_Caract6', max_length=5, blank=True, null=True) # Field name made lowercase.
val_caract6 = models.FloatField(db_column='Val_Caract6', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified
code_caract7 = models.CharField(db_column='Code_Caract7', max_length=5, blank=True, null=True) # Field name made lowercase.
val_caract7 = models.FloatField(db_column='Val_Caract7', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified
code_caract8 = models.CharField(db_column='Code_Caract8', max_length=5, blank=True, null=True) # Field name made lowercase.
val_caract8 = models.FloatField(db_column='Val_Caract8', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified
code_caract9 = models.CharField(db_column='Code_Caract9', max_length=5, blank=True, null=True) # Field name made lowercase.
val_caract9 = models.FloatField(db_column='Val_Caract9', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified
code_caract10 = models.CharField(db_column='Code_Caract10', max_length=5, blank=True, null=True) # Field name made lowercase.
val_caract10 = models.FloatField(db_column='Val_Caract10', blank=True, null=True) # Field name made lowercase. This field type is a guess. Modified
code_cel = models.CharField(db_column='Code_Cel', max_length=5, blank=True, null=True) # Field name made lowercase.
num_operation = models.IntegerField(db_column='Num_Operation', blank=True, null=True) # Field name made lowercase.
datetime2supv = models.CharField(db_column='DateTime2SUPV', max_length=20, blank=True, null=True) # Field name made lowercase.
num_lot_supv = models.BigIntegerField(db_column='Num_Lot_SUPV', blank=True, null=True) # Field name made lowercase.
user_supv = models.CharField(db_column='User_SUPV', max_length=18, blank=True, null=True) # Field name made lowercase.
class TbEspece(models.Model):
id = models.AutoField(db_column='Id', primary_key=True) # Field name made lowercase.
recolte = models.SmallIntegerField(db_column='Recolte') # Field name made lowercase.
groupe = models.CharField(db_column='Groupe', max_length=3) # Field name made lowercase.
categorie = models.CharField(db_column='Categorie', max_length=3) # Field name made lowercase.
code = models.CharField(db_column='Code', max_length=3) # Field name made lowercase.
libelle = models.CharField(db_column='Libelle', max_length=30) # Field name made lowercase.
class Meta:
managed = False
db_table = 'TB_Espece'
app_label = 'erp'
class ResumeMvtActif(models.Model):
mvt = models.ForeignKey(TbMouvementinit)
espece = models.ForeignKey(TbEspece)
And then call it by using just
mouvements = ResumeMvtActif.objects.all()
But of course i get a Database error because i don't really have a ResumeMvtActif table.
How can i proceed to make this work ? do i have to create an extra table on my DB ? Is there a trick to tell Django that it's not a real table and just a join of two tables ?

Can't update existing record in django

I need to update existing recode in the database.I'm using mysql.
this my model class
class SuSurey(models.Model):
#id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase.
su_name = models.CharField(db_column='su_Name', max_length=30) # Field name made lowercase.
description = models.CharField(db_column='Description', max_length=500, blank=True) # Field name made lowercase.
duration = models.IntegerField(db_column='Duration') # Field name made lowercase.
audience = models.CharField(db_column='Audience', max_length=20, blank=True) # Field name made lowercase.
start_date = models.CharField(db_column='Start_date', max_length=50, blank=True) # Field name made lowercase.
end_date = models.CharField(db_column='End_date', max_length=50, blank=True) # Field name made lowercase.
create_date = models.CharField(db_column='Create_date', max_length=50, blank=True) # Field name made lowercase.
update_date = models.CharField(db_column='Update_date', max_length=50, blank=True) # Field name made lowercase.
create_by = models.IntegerField(db_column='Create_by', blank=True, null=True) # Field name made lowercase.
update_by = models.IntegerField(db_column='Update_by', blank=True, null=True) # Field name made lowercase.
def __unicode__(self):
return self.su_name
class Meta:
managed = False
db_table = 'su_surey'
i didn't use any forms in my web application. In my view.py i have this
if request.method == 'POST':
date=request.POST.get('dates','').split('-')
survey_data=SuSurey.objects.get(id=survey_id)
survey_data.su_name=request.POST.get('Name','')
survey_data.description=request.POST.get('Description','')
survey_data.duration=request.POST.get('Duration','')
survey_data.audience=request.POST.get('Audience','')
survey_data.start_date=date[0]
survey_data.end_date=date[1]
survey_data.update_date=datetime.datetime.today()
survey_data.update_by=request.session['user_login_data']['id']
try:
survey_data.full_clean()
survey_data.save(update_fields=['su_name','description','duration','audience','start_date','end_date','update_date','update_by'])
messages={'success':'Successfuly data added'}
url = reverse('addQuestionSurveys', kwargs={'survey_id': survey_id })
return HttpResponseRedirect(url)
except ValidationError as e:
messages={'error':e.messages}
return render(request, 'pages/forms/newSurvey.html',{'dept_data': dept_data,'messages': messages},context_instance=RequestContext(request))
when i add data Django did update the recode that is find by survey_id recode. it will add new recode to database.how can i fix this problem ? need a quick help thank you.

Categories

Resources