I am trying to create an application where you can create project-based expenses, and each project should have a list of approvers who will approve the expense once uploaded to the project, how do I replicate this in Django.
What I tried to do.
I got the approvers into the form as a ModelMultipleChoiceField
self.fields['approvers'] = forms.ModelMultipleChoiceField(queryset=Profile.objects.all())
and saved it as a list into the database
def getApprovers(approvers):
id = []
for profile in approvers:
id.append(profile.id)
return id
in project create function
project.approvers = getApprovers(form.cleaned_data['approvers'])
I created a templatetag to display the list of approvers as the Profile Queryset objects. I tried to iterate over the saved list of approvers, but I keep getting errors
def approvers_list(approvers):
for profile in list(approvers):
profiles = [Profile.objects.filter(pk = i) for i in
list(approvers)]
return profile
I got this error
Field 'id' expected a number but got '['.
This is the result I got after changing the approvers_list method
def approvers_list(approvers):
p = []
for profile in list(approvers):
p.append(profile)
return p
This is the result
['[', '1', ',', ' ', '2', ',', ' ', '3', ']']
How can I turn this into a list of ids, so I can use it to get individual profiles of the approvers?
How can I get this to work best?
Here are the models
class Project(MiscClass):
owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True)
organisation = models.ForeignKey(Organisation, on_delete=models.SET_NULL, null=True, blank=True)
title = models.CharField(max_length=200, null=True, blank=True, unique=True)
slug = models.SlugField(max_length=500, null=True, blank=True, unique=True)
category = models.ForeignKey('Category', on_delete=models.CASCADE, null=True, blank=True)
description = models.TextField(null=True, blank=True)
approvers = models.CharField(max_length=100, null=True, blank=True, validators=[int_list_validator])
class Meta:
ordering = ['-created']
def __str__(self):
return str(self.title)
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Project, self).save(*args, **kwargs)
class Expense(MiscClass):
PROCESSING = 1
APPROVED = 2
DECLINED = 3
APPROVAL_STATUS = (
(PROCESSING, 'Processing'),
(APPROVED, 'Approved'),
(DECLINED, 'Declined')
)
owner = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True)
title = models.CharField(max_length=300, null=True)
slug = models.SlugField(max_length=300 , null=True, unique=True)
amount = models.CharField(max_length=200, null=True, blank=True)
status = models.IntegerField(choices=APPROVAL_STATUS, default=PROCESSING)
description = models.TextField(blank=True, null=True)
refrence_number = models.CharField(max_length=300, unique=True, null=True)
category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True, blank=True)
date_due = models.DateTimeField(auto_now_add=False, null=True, blank=True)
merchant = models.CharField(max_length=200, null=True, blank=True)
expense_date = models.DateTimeField(auto_now_add=False, null=True, blank=True)
def __str__(self):
return str(self.title)
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
return super(Expense, self).save(*args, **kwargs)
Related
I am trying to filter my many to many variation fields with respect to the product. means, I only want the variations related to the current product to show in the admin page. now its showing all the variations available for every product.
I added formfield_for_manytomany() function to my admin.py but how can I get the current product(id) in the cart or order to filter the variations?
most of the questions in stack overflow Is based on the current user, which is easy to get? but how should I get the specific product(id) that is opened in the admin panel.
admin.py
from django.contrib import admin
from .models import *
from products.models import Variation
class CartAdmin(admin.ModelAdmin):
list_display = ('cart_id', 'date_created')
class CartItemAdmin(admin.ModelAdmin):
list_display = ('user','cart', 'product', 'quantity','is_active')
def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == "variation":
product = Products.objects.get(id='??') # how I get the current product in the cart or order
kwargs["queryset"] = Variation.objects.filter(product=product.id)
return super().formfield_for_manytomany(db_field, request, **kwargs)
admin.site.register(Cart, CartAdmin)
admin.site.register(CartItem, CartItemAdmin)
CartItem Model
class CartItem(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True)
cart = models.ForeignKey(Cart, on_delete=models.CASCADE, null=True)
product = models.ForeignKey(Products, on_delete=models.CASCADE)
variation = models.ManyToManyField(Variation, blank=True)
quantity = models.IntegerField()
is_active = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True)
def item_total(self):
return self.product.price * self.quantity
def __str__(self):
return self.product.name
Product and Variation Model
class Products(models.Model):
name = models.CharField(max_length=50, unique=True)
slug = AutoSlugField(populate_from='name', max_length=100, unique=True)
isbn = models.CharField(max_length=20, unique=True, blank=True, null=True)
sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
language = models.ForeignKey(Language, on_delete=models.SET_NULL, null=True)
author = models.CharField(max_length=100)
Publisher = models.CharField(max_length=100, blank=True, default=None)
release_date = models.DateField(blank=True, null=True, default=None)
price = models.IntegerField(default=None)
stock = models.IntegerField(default=None)
is_available = models.BooleanField(default=True)
cover_image = models.ImageField(upload_to='images/products')
image1 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
image2 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
image3 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
description = models.TextField(max_length=2000, blank=True, default=None)
create_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
number_of_pages = models.IntegerField(blank=True, null=True)
weight = models.IntegerField(blank=True, null=True)
width = models.IntegerField(blank=True, null=True)
height = models.IntegerField(blank=True, null=True)
spine_width = models.IntegerField(blank=True, null=True)
class Meta:
verbose_name = 'Product'
verbose_name_plural = 'Products'
def get_url(self):
return reverse('product-view', args=[self.slug])
def __str__(self):
return self.name
class Variation(models.Model):
product = models.ForeignKey(Products, on_delete=models.CASCADE)
variation_category = models.CharField(max_length=100, choices=variation_category_choice)
variation_value = models.CharField(max_length=100, choices=variation_value_choice)
is_available = models.BooleanField(default=True)
date_added = models.DateTimeField(auto_now_add=True)
objects = VariationManager()
def __str__(self):
return self.variation_value
I am trying to make django urls suitable for the seo. I want to send Id and slug in the same url.I don't want to use slug I only want to show in the url.But i am getting an error. My model looks like this:
class Oyunlar(models.Model):
game_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=10000)
platform = models.CharField(max_length=10)
image = models.CharField(max_length=255, blank=True, null=True)
release_date = models.DateField(blank=True, null=True)
click_count = models.IntegerField()
categories=models.ManyToManyField(Kategoriler,through='OyunlarKategoriler')
base_price=models.DecimalField(default=0,max_digits=65535, decimal_places=2)
big_discount=models.BooleanField(default=False)
en_ucuz = models.DecimalField(default=0,max_digits=65535, decimal_places=2)
popularite = models.IntegerField(blank=True, null=True,default=0)
discount_rate = models.DecimalField(max_digits=65535, decimal_places=2)
title_edit = models.CharField(max_length=500, blank=True, null=True)
description = models.CharField(max_length=100000, blank=True, null=True)
steam_id = models.CharField(max_length=1000, blank=True, null=True)
metacritic = models.FloatField(blank=True, null=True)
recommendation = models.BigIntegerField(blank=True, null=True)
full_game = models.BooleanField(blank=True, null=True)
age = models.CharField(max_length=500, blank=True, null=True)
minimum = models.CharField(max_length=10000, blank=True, null=True)
recommended = models.CharField(max_length=10000, blank=True, null=True)
developer = models.CharField(max_length=500, blank=True, null=True)
publisher = models.CharField(max_length=500, blank=True, null=True)
oyun_foto = ArrayField(models.CharField(max_length=10000, blank=True, null=True)) # This field type is a guess.
windows = models.BooleanField(blank=True, null=True)
mac = models.BooleanField(blank=True, null=True)
linux = models.BooleanField(blank=True, null=True)
class Meta:
managed = False
db_table = 'oyunlar'
def __str__(self):
return self.title
Urls.py
path('<int:game_id>/<slug:slug>/',views.oyun,name='detail'),
views.py
def oyun(request,slug,game_id):
print(slug)
oyun=Oyunlar.objects.get(pk=game_id)
comments=Comments.objects.filter(oyunlar=oyun)
game_price=GamePrice.objects.filter(game_id=game_id).order_by('price')
categories = OyunlarKategoriler.objects.filter(game=oyun).values_list('category_id', flat=True)
benzer = Oyunlar.objects.filter(categories__category_id__in=categories, platform=oyun.platform).order_by('-click_count').distinct()[:4]
print(request.method)
if request.method == 'POST':
cf = CommentForm(request.POST or None)
print('burda')
if cf.is_valid():
print('valid')
text = request.POST.get('text')
comment = Comments.objects.create(oyunlar=oyun, user=request.user, text=text)
comment.save()
return redirect(oyun.get_absolute_url())
else:
cf = CommentForm()
return render(request,'product-simple.html',{'oyun':oyun,'game_price':game_price,'benzer':benzer,'comment_form':cf,'comments':comments})
Helper Tag
#register.filter
def slug(value):
return slugify(unidecode(value))
html
<a href="{% url 'detail' i.game_id i.title|slug %}"
But I am getting an error:
Error
Reverse for 'detail' with arguments '(32147,)' not found. 1 pattern(s) tried: ['(?P<game_id>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)/$']
In the following code, for some reason, after using the foreign key for the project name, at the def __str__(self): part, on the 2nd like where it says
return self.Project + ' (' + self.Situation_Type + ') ' + ' [' + self.Status + '] ' at the self.Project part, it shows me an error saying,
class 'Project' does not define '_add_', so the '+' operator cannot be used on its instances
This inspection detects names that should resolve but dont. Due to dynamic dispatch and ducttyping, this is possible in a limited but useful number of cases. Top-level and class level items are supported better than instance items.
Ever since this error started coming up, My Projects page has been displaying nothing in the list, but it says that there is 1 item. What could be the issue?
from django.db import models
# Create your models here.
from django.contrib.auth.models import User
from django.db import models
from django.core.mail import EmailMessage
# Create your models here.
class Project(models.Model):
STATUS_CHOICE = (
('Project Manager', 'Project Manager'),
('Technician', 'Technician'),
('Tester', 'Tester')
)
STATUS_CHOICE_1 = (
('Work Assigned', 'Work Assigned'),
('Work in Progress', 'Work in Progress'),
('Testing', 'Testing'),
('Completed', 'Completed')
)
Project_Name = models.CharField(max_length=100)
Project_Description = models.CharField(max_length=100)
Admin_Name = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Admin_Name_users+')
Admin_Mail_ID = models.EmailField(max_length=50)
Project_Manager_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Project_Manager_1_users+')
Project_Manager_1_Mail_ID = models.EmailField(max_length=50)
Project_Manager_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Project_Manager_2_users+', blank=True, null=True)
Project_Manager_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Technician_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Technician_1_users+')
Technician_1_Mail_ID = models.EmailField(max_length=50)
Technician_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Technician_2_users+', blank=True, null=True)
Technician_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Technician_3 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Technician_3_users+', blank=True, null=True)
Technician_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Tester_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Tester_1_users+')
Tester_1_Mail_ID = models.EmailField(max_length=50, default='Example#gmail.com')
Additional_User_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Ad_1_users+', blank=True, null=True)
Additional_User_1_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_1_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Additional_User_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Ad_1_users+', blank=True, null=True)
Additional_User_2_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Additional_User_3 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Ad_1_users+', blank=True, null=True)
Additional_User_3_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Status_of_the_project = models.CharField(max_length=18, choices=STATUS_CHOICE_1)
Created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
Finish_Date = models.DateTimeField(null=True, blank=True)
Supporting_Documents = models.FileField(null=True, blank=True)
def __str__(self):
return self.Project_Name
class Meta:
verbose_name_plural = "List Of Projects"
class Bug(models.Model):
STATUS_CHOICE = (
('Unassigned', 'Unassigned'),
('Assigned', 'Assigned'),
('Testing', 'Testing'),
('Tested', 'tested'),
('Fixed', 'Fixed')
)
STATUS_CHOICE_1 = (
('Bug', 'Bug'),
('Issue', 'Issue'),
('Enhancement', 'Enhancement'),
('Not an issue or bug', 'Not an issue or bug'),
('Fixed', 'Fixed')
)
Project = models.ForeignKey(Project, on_delete=models.CASCADE)
Issue_Title = models.CharField(max_length=50, blank=True, null=True)
Situation_Type = models.CharField(max_length=25, choices=STATUS_CHOICE_1)
Basic_Description = models.CharField(max_length=100)
Detailed_Description = models.TextField(default='The Description, here.')
Status = models.CharField(max_length=18, choices=STATUS_CHOICE)
Assigned_to = models.ForeignKey(User, on_delete=models.CASCADE)
Assigned_to_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Admin_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Reported_by = models.CharField(max_length=50, blank=True, null=True)
Reporters_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Reported_Date = models.DateTimeField(null=True, blank=True)
Created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
Updated = models.DateTimeField(auto_now=True, null=True, blank=True)
Deadline_Date = models.DateTimeField(null=True, blank=True)
Supporting_Documents_By_Reporter = models.FileField(null=True, blank=True)
Project_Managers_Comment = models.TextField(default='The Description, here.')
Supporting_Documents_by_Project_Manager = models.FileField(null=True, blank=True)
Technicians_Comment = models.TextField(default='The Description, here.')
Supporting_Documents_by_Technician = models.FileField(null=True, blank=True)
Testers_Comment = models.TextField(default='The Description, here.')
Supporting_Documents_by_Tester = models.FileField(null=True, blank=True)
def __str__(self):
return self.Project + ' (' + self.Situation_Type + ') ' + ' [' + self.Status + '] '
def send_mail(admin,ass):
email=EmailMessage('Changes made to Task','Changes have been made to one of your Task reports and we hereby request you to have a look at it at the earliest.', to=[admin,ass])
email.send()
def send_mail(admin,ass):
email=EmailMessage('Changes made to Task','Changes have been made to one of your Task reports and we hereby request you to have a look at it at the earliest.', to=[admin,ass])
email.send()
Here's the code from my admin.py
from django.contrib import admin
from .models import Bug, Project
from django.contrib.admin.models import LogEntry
admin.site.register(LogEntry)
# Register your models here.
class BugDisplay(admin.ModelAdmin):
list_display = ('Project', 'Status', 'Basic_Description', 'Assigned_to', 'Created', 'Updated')
list_filter = ('Status', 'Assigned_to', 'Project')
search_fields = ('Reporters_Mail_ID', 'Reported_by', 'Basic_Description',)
admin.site.register(Bug, BugDisplay)
# Register your models here.
#admin.register(Project)
class ProjectDisplay(admin.ModelAdmin):
list_display = ('Project_Name','Admin_Name', 'Project_Manager_1', 'Status_of_the_project')
list_filter = ('Admin_Name', 'Project_Manager_1', 'Status_of_the_project')
search_fields = ('Project_Name', 'Project_Description', 'Admin_Name', 'Admin_Mail_ID', 'Project_Manager_1 '
'Project_Manager_1_Mail_ID', 'Project_Manager_2 ', 'Project_Manager_2_Mail_ID',
'Technician_1',
'Technician_1_Mail_ID', 'Technician_2', 'Technician_2_Mail_ID', 'Technician_3',
'Technician_3_Mail_ID', 'Tester_1', 'Tester_1_Mail_ID', 'Additional_User_1', 'Additional_User_1_Type',
'Additional_User_1_Mail_ID', 'Additional_User_2', 'Additional_User_2_Type', 'Additional_User_2_Mail_ID',
'Additional_User_3', 'Additional_User_3_Type', 'Additional_User_3_Mail_ID', 'Status_of_the_project', 'Created',
'Finish_Date', 'Supporting_Documents'
)
Well self.Project (actually the convention is to name such attributes project, not Project) is a Project object.
Now you write:
self.Project + '('
(some extra additions as well, but those are not relevant here, at least not directly).
So that means that you want to add a Project instance and a string instance together. But since you did not tell Python how to do that (by overriding the __add__ function), this can not be done, but I don't think you want to do that anyway.
What you probably want to do, is first convert the self.Project to its string representation. We can do that with string formatting:
def __str__(self):
return '{} ({}) [{}]'.format(self.Project, self.Situation_Type, self.Status)
Here the parmeters will be converted to their textual counterparts automatically. Furthermore this is also a neater way to produce a string. In the original code, it might be hard to find out that there are two spaces between the ) and [, here we see that immediately (perhaps you want to change that).
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.
I can create new custom user profile with create_profile pipeline function. But also I want to update profile details, if user (or profiles) exist. I couldn't figure out what I need add this function.
utils.py
def create_profile(strategy, backend, details, response, user, *args, **kwargs):
if Profiles.objects.filter(user=user).exists():
if backend.name == 'facebook':
Profiles(user=user).gender = response.get('gender')
Profiles(user=user).fb_link = response.get('link')
Profiles(user=user).timezone = response.get('timezone')
Profiles(user=user).birthdate = response.get('birthday')
Profiles(user=user).email = response.get('email')
Profiles(user=user).fb_id = response.get('id')
else:
new_profile = Profiles(user=user)
if backend.name == 'facebook':
new_profile.gender = response.get('gender')
new_profile.fb_link = response.get('link')
new_profile.timezone = response.get('timezone')
new_profile.birthday = response.get('birthday')
new_profile.email = response.get('email')
new_profile.fb_id = response.get('id')
new_profile.save()
return kwargs
myapp.models.py
class Profiles(models.Model):
user = models.OneToOneField(User, unique=True, null=True)
first_name = models.CharField(max_length=250, blank=True, null=True)
last_name = models.CharField(max_length=250, blank=True, null=True)
middle_name = models.CharField(max_length=200, blank=True, null=True, default="")
profile_img = models.URLField(upload_to='avatars/',null=True, blank=True, default="http://www.murketing.com/journal/wp-content/uploads/2009/04/brightkite.png")
birthdate = models.DateField(null=True, blank=True)
locale = models.CharField(max_length=250, blank=True, null=True)
email = models.CharField(max_length=250, blank=True, null=True)
fb_id = models.BigIntegerField(blank=True, null=True, verbose_name='Facebook ID')