How to update integer field in DRF - python

In my project there is video module, related to this module user can add vodeo bookmarks,
class VideoBookmark(BaseModel, SoftDelete):
video = models.ForeignKey(Video, on_delete=models.CASCADE)
sort_order = models.PositiveSmallIntegerField(null=False, blank=False)
name = models.CharField(max_length=254, null=True, blank=True)
description = models.CharField(max_length=254, null=True, blank=True)
duration = models.DurationField(default=timedelta())
start_time = models.DurationField(default=timedelta())
end_time = models.DurationField(default=timedelta())
mobile_thumbnail_image = models.ImageField(upload_to='video_bookmark_mobile_thumbnail', height_field=None,
width_field=None, null=True, blank=True)
web_thumbnail_image = models.ImageField(upload_to='video_bookmark_web_thumbnail', height_field=None,
width_field=None, null=True, blank=True)
def __str__(self):
return str(self.name)
Bookmark3 is in the order of "2" and when trying to add bookmark2 in the order of "2" the order of bookmark3 should be changed to the order of "3".I don't know how to implement this, Can you suggest a way to implement this?

Related

How to use an outside script within a Django Project?

Sorry for the wording on the question if it isn't clear.
I am rather new to Django but not too new to Python. I have a Model in my Django Project, which keeps track of trailer locations. I then need to use another script to update this data. However, when running this script, the Dict that is suppose to be returned is not getting returned properly.
class TrailerLocation(models.Model):
trailer = models.OneToOneField(Trailer, on_delete=models.CASCADE)
locationCity = models.CharField(max_length=70, null=True, blank=True)
locationState = models.CharField(max_length=30, null=True, blank=True)
locationCountry = models.CharField(max_length=50, null=True, blank=True)
locationStatus = models.CharField(max_length=200, null=True, blank=True)
latitude = models.CharField(max_length=200, null=True, blank=True)
longitude = models.CharField(max_length=200, null=True, blank=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
# def __str__(self):
# return self.trailer
def createLocation(self, trailer):
trailerLocation = TrailerLocation(trailer=trailer)
trailerLocation.save()
def getLocations(self):
locDataDict = trailerLocations.run()
print(locDataDict)
for key in locDataDict.keys():
datalist = locDataDict[key]
self.updateLocation(key, datalist)

Restrict form field choices based on previous model choice in Django

I am currently attempting to create a DnD 5e Character creator using Django and SRD materials provided by WoTC. This is the first time I have ever used Django, and I am learning it as I go. I have come up against a bit of a challenge that has stone-walled me for a few days now. I have researched the issue, and after applying multiple techniques I thought may help, I've had limited luck. My question is this:
I have a number of models representing Heroes, Races, Subraces, Classes, Backgrounds and so forth. I wish to be able to restrict a users ability to choose a Subrace, based on their selection of a race beforehand.
So far I have this:
models.py
class Race(models.Model):
race_name = models.CharField(max_length=200)
race_size = models.CharField(
max_length=2, choices=SIZE_CHOICE, default='M')
race_speed = models.IntegerField(
default=30)
race_lang = models.CharField(max_length=200, null=True, blank=True)
race_str = models.IntegerField(default=0, null=True, blank=True)
race_dex = models.IntegerField(default=0, null=True, blank=True)
race_con = models.IntegerField(default=0, null=True, blank=True)
race_int = models.IntegerField(default=0, null=True, blank=True)
race_wis = models.IntegerField(default=0, null=True, blank=True)
race_cha = models.IntegerField(default=0, null=True, blank=True)
skill_spend = models.IntegerField(default=0, null=True, blank=True)
race_extra = models.TextField(max_length=2000, blank=True, null=True)
race_source = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.race_name
class Meta:
verbose_name = 'Race'
verbose_name_plural = 'Races'
class Subrace(models.Model):
sub_name = models.CharField(max_length=200)
sub_size = models.CharField(
max_length=2, choices=SIZE_CHOICE, default='M', null=True)
sub_speed = models.IntegerField(
default=30, null=True)
sub_lang = models.CharField(max_length=200, null=True, blank=True)
sub_str = models.IntegerField(default=0, null=True, blank=True)
sub_dex = models.IntegerField(default=0, null=True, blank=True)
sub_con = models.IntegerField(default=0, null=True, blank=True)
sub_int = models.IntegerField(default=0, null=True, blank=True)
sub_wis = models.IntegerField(default=0, null=True, blank=True)
sub_cha = models.IntegerField(default=0, null=True, blank=True)
sub_extra = models.TextField(max_length=2000, null=True, blank=True)
sub_parent = models.ForeignKey(Race, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.sub_name
class Meta:
verbose_name = 'Subrace'
verbose_name_plural = 'Subraces'
class Hero(models.Model):
def roll_stats():
d6 = die.Dice(6)
list_stats = d6.roll(4)
list_stats.sort()
add = sum(list_stats[1:4])
return add
hero_name = models.CharField(max_length=200)
author = models.ForeignKey(User, null=True)
hero_subrace = models.ForeignKey(
Subrace, on_delete=models.CASCADE, null=True, blank=True)
pub_date = models.DateTimeField('date published', blank=True, null=True)
hero_klass = models.ForeignKey(Klass, on_delete=models.CASCADE, null=True)
hero_race = models.ForeignKey(Race, on_delete=models.CASCADE)
background = models.ForeignKey(
Background, on_delete=models.CASCADE, null=True)
health = models.IntegerField(blank=True, null=True)
hero_exp = models.IntegerField(default=0, null=True)
hero_alignment = models.ForeignKey(Alignment, blank=True, null=True)
hero_str = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_dex = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_con = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_int = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_wis = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_cha = models.IntegerField(default=roll_stats, null=True, blank=True)
def save(self, *args, **kwargs):
"Returns a hero's hp"
die_str = str(self.hero_klass.hit_dice)
die_nums = die_str.split("d")
die_val = int(die_nums[1])
die_roll = int(die_nums[0])
hp_die = die.Dice(die_val)
results = hp_die.roll(die_roll)
self.health = sum(results)
super(Hero, self).save(*args, **kwargs)
def __str__(self):
return self.hero_name
def get_absolute_url(self):
return reverse('hero.views.detail', args=[str(self.id)])
class Meta:
verbose_name = 'Hero'
verbose_name_plural = 'Heroes'
views.py
def new_hero(request):
user = request.user
if request.method == "POST":
form = HeroForm(request.POST)
if form.is_valid():
hero = form.save(commit=False)
hero.author = request.user
hero.save()
return redirect('detail', hero.pk)
else:
form = HeroForm()
return render(request, 'new_hero.html', {'form': form, 'user': user})
forms.py
class HeroForm(forms.ModelForm):
class Meta:
model = Hero
fields = ['hero_name', 'hero_race', 'hero_subrace',
'hero_klass', 'hero_exp', 'health', 'background',
'hero_str', 'hero_dex', 'hero_con', 'hero_int',
'hero_wis', 'hero_cha', 'hero_alignment']
def __init__(self, *args, **kwargs):
super(HeroForm, self).__init__(*args, **kwargs)
for fieldname in ['hero_str', 'hero_dex', 'hero_con', 'hero_int', 'hero_wis', 'hero_cha']:
self.fields[fieldname].disabled = True
race = Race.objects.all()
for name in race:
self.fields['hero_subrace'].queryset = Subrace.objects.filter(sub_parent=name)
I have trialled a few different techniques, but this is where I am now. This:
for name in race:
self.fields['hero_subrace'].queryset = Subrace.objects.filter(sub_parent=name)
is my most recent addition to my app. At the hero creation screen I am hit with a blank box of choices, as opposed to the full unrestricted list without the loop or queryset.
Basically I'm hoping that someone has some advice for me on a method I may be overlooking, or something that I've missed, or simply not found yet. Also please feel free to critique the rest of the code, like I said this is my first Django App :). Also my first Stack Overflow question, so thanks :)
For anyone that is wondering, I used django-smart-selects to solve my problem.
base.html
<script type="text/javascript" src="{% static 'smart-selects/admin/js/chainedfk.js' %}"></script>
<script type="text/javascript" src="{% static 'smart-selects/admin/js/bindfields.js' %}"></script>
I added the above html to my {% load staticfiles %} call.
and changed models.py:
models.py
from smart_selects.db_fields import ChainedForeignKey
class Hero(models.Model):
....
race = models.ForeignKey(Race, on_delete=models.CASCADE)
subrace = ChainedForeignKey(Subrace,
chained_field="race",
chained_model_field="race",
show_all=False,
auto_choose=True,
blank=True,
null=True)
Now I have a subrace field that is dynamically update when the user chooses a Race.

Getting started building a template/view for a django model that joins two models together

I have a form where I can create and edit a group (a business really). Though I want to be able to say this business has many locations. I have the models written but the UI is giving me trouble.
I think mostly my question would be answered by how to update the Group model (creating/editing a group) and the GroupLocations model with a single form (adding an address as a new location if need be) so almost three models with a single form?
The models are:
class Address(models.Model):
city = models.CharField(max_length=50)
state = models.CharField(max_length=50)
zip_code = models.CharField(max_length=50)
address_line_one = models.CharField(max_length=50)
address_line_two = models.CharField(max_length=50, null=True, blank=True)
contact = models.CharField(max_length=50, null=True, blank=True)
phone = models.CharField(max_length=50)
fax = models.CharField(max_length=50, null=True, blank=True)
created_at=models.DateField(auto_now_add=True)
updated_at=models.DateField(auto_now=True)
def __str__(self):
return self.city
class Group(models.Model):
group_name = models.CharField(max_length=50)
group_contact= models.CharField(max_length=50)
tin = models.CharField(max_length=50)
npi =models.CharField(max_length=50)
notes = models.TextField(max_length = 255, null=True, blank=True)
billing_address = models.ForeignKey('Address', related_name = 'billing_address', on_delete=models.SET_NULL, null=True)
mailing_address = models.ForeignKey('Address', related_name = 'mailing_address', on_delete=models.SET_NULL, null=True, blank=True)
start_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True)
end_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True)
change_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True)
change_text = models.TextField(max_length = 255, null=True, blank=True)
term_comment = models.TextField(max_length = 255, null=True, blank=True)
group_phone=models.CharField(max_length=50)
group_fax = models.CharField(max_length=50)
group_term = models.ForeignKey(GroupTerm, on_delete=models.SET_NULL, null=True, blank=True) #quesiton is can a group be termed many times?
created_at=models.DateField(auto_now_add=True)
updated_at=models.DateField(auto_now=True)
#provider_location = models.ManyToManyField('ProviderLocations', through='GroupLocations')
def __str__(self):
return self.group_name
class GroupLocations(models.Model):
address = models.ForeignKey('Address', on_delete= models.SET_NULL, null=True)
group = models.ForeignKey('Group', on_delete=models.CASCADE)
doing_business_as = models.CharField(max_length = 255)
created_at=models.DateField(auto_now_add=True)
updated_at=models.DateField(auto_now=True)
def __str__(self):
return self.doing_business_as
I would love to (for this model and others) mimic how the admin handles users with the nice left and right multiple select boxes: (Though not sure how the add new location maybe a button to take you to another form that somehow knows its supposed to be added to the group as well?)
I realize this is a very large question I am looking for just mostly I think how to deal with several models on one form/template rails had a word for this (the name escapes me now) and not sure what the Django paradigm is.

How to get a list of all ForeignKey's in django

I'm trying to create a simple upload center with accounting .
I have a User and a File model like this :
class File(models.Model):
name = models.CharField(max_length=100)
path = models.CharField(max_length=255)
short_discripton = models.TextField(max_length=500, null=False)
upload_date = models.DateTimeField("Uploaded Date", auto_now_add=True)
def upload_date(self):
return timezone.datetime.now()
def __unicode__(self):
return self.name
class User(models.Model):
username = models.CharField(max_length=25, null=False, blank=False)
password = models.CharField(max_length=255, null=False, blank=False)
user_path = models.CharField(max_length=255, null=False, blank=False)
first_name = models.CharField(max_length=50, null=False, blank=False)
last_name = models.CharField(max_length=60, null=True, blank=True)
creation_date = models.DateTimeField("Register Date", auto_now_add=True)
files = models.ForeignKey(File, null=True, blank=True)
def __unicode__(self):
return self.userna
me
But when i try to retrieve the files using :
all_user_files = File.objects.get(pk=user.id)
It only returns one of the files though there is more files in the database(checking admin panel).
And the other way when i use :
user_all_files = user.files_set.all()
It will raise the error :
'User' object has no attribute 'files_set'
I'm really confused with that.Is there any other way ?
You need delete files = models.ForeignKey(File, null=True, blank=True)
And add to File (model) user= models.ForeignKey(User)
example here docs.djangoproject.com/en/1.8/topics/db/examples/many_to_one

Access A Specific Item In DB in my for statement

I have a somewhat odd scenario. I am using a read only database that I have access through my property management software. They allow the user to define fields in there software. However they don't show up as specific fields in the database. The database has 2 tables related to them propuserdefined and propuserdefinedvalues. The propuserdefined contains all the info about the field(id, name, description) the propuserdiefinedvalues contains the values associated with the property. It has propid, userdefinedid, and value. My question is this, I need to access the value of propuserdefinedvalues where propid equals the propid in my for property in properties statement and the userdefinedid equals 49. How would I do this? Is it with a template tag?
Thanks in advance for your help.
Brandon
Here are my models.
class Propuserdefined(models.Model):
userdefinedid = models.IntegerField(primary_key=True)
name = models.CharField(max_length=50L, blank=True)
type = models.IntegerField()
userid = models.IntegerField(null=True, blank=True)
updated = models.DateTimeField(null=True, blank=True)
datecreated = models.DateTimeField(null=True, blank=True)
combolist = models.TextField(blank=True)
class Meta:
db_table = 'propuserdefined'
class Propuserdefinedvalues(models.Model):
userdefinedid = models.IntegerField()
propid = models.IntegerField()
value = models.TextField(blank=True)
userid = models.IntegerField(null=True, blank=True)
updated = models.DateTimeField(null=True, blank=True)
datecreated = models.DateTimeField(null=True, blank=True)
class Meta:
db_table = 'propuserdefinedvalues'
class Property(models.Model):
propid = models.IntegerField(primary_key=True)
name = models.CharField(max_length=35L, blank=True)
shortname = models.CharField(max_length=6L, blank=True)
street1 = models.CharField(max_length=50L, blank=True)
street2 = models.CharField(max_length=50L, blank=True)
city = models.CharField(max_length=50L, blank=True)
state = models.CharField(max_length=2L, blank=True)
zip = models.CharField(max_length=50L, blank=True)
phone = models.CharField(max_length=21L, blank=True)
fax = models.CharField(max_length=50L, blank=True)
email = models.CharField(max_length=255L, blank=True)
manager = models.CharField(max_length=25L, blank=True)
billname1 = models.CharField(max_length=35L, blank=True)
billname2 = models.CharField(max_length=35L, blank=True)
billstreet1 = models.CharField(max_length=50L, blank=True)
billstreet2 = models.CharField(max_length=50L, blank=True)
billcity = models.CharField(max_length=50L, blank=True)
billstate = models.CharField(max_length=2L, blank=True)
billzip = models.CharField(max_length=50L, blank=True)
proptaxid = models.CharField(max_length=35L, blank=True)
rentchargetype = models.CharField(max_length=20L, blank=True)
lastpostdate = models.DateField(null=True, blank=True)
lastweeklypostdate = models.DateField(null=True, blank=True)
comments = models.CharField(max_length=25L, blank=True)
enablespeciallatecharge = models.IntegerField(null=True, blank=True)
fixedlatecharge = models.IntegerField(null=True, blank=True)
fixedlateamount = models.FloatField(null=True, blank=True)
fixedlaterentonly = models.IntegerField(null=True, blank=True)
percentlate = models.IntegerField(null=True, blank=True)
percentlateamount = models.FloatField(null=True, blank=True)
percentlatefullcharge = models.IntegerField(null=True, blank=True)
percentlaterentonly = models.IntegerField(null=True, blank=True)
perdaylate = models.IntegerField(null=True, blank=True)
perdaylateamount = models.FloatField(null=True, blank=True)
perdaylategrace = models.IntegerField(null=True, blank=True)
perdaylategracenum = models.IntegerField(null=True, blank=True)
perdatelatelimitamount = models.FloatField()
perdaylategracenonretro = models.IntegerField()
perdaylategraceexclweekends = models.IntegerField()
perdaylategraceexclholidays = models.IntegerField()
datecreated = models.DateTimeField(null=True, blank=True)
updated = models.DateTimeField(null=True, blank=True)
userid = models.IntegerField(null=True, blank=True)
logofile = models.CharField(max_length=255L, blank=True)
merchantid = models.CharField(max_length=255L, blank=True)
epaybankid = models.IntegerField()
epaylimit = models.FloatField()
epayenabled = models.IntegerField()
achconveniencefeeenabled = models.IntegerField()
ccconveniencefeeenabled = models.IntegerField()
rwaachconvenciencefeeenabled = models.IntegerField()
rwaccconveniencefeeenabled = models.IntegerField()
epayislimited = models.IntegerField()
epayusedefaults = models.IntegerField()
achconveniencefee = models.FloatField(null=True, blank=True)
ccconveniencefee = models.FloatField(null=True, blank=True)
rwaachconveniencefee = models.FloatField(null=True, blank=True)
rwaccconveniencefee = models.FloatField(null=True, blank=True)
epaychargetype = models.IntegerField()
epayamounttype = models.IntegerField()
epaysetamount = models.FloatField()
epaycustlimit = models.FloatField()
sqft = models.IntegerField()
lateminbalance = models.FloatField(null=True, blank=True)
defaultbank = models.IntegerField()
postday = models.IntegerField(null=True, blank=True)
active = models.IntegerField(null=True, blank=True)
iscommercial = models.IntegerField(null=True, blank=True)
assignedissueuserid = models.IntegerField(null=True, blank=True)
altname = Propuserdefinedvalues.objects.filter(userdefinedid=49)
class Meta:
db_table = 'property'
It sounds like you are attempting to do this in a Django template. You should instead be using Python code, because Django templates are not designed for this.
The Django models for the table also won't provide the nicest interface for accessing these properties. Instead you should create some functions on top of them. Alternatively you could write raw SQL that do joins across the two tables.
Using your models as they are (there are no ForeignKeys defined, so you can't use the ORM to follow relationships), you can get the details like this (if I understood your question correctly):
property = Property.objects.get(name='my_property_name') # or however you get the property
prop_user_defined_values = Propuserdefinedvalues.objects.filter(propid=property.id, userdefinedid=49)
However, this could be shorted if you changed the order of your models, and some of your fields to type ForiegnKey:
class Property(models.Model):
# ... rest truncated ...
class Propuserdefined(models.Model):
# ... rest truncated ...
class Propuserdefinedvalues(models.Model):
property = models.ForeignKey(Property, db_column='propid')
userdefined = models.ForeignKey(Propuserdefined, db_column='userdefinedid')
# ... rest truncated ...
This would let you do something like:
Propuserdefinedvalues.objects.filter(userdefined__name='my_name', property__name='my_property')
# or:
my_property = Property.objects.get(name='my_property')
Propuserdefinedvalues.objects.filter(userdefined__userdefinedid=49, property=my_property)
I suggest you read about Django's models here: https://docs.djangoproject.com/en/1.5/topics/db/models/ - they're quite easy to get right, even if you have pre-existing tables, as long as you know the relationships.
(Disclaimer: untested code! May be bugs ;))

Categories

Resources