How do I set a ForeignKey based on the user account when I save a new element with the extra field of...
I have two problems:
1) I would like to add a new player in extra field of the Formset but when I save it I have an IntegrityError because
team = models.ForeignKey(Team, on_delete=models.CASCADE
is not set. I need that the value of team is
team=request.user.team
but I don't know where to put this in my views.py or if I need to override some existing function.
2) When I render the site at the end of each form appear the string "Human ptr:"... how can I delete it?
I have a form made with formset_factory rendered like this:
team_area.html
{% extends 'base_layout.html' %}
{% block content %}
<h1>Area Squadra</h1>
<form method="post" action="">
{% csrf_token %}
{{ player_formset.management_form }}
{% for player_form in player_formset %}
{% for field in player_form %}
{{ field.label_tag }} {{ field }}
{% endfor %}
<br>
{% endfor %}
<input type="submit" value="Aggiorna">
</form>
{% endblock %}
And the view is managed by:
views.py
from django.shortcuts import render, redirect
from skeleton.models import Player
from django.contrib.auth.decorators import login_required
from .forms import PlayerForm
from django.forms import modelformset_factory
# Create your views here.
@login_required(login_url="/accounts/login/")
def team_area(request):
PlayerFormSet = modelformset_factory(Player, fields=('first_name', 'last_name'), extra=1)
if request.method == "POST":
player_formset = PlayerFormSet(
request.POST,
request.FILES,
queryset=Player.objects.all().filter(team=request.user.team),)
if player_formset.is_valid():
player_formset.save()
return redirect('team_area:home')
else:
player_formset = PlayerFormSet(queryset=Player.objects.all().filter(team=request.user.team))
return render(request, 'team_area/team_area.html', {'player_formset': player_formset})
The Player model is:
class Human(models.Model):
SHIRT_SIZES = (('XXS', 'XXS'), ('XS', 'XS'), ('S', 'S'), ('M', 'M'), ('L', 'L'), ('XL', 'XL'), ('XXL', 'XXL'))
team = models.ForeignKey(Team, on_delete=models.CASCADE)
first_name = models.CharField(max_length=16)
last_name = models.CharField(max_length=16)
jersey_size = models.CharField(max_length=4, choices=SHIRT_SIZES, blank=True)
slug = models.SlugField(blank=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.first_name + ' ' + self.last_name)
super(Human, self).save(*args, **kwargs)
def __str__(self):
return self.first_name + ' ' + self.last_name
class Player(Human):
year_of_birth = models.IntegerField(validators=[MinValueValidator(1900), MaxValueValidator(2100)], blank=True, null=True)
jersey_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)], blank=True, null=True)
all_star_game = models.ForeignKey(AllStarGame, on_delete=models.CASCADE, blank=True, null=True)
python django django-models django-forms django-views
add a comment |
I have two problems:
1) I would like to add a new player in extra field of the Formset but when I save it I have an IntegrityError because
team = models.ForeignKey(Team, on_delete=models.CASCADE
is not set. I need that the value of team is
team=request.user.team
but I don't know where to put this in my views.py or if I need to override some existing function.
2) When I render the site at the end of each form appear the string "Human ptr:"... how can I delete it?
I have a form made with formset_factory rendered like this:
team_area.html
{% extends 'base_layout.html' %}
{% block content %}
<h1>Area Squadra</h1>
<form method="post" action="">
{% csrf_token %}
{{ player_formset.management_form }}
{% for player_form in player_formset %}
{% for field in player_form %}
{{ field.label_tag }} {{ field }}
{% endfor %}
<br>
{% endfor %}
<input type="submit" value="Aggiorna">
</form>
{% endblock %}
And the view is managed by:
views.py
from django.shortcuts import render, redirect
from skeleton.models import Player
from django.contrib.auth.decorators import login_required
from .forms import PlayerForm
from django.forms import modelformset_factory
# Create your views here.
@login_required(login_url="/accounts/login/")
def team_area(request):
PlayerFormSet = modelformset_factory(Player, fields=('first_name', 'last_name'), extra=1)
if request.method == "POST":
player_formset = PlayerFormSet(
request.POST,
request.FILES,
queryset=Player.objects.all().filter(team=request.user.team),)
if player_formset.is_valid():
player_formset.save()
return redirect('team_area:home')
else:
player_formset = PlayerFormSet(queryset=Player.objects.all().filter(team=request.user.team))
return render(request, 'team_area/team_area.html', {'player_formset': player_formset})
The Player model is:
class Human(models.Model):
SHIRT_SIZES = (('XXS', 'XXS'), ('XS', 'XS'), ('S', 'S'), ('M', 'M'), ('L', 'L'), ('XL', 'XL'), ('XXL', 'XXL'))
team = models.ForeignKey(Team, on_delete=models.CASCADE)
first_name = models.CharField(max_length=16)
last_name = models.CharField(max_length=16)
jersey_size = models.CharField(max_length=4, choices=SHIRT_SIZES, blank=True)
slug = models.SlugField(blank=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.first_name + ' ' + self.last_name)
super(Human, self).save(*args, **kwargs)
def __str__(self):
return self.first_name + ' ' + self.last_name
class Player(Human):
year_of_birth = models.IntegerField(validators=[MinValueValidator(1900), MaxValueValidator(2100)], blank=True, null=True)
jersey_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)], blank=True, null=True)
all_star_game = models.ForeignKey(AllStarGame, on_delete=models.CASCADE, blank=True, null=True)
python django django-models django-forms django-views
add a comment |
I have two problems:
1) I would like to add a new player in extra field of the Formset but when I save it I have an IntegrityError because
team = models.ForeignKey(Team, on_delete=models.CASCADE
is not set. I need that the value of team is
team=request.user.team
but I don't know where to put this in my views.py or if I need to override some existing function.
2) When I render the site at the end of each form appear the string "Human ptr:"... how can I delete it?
I have a form made with formset_factory rendered like this:
team_area.html
{% extends 'base_layout.html' %}
{% block content %}
<h1>Area Squadra</h1>
<form method="post" action="">
{% csrf_token %}
{{ player_formset.management_form }}
{% for player_form in player_formset %}
{% for field in player_form %}
{{ field.label_tag }} {{ field }}
{% endfor %}
<br>
{% endfor %}
<input type="submit" value="Aggiorna">
</form>
{% endblock %}
And the view is managed by:
views.py
from django.shortcuts import render, redirect
from skeleton.models import Player
from django.contrib.auth.decorators import login_required
from .forms import PlayerForm
from django.forms import modelformset_factory
# Create your views here.
@login_required(login_url="/accounts/login/")
def team_area(request):
PlayerFormSet = modelformset_factory(Player, fields=('first_name', 'last_name'), extra=1)
if request.method == "POST":
player_formset = PlayerFormSet(
request.POST,
request.FILES,
queryset=Player.objects.all().filter(team=request.user.team),)
if player_formset.is_valid():
player_formset.save()
return redirect('team_area:home')
else:
player_formset = PlayerFormSet(queryset=Player.objects.all().filter(team=request.user.team))
return render(request, 'team_area/team_area.html', {'player_formset': player_formset})
The Player model is:
class Human(models.Model):
SHIRT_SIZES = (('XXS', 'XXS'), ('XS', 'XS'), ('S', 'S'), ('M', 'M'), ('L', 'L'), ('XL', 'XL'), ('XXL', 'XXL'))
team = models.ForeignKey(Team, on_delete=models.CASCADE)
first_name = models.CharField(max_length=16)
last_name = models.CharField(max_length=16)
jersey_size = models.CharField(max_length=4, choices=SHIRT_SIZES, blank=True)
slug = models.SlugField(blank=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.first_name + ' ' + self.last_name)
super(Human, self).save(*args, **kwargs)
def __str__(self):
return self.first_name + ' ' + self.last_name
class Player(Human):
year_of_birth = models.IntegerField(validators=[MinValueValidator(1900), MaxValueValidator(2100)], blank=True, null=True)
jersey_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)], blank=True, null=True)
all_star_game = models.ForeignKey(AllStarGame, on_delete=models.CASCADE, blank=True, null=True)
python django django-models django-forms django-views
I have two problems:
1) I would like to add a new player in extra field of the Formset but when I save it I have an IntegrityError because
team = models.ForeignKey(Team, on_delete=models.CASCADE
is not set. I need that the value of team is
team=request.user.team
but I don't know where to put this in my views.py or if I need to override some existing function.
2) When I render the site at the end of each form appear the string "Human ptr:"... how can I delete it?
I have a form made with formset_factory rendered like this:
team_area.html
{% extends 'base_layout.html' %}
{% block content %}
<h1>Area Squadra</h1>
<form method="post" action="">
{% csrf_token %}
{{ player_formset.management_form }}
{% for player_form in player_formset %}
{% for field in player_form %}
{{ field.label_tag }} {{ field }}
{% endfor %}
<br>
{% endfor %}
<input type="submit" value="Aggiorna">
</form>
{% endblock %}
And the view is managed by:
views.py
from django.shortcuts import render, redirect
from skeleton.models import Player
from django.contrib.auth.decorators import login_required
from .forms import PlayerForm
from django.forms import modelformset_factory
# Create your views here.
@login_required(login_url="/accounts/login/")
def team_area(request):
PlayerFormSet = modelformset_factory(Player, fields=('first_name', 'last_name'), extra=1)
if request.method == "POST":
player_formset = PlayerFormSet(
request.POST,
request.FILES,
queryset=Player.objects.all().filter(team=request.user.team),)
if player_formset.is_valid():
player_formset.save()
return redirect('team_area:home')
else:
player_formset = PlayerFormSet(queryset=Player.objects.all().filter(team=request.user.team))
return render(request, 'team_area/team_area.html', {'player_formset': player_formset})
The Player model is:
class Human(models.Model):
SHIRT_SIZES = (('XXS', 'XXS'), ('XS', 'XS'), ('S', 'S'), ('M', 'M'), ('L', 'L'), ('XL', 'XL'), ('XXL', 'XXL'))
team = models.ForeignKey(Team, on_delete=models.CASCADE)
first_name = models.CharField(max_length=16)
last_name = models.CharField(max_length=16)
jersey_size = models.CharField(max_length=4, choices=SHIRT_SIZES, blank=True)
slug = models.SlugField(blank=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.first_name + ' ' + self.last_name)
super(Human, self).save(*args, **kwargs)
def __str__(self):
return self.first_name + ' ' + self.last_name
class Player(Human):
year_of_birth = models.IntegerField(validators=[MinValueValidator(1900), MaxValueValidator(2100)], blank=True, null=True)
jersey_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)], blank=True, null=True)
all_star_game = models.ForeignKey(AllStarGame, on_delete=models.CASCADE, blank=True, null=True)
python django django-models django-forms django-views
python django django-models django-forms django-views
asked 2 days ago
Lorenzo Fiamingo
808
808
add a comment |
add a comment |
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53945373%2fhow-do-i-set-a-foreignkey-based-on-the-user-account-when-i-save-a-new-element-wi%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53945373%2fhow-do-i-set-a-foreignkey-based-on-the-user-account-when-i-save-a-new-element-wi%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown