Django Foreign Key query_set update through Views.py












0















As an extension of the polling app tutorial from the Django docs, I'm creating user profiles and I want to grab a particular user's response to each question and store it in the database, and be able to list all the responses of a user to all the questions when the user signs in. And also all responses to a question from all the users. The tutorial creates two models : Question and Choice.(Choice has Question as ForeignKey). But how do I attach a particular question's choice selected by a particular user, to that same User?



Here is my models.py



from django.db import models

import datetime
from django.utils import timezone

from django.contrib.auth.models import User

# Create your models here.
class Question(models.Model):
uzers = models.ManyToManyField(User)
question_text = models.CharField(max_length=100)
pub_date = models.DateTimeField('date published')

def __str__(self):
return self.question_text

def published_recently(self):
return self.pub_date > timezone.now()


class Choice(models.Model):
question = models.ForeignKey(Question, on_delete = models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)

def __str__(self):
return self.choice_text

class Response(models.Model):
uzer = models.ForeignKey(User, on_delete = models.CASCADE)
question = models.ForeignKey(Question, on_delete= models.CASCADE)
response = models.ForeignKey(Choice, on_delete = models.CASCADE)

def __str__(self):
return self.uzer + self.question + self.response



datetime.timedelta(days=1)


views.py :



from .models import Choice, Question, Response

from django.contrib.auth.models import User


def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:

selected_choice.votes += 1
q = selected_choice.question
c = selected_choice
r= Response(uzer=User, question = q,response =c )
r.save()

#User.response_set(question = selected_choice.question, response = selected_choice )
selected_choice.save()
User.save()


return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))


I also tried :
User.response_set.create(question = q, response = c)
Also tried replacing 'create' with 'add'. Didn't work.










share|improve this question

























  • Why not having a ForeignKey to User and Choice?

    – ger.s.brett
    Jan 2 at 9:40











  • Thanks brett. I should have been clearer. I have edited it for greater clarity.

    – vsingh
    Jan 4 at 10:11











  • So is your question where you get the user from? If yes - you need to have some kind of autorizsation - the easiest would be to use 'django.contrib.auth' and you need to protect your views from accessing them without login (@login_required). Details you can find in the docs: docs.djangoproject.com/en/2.1/topics/auth/default/…

    – ger.s.brett
    Jan 5 at 10:08
















0















As an extension of the polling app tutorial from the Django docs, I'm creating user profiles and I want to grab a particular user's response to each question and store it in the database, and be able to list all the responses of a user to all the questions when the user signs in. And also all responses to a question from all the users. The tutorial creates two models : Question and Choice.(Choice has Question as ForeignKey). But how do I attach a particular question's choice selected by a particular user, to that same User?



Here is my models.py



from django.db import models

import datetime
from django.utils import timezone

from django.contrib.auth.models import User

# Create your models here.
class Question(models.Model):
uzers = models.ManyToManyField(User)
question_text = models.CharField(max_length=100)
pub_date = models.DateTimeField('date published')

def __str__(self):
return self.question_text

def published_recently(self):
return self.pub_date > timezone.now()


class Choice(models.Model):
question = models.ForeignKey(Question, on_delete = models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)

def __str__(self):
return self.choice_text

class Response(models.Model):
uzer = models.ForeignKey(User, on_delete = models.CASCADE)
question = models.ForeignKey(Question, on_delete= models.CASCADE)
response = models.ForeignKey(Choice, on_delete = models.CASCADE)

def __str__(self):
return self.uzer + self.question + self.response



datetime.timedelta(days=1)


views.py :



from .models import Choice, Question, Response

from django.contrib.auth.models import User


def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:

selected_choice.votes += 1
q = selected_choice.question
c = selected_choice
r= Response(uzer=User, question = q,response =c )
r.save()

#User.response_set(question = selected_choice.question, response = selected_choice )
selected_choice.save()
User.save()


return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))


I also tried :
User.response_set.create(question = q, response = c)
Also tried replacing 'create' with 'add'. Didn't work.










share|improve this question

























  • Why not having a ForeignKey to User and Choice?

    – ger.s.brett
    Jan 2 at 9:40











  • Thanks brett. I should have been clearer. I have edited it for greater clarity.

    – vsingh
    Jan 4 at 10:11











  • So is your question where you get the user from? If yes - you need to have some kind of autorizsation - the easiest would be to use 'django.contrib.auth' and you need to protect your views from accessing them without login (@login_required). Details you can find in the docs: docs.djangoproject.com/en/2.1/topics/auth/default/…

    – ger.s.brett
    Jan 5 at 10:08














0












0








0








As an extension of the polling app tutorial from the Django docs, I'm creating user profiles and I want to grab a particular user's response to each question and store it in the database, and be able to list all the responses of a user to all the questions when the user signs in. And also all responses to a question from all the users. The tutorial creates two models : Question and Choice.(Choice has Question as ForeignKey). But how do I attach a particular question's choice selected by a particular user, to that same User?



Here is my models.py



from django.db import models

import datetime
from django.utils import timezone

from django.contrib.auth.models import User

# Create your models here.
class Question(models.Model):
uzers = models.ManyToManyField(User)
question_text = models.CharField(max_length=100)
pub_date = models.DateTimeField('date published')

def __str__(self):
return self.question_text

def published_recently(self):
return self.pub_date > timezone.now()


class Choice(models.Model):
question = models.ForeignKey(Question, on_delete = models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)

def __str__(self):
return self.choice_text

class Response(models.Model):
uzer = models.ForeignKey(User, on_delete = models.CASCADE)
question = models.ForeignKey(Question, on_delete= models.CASCADE)
response = models.ForeignKey(Choice, on_delete = models.CASCADE)

def __str__(self):
return self.uzer + self.question + self.response



datetime.timedelta(days=1)


views.py :



from .models import Choice, Question, Response

from django.contrib.auth.models import User


def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:

selected_choice.votes += 1
q = selected_choice.question
c = selected_choice
r= Response(uzer=User, question = q,response =c )
r.save()

#User.response_set(question = selected_choice.question, response = selected_choice )
selected_choice.save()
User.save()


return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))


I also tried :
User.response_set.create(question = q, response = c)
Also tried replacing 'create' with 'add'. Didn't work.










share|improve this question
















As an extension of the polling app tutorial from the Django docs, I'm creating user profiles and I want to grab a particular user's response to each question and store it in the database, and be able to list all the responses of a user to all the questions when the user signs in. And also all responses to a question from all the users. The tutorial creates two models : Question and Choice.(Choice has Question as ForeignKey). But how do I attach a particular question's choice selected by a particular user, to that same User?



Here is my models.py



from django.db import models

import datetime
from django.utils import timezone

from django.contrib.auth.models import User

# Create your models here.
class Question(models.Model):
uzers = models.ManyToManyField(User)
question_text = models.CharField(max_length=100)
pub_date = models.DateTimeField('date published')

def __str__(self):
return self.question_text

def published_recently(self):
return self.pub_date > timezone.now()


class Choice(models.Model):
question = models.ForeignKey(Question, on_delete = models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)

def __str__(self):
return self.choice_text

class Response(models.Model):
uzer = models.ForeignKey(User, on_delete = models.CASCADE)
question = models.ForeignKey(Question, on_delete= models.CASCADE)
response = models.ForeignKey(Choice, on_delete = models.CASCADE)

def __str__(self):
return self.uzer + self.question + self.response



datetime.timedelta(days=1)


views.py :



from .models import Choice, Question, Response

from django.contrib.auth.models import User


def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:

selected_choice.votes += 1
q = selected_choice.question
c = selected_choice
r= Response(uzer=User, question = q,response =c )
r.save()

#User.response_set(question = selected_choice.question, response = selected_choice )
selected_choice.save()
User.save()


return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))


I also tried :
User.response_set.create(question = q, response = c)
Also tried replacing 'create' with 'add'. Didn't work.







django database sqlite django-models






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 4 at 10:09







vsingh

















asked Jan 2 at 6:35









vsinghvsingh

112




112













  • Why not having a ForeignKey to User and Choice?

    – ger.s.brett
    Jan 2 at 9:40











  • Thanks brett. I should have been clearer. I have edited it for greater clarity.

    – vsingh
    Jan 4 at 10:11











  • So is your question where you get the user from? If yes - you need to have some kind of autorizsation - the easiest would be to use 'django.contrib.auth' and you need to protect your views from accessing them without login (@login_required). Details you can find in the docs: docs.djangoproject.com/en/2.1/topics/auth/default/…

    – ger.s.brett
    Jan 5 at 10:08



















  • Why not having a ForeignKey to User and Choice?

    – ger.s.brett
    Jan 2 at 9:40











  • Thanks brett. I should have been clearer. I have edited it for greater clarity.

    – vsingh
    Jan 4 at 10:11











  • So is your question where you get the user from? If yes - you need to have some kind of autorizsation - the easiest would be to use 'django.contrib.auth' and you need to protect your views from accessing them without login (@login_required). Details you can find in the docs: docs.djangoproject.com/en/2.1/topics/auth/default/…

    – ger.s.brett
    Jan 5 at 10:08

















Why not having a ForeignKey to User and Choice?

– ger.s.brett
Jan 2 at 9:40





Why not having a ForeignKey to User and Choice?

– ger.s.brett
Jan 2 at 9:40













Thanks brett. I should have been clearer. I have edited it for greater clarity.

– vsingh
Jan 4 at 10:11





Thanks brett. I should have been clearer. I have edited it for greater clarity.

– vsingh
Jan 4 at 10:11













So is your question where you get the user from? If yes - you need to have some kind of autorizsation - the easiest would be to use 'django.contrib.auth' and you need to protect your views from accessing them without login (@login_required). Details you can find in the docs: docs.djangoproject.com/en/2.1/topics/auth/default/…

– ger.s.brett
Jan 5 at 10:08





So is your question where you get the user from? If yes - you need to have some kind of autorizsation - the easiest would be to use 'django.contrib.auth' and you need to protect your views from accessing them without login (@login_required). Details you can find in the docs: docs.djangoproject.com/en/2.1/topics/auth/default/…

– ger.s.brett
Jan 5 at 10:08












0






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
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54002211%2fdjango-foreign-key-query-set-update-through-views-py%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































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.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54002211%2fdjango-foreign-key-query-set-update-through-views-py%23new-answer', 'question_page');
}
);

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







Popular posts from this blog

Monofisismo

Angular Downloading a file using contenturl with Basic Authentication

Olmecas