I would like to create a model method that will take the “user” (which is a CharField) for
a given review and then return the “quote” associated with that user that is defined as part
of UserProfile. I am trying to create both the method as well as the template. The things I’ve tried so far haven’t seemed to work.
I know the best way to do this is probably make the “user” field within
Reviewbackup a ForeignKey to user, but I’d like to know how to be able to do it with a
method so I can learn.
models.py
class Reviewbackup(models.Model):
review = models.CharField('Review', max_length = 2000)
user = models.CharField('Username', max_length = 200)
rating = models.IntegerField(max_length=2, choices=RATING_OPTIONS)
product = models.ForeignKey(Productbackup)
def __unicode__(self):
return self.review
class UserProfile(models.Model):
user = models.OneToOneField(User)
quote = models.CharField('About', max_length = 200, null=True, blank=True)
website = models.URLField('Personal website/blog', null=True, blank=True)
facebook = models.URLField('Facebook profile page', max_length = 200, null=True, blank=True)
twitter = models.URLField('Twitter profile page', max_length = 200, null=True, blank=True)
youtube = models.URLField('YouTube channel page', max_length = 200, null=True, blank=True)
views.py
def view_reviews(request, product_name):
product = get_object_or_404(Productbackup, url_friendly=product_name)
product_id = product.id
#get reviews for the this product
reviews = Reviewbackup.objects.filter(product_id=product_id).order_by("-created_on")
return render_to_response('reserve/templates/view_reviews.html', {'reviews':reviews},
context_instance=RequestContext(request))
template
{% for review in reviews %}
{{review.user}}
<br>{{review.user.userprofile.quote}}
{% endfor %}
If condition of the problem says “not to use a ForeignKey for user, but use CharField for username” you may add the method to your Reviewbackup model like:
and use it in the template:
But you really should replace your user field to ForeignKey