Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change the prepopulated_fields for Page model?
I am use custom field "full_title" instead of "title". I need the servants to be automatically filled in the admin panel, as it was by default. Where to fix the code, so that the slug pulls data from full_it instead of title? -
Get objects from current site without settings.SITE_ID
I'm looking for the same functionality as the CurrentSiteManager provides but without having to specify SITE_ID in settings.py as the CurrentSiteManager requires. Information about the current site should come from the request. My take on the problem would be to make a custom manager, but is there something I'm missing? What would be a good way of doing this? It seems quite trivial that the CurrentSiteManager should provide this functionality. Would it make sense to submit a feature request? -
Why does a Django HttpRequest (POST) appear to set request.data to the value of the "data" key from request.body?
Background I have a Django wsgi application which also makes use of django-rest-framework. A POST request is made to my application which has a JSON payload containing the key "data", eg. {'meta': {'some': 'stuff'}, 'data': {'other': 'stuff'}} I have noticed that the WSGIRequest object (as soon as it gets initialized, ie. not a django-rest-framework request object yet) has request.body containing the full payload, but request.data containing the value of request.body['data']. My application has been written to depend on the fact that only the "data" key value is present in request.data. I recently upgraded Django from 1.6 to 1.11 and django-rest-framework from 2.3.8 to 3.8.2. The newer version of DRF implements its own request.data whereas before it was just proxying it to the underlying Django request object. The new implementation sets request.data to the parsed request.body. This breaks my application further down the line. Question I can't find any indication in the source code or elsewhere that request.data should be different from request.body. To the contrary, several questions seem to take it for granted that they are the same. Can anyone help me in figuring out if I have found a bug or if this is expected behaviour? Is my application … -
ModuleNotFoundError: No module named 'myproject.wsgi' - Gunicorn, Redhat 7, Django 2.0
I am trying to deploy a Django Application on RHEL 7. I have setup a virtualenv with Python 3.6 Here is my executable gunicorn_start file. #!/bin/bash NAME="Garage" DJANGODIR=/opt/garage/garage USER=user1 GROUP=user1 WORKERS=3 BIND=unix:/opt/garage/run/gunicorn.sock DJANGO_SETTINGS_MODULE=garage.settings DJANGO_WSGI_MODULE=garage.wsgi LOGLEVEL=error cd $DJANGODIR source venv/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH exec venv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOGLEVEL \ --log-file=- Here is my gunicorn.service file [Unit] Description=gunicorn daemon After=network.target [Service] User=user1 Group=user1 WorkingDirectory=/opt/garage ExecStart=/opt/garage/gunicorn_start [Install] WantedBy=multi-user.target I start gunicorn with this commands sudo systemctl start gunicorn sudo systemctl enable gunicorn After starting Gunicorn i check status with sudo systemctl enable gunicorn I get the error ModuleNotFoundError: No module named 'garage.wsgi' -
Word frequency count within record with Django model Manager
I am building a Django app that works with a text-heavy database, and it counts some predefined phrases within the text. It does not count the number of records that contain the phrases, but it counts the frequency within one record. And here is where i am stuck: Django does count and find phrases if i add the string directly: frequency = 'Search this text for me, please'.count('this text') When i use this logic with a model Manager, "count" does not work, and gives the error: Typeerror: count() takes 1 positional argument but 2 were given This is my code in model.py class MyModelManager(models.Manager): def get_queryset(self): qs = super(MyModelManager, self).get_queryset().values_list('mytext').count('this text') return qs class MyModel(models.Model): mytext = models.TextField() ... objects = MyModelManager() Can you please suggest me how should i continue? Am i on the right track or should i apply a totally different approach to make this working? Thanks! -
Django: Reading file from user and returning result
I have an app that allows the user to upload a .txt file. Once uploaded, I want to see if that file has a word in it, e.g "hello". I'm unsure how to do this as users will upload files with different names. I have a function outside of the project that does this, but the name of the file is given. It essentially reads the file, splits it into words and then checks if words from the file exist in cv_list. See below: import nltk from nltk.tokenize import word_tokenize cv_list = ['hello', 'hi'] sCV = open("cv.txt","r").read().lower() cv = nltk.word_tokenize(sCV) def tWords(): #print(cv) t_words = set(word for word in cv if word in cv_list) print("Words found: " + t_words) tWords() How can I incorporate this into my Django project without needing the exact name of the file? I assume I need a file handler as mentioned here, but I'm having trouble with it. My code for django is below: settings.py INSTALLED_APPS = [ 'uploader.apps.UploaderConfig',] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from uploader import views as uploader_views urlpatterns = [ url(r'^admin/', admin.site.urls), url('', … -
The advantage of `super_new = super().__new__` over conventional class?
I am following Django codes to understand its internal machanism of Models django/base.py class ModelBase(type): """Metaclass for all models.""" def __new__(cls, name, bases, attrs, **kwargs): super_new = super().__new__ # Also ensure initialization is only performed for subclasses of Model # (excluding Model class itself). parents = [b for b in bases if isinstance(b, ModelBase)] if not parents: return super_new(cls, name, bases, attrs) I searched the difference between __new__ and __init__, but still find super_new = super().__new__ very tricky to interpret. What's its advantage over a conventional definded class? -
Creating user accounts for pre-registered users in Django
I have a website that has a registration system and a blog with some registered users. Yesterday, I added a new app that creates dedicated profile pages for each one of those users. The issue being, the profile pages aren't getting created for the users that have already registered. This is, I guess because the user profile creation logic allows for profile creations only after the user has registered. Below is the code in my models.py from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=User) def create_account(sender, instance, created, *args, **kwargs): if created: profile, new = UserAccount.objects.get_or_create(user=instance) post_save.connect(create_account, sender=settings.AUTH_USER_MODEL) So, what can I do to create those profile pages? I tried the following: 1. Manually creating a profile page against each registered users' username. (But this isn't the way I want to lean on. This is just a temporary arrangement) Issue with this, when the superuser who creates these profile pages calls for his private profile page [at /u/], the code looks towards all the users created by the superuser instead of his own. This is the error that's shown: MultipleObjectsReturned at /u/ get() returned more than one UserAccount -- it returned 2! . . . instance = get_object_or_404(UserAccount) … -
Change Serialised JSON output
In my Django project I have a django rest framework serialiser class CarSerializer(serializers.ModelSerializer): that takes a filtered query set and then serialises it. I then use JSONRenderer().render( testserializer.data ) to convert it to JSON The issue I face is that I need to change the output, currently I get this: b'[{"car_age":"1","car_type":"1"},{"car_age":"4","car_type":"2"}]' But I want the return response in the views to have this json payload: {“cars”:[{"car_age":"1","car_type":"1"},{"car_age":"4","car_type":"2"}]} Any help in achieving this would be greatly appreciated, thanks. -
Why django loads replaced image?
I am using Python 2.7.13 and Django version 1.8.17 for my project, I've placed 4 images namely image1.jpg , image2.jpg , image3.jpg and image4.jpg in the static/homepage directory of my app. Problem: I have replaced the image1.jpg with other image using the same name. But django still loads the replaced(deleted) image, when the html page is requested. If I change the name of image1.jpg to some other name example imagex.jpg. The page is loading fine with new(existing) image of static/homepage as carousel but If I again change the name to image1.jpg. It loads the replaced image that I have replaced by a new image. Template with bootstrap 3 included: <!--Carousel --> <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> <li data-target="#myCarousel" data-slide-to="2"></li> <li data-target="#myCarousel" data-slide-to="3"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="item active"> <img src="{% static 'homepage/image1.jpg' %}" alt="Image1"> </div> <div class="item"> <img src="{% static 'homepage/image2.jpg' %}" alt="Image2"> </div> <div class="item"> <img src="{% static 'homepage/image3.jpg' %}" alt="Image3"> </div> <div class="item"> <img src="{% static 'homepage/image4.jpg' %}" alt="Image4"> </div> </div> <!-- Left and right controls --> <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> … -
RuntimeError: main thread is not in main loop using Matplotlib with Django
I am creating a Matplotlib figure to display in a HTML template in my Django application. I send this figure to the HTML by saving it under my static files, and then loading an img tag with the saved .png. I do this in my views.py after getting a reference to the figure. # Get analysis visualization chart figure = analyser.visualize_tweets(emotions) # Save figure in static folder as png figure.savefig('static/analysis_figures/figure.png') # Inject html with figure path response['analysis_figure_path'] = 'analysis_figures/figure.png' return render(request, 'landing_page/index.html', response) My HTML is something like this: <img src={% static analysis_figure %} alt=""> However, this caused the RuntimeError: main thread is not in main loop to happen when the function in my views.py is called a second time (if it's called once everything works properly). To prevent this error, I moved saving the Matplotlib figure to main() as to run in the main thread and then call it in my original function. This fixed the error, but prevents my HTML from reloading so every time the user submits a query the new figure is displayed over the previous one without the previous one being removed. Any ideas on any of the problems ? -
Django json nested list .get()
I am stuck with a silly problem. I have a json data and trying to save it in my model. Here is the code. response = response.json() #this gives json data response = json.loads(response) #loads string to json json_string = response #ready to get data from list gstin = json_string.get("abc") # this works fine bnm = json_string.get('["c"]["d"]["e"]') #this does not give data though data is present. My json data comes like this: { "abc":"AP003", "c":[ { "d":{ "e":"some data" } } ] } So my question is how to get data inside c. -
Unittest Django: Mock external API, what is proper way?
I am having a problem understanding how mock works and how to write unittests with mock objects. I wanted to mock an external api call every time when my model calls save() method. My code: models.py from . import utils class Book(Titleable, Isactiveable, Timestampable, IsVoidable, models.Model): title orig_author orig_title isbn def save(self, *args, **kwargs): if self.isbn: google_data = utils.get_original_title_and_name(self.isbn) if google_data: self.original_author = google_data['author'] self.original_title = google_data['title'] super().save(*args, **kwargs) utils.py def get_original_title_and_name(isbn, **kawargs): isbn_search_string = 'isbn:{}'.format(isbn) payload = { 'key': GOOGLE_API_KEY, 'q': isbn_search_string, 'printType': 'books', } r = requests.get(GOOGLE_API_URL, params=payload) response = r.json() if 'items' in response.keys(): title = response['items'][THE_FIRST_INDEX]['volumeInfo']['title'] author = response['items'][THE_FIRST_INDEX]['volumeInfo']['authors'][THE_FIRST_INDEX] return { 'title': title, 'author': author } else: return None I began read docs and write test: test.py: from unittest import mock from django.test import TestCase from rest_framework import status from .constants import THE_FIRST_INDEX, GOOGLE_API_URL, GOOGLE_API_KEY class BookModelTestCase(TestCase): @mock.patch('requests.get') def test_get_original_title_and_name_from_google_api(self, mock_get): # Define new Mock object mock_response = mock.Mock() # Define response data from Google API expected_dict = { 'kind': 'books#volumes', 'totalItems': 1, 'items': [ { 'kind': 'books#volume', 'id': 'IHxXBAAAQBAJ', 'etag': 'B3N9X8vAMWg', 'selfLink': 'https://www.googleapis.com/books/v1/volumes/IHxXBAAAQBAJ', 'volumeInfo': { 'title': "Alice's Adventures in Wonderland", 'authors': [ 'Lewis Carroll' ] } } ] } # Define response data for my … -
MySQL in Django (Not for usermanagement)
I have to fetch data from MySQL in django app. For that I written a singleton. I am not using user management and my front end is in Angular. Is this the correct approach to connect to a database from django?? or DATABASES in settings.py. In all the examples I have seen these variable is using to maintain the users. Whats the better approach for fetching data to pass to frontend through django??? MySQL_Singleton.py class Singleton: __instance = None @staticmethod def getInstance(): """ Static access method. """ if Singleton.__instance == None: Singleton() return Singleton.__instance def __init__(self): """ Virtually private constructor. """ if Singleton.__instance != None: raise Exception("This class is a singleton!") else: self.conn = pymysql.connect(host="localhost", user="root", passwd="da$mysql$123!", db="fpautomation") Singleton.__instance = self def insert(self, query): try: self.conn.ping(True) cursor = self.conn.cursor() cursor.execute(query) self.conn.commit() return {"result":True} except Exception as e: logger.error(str(e)) self.conn.rollback() raise Exception(e) return {"result":False} def execute(self, query): i = 0 while i<3: try: self.ping_server() logger.debug("Pinging") break except Exception as e: logger.error("Pinging failed.. Retrying... %s", str(e)) #self.conn.ping(True) cursor = self.conn.cursor() cursor.execute(query) col_names = [field[0] for field in cursor.description] df = [] for row in cursor.fetchall(): df.append(row) final_df = pd.DataFrame(data=df, columns=col_names) return final_df myapp/views.py import MySQL_Singleton def myview(request): body = json.loads(request.body) mysql = … -
Django Form Wizard
I want to implement 2-page form using django-formtools form wizard and I want to add quick finish button in the first page, so that the user won't see the second page. I know that we can conditionally view/skip specific steps but I haven't seen an implementation that invokes the submission. -
Django-cms CMS plugin with inlines once created inlines dont appear in Edit mode
I have a widget 'quick links' I want to add in my footer (In a static placeholder) I can add the widget and all the inlines. Once created, I can see the inlines in published mode, but the widget is empty in edit mode. Can you help me please? Models.py class LienFooterPlugin(CMSPlugin): langue = models.CharField(max_length=128) def copy_relations(self, oldinstance): self.lien_footer = oldinstance.lien_footer.all() class LienFooter(models.Model): class Meta: ordering = ["ordre"] lienfooter = models.ForeignKey(LienFooterPlugin, related_name="lien_footer") titre = models.CharField(max_length=150, blank=True, null=True) adresse = models.CharField(max_length=150, blank=True, null=True) ordre = models.PositiveIntegerField(default=1) admin.py class LienFooterInline(admin.StackedInline): model = LienFooter cms_plugins.py class LienFooterAppPlugin(CMSPluginBase): model = LienFooterPlugin name = u'Liens rapides' render_template = "widget/_liens_footer.html" inlines = (LienFooterInline,) def __init__(self, model=None, admin_site=None): super(LienFooterAppPlugin, self).__init__(model=model, admin_site=admin_site) for inline in self.inlines: inline.placeholder = self.placeholder inline.page = self.page def render(self, context, instance, placeholder): context = super(LienFooterAppPlugin, self).render(context, instance, placeholder) items = instance.lien_footer.all() context.update({ 'model':instance, 'placeholder': placeholder, 'items': items, }) return context plugin_pool.register_plugin(LienFooterAppPlugin) Thanks a lot for your help! -
Unable to access UserProfile model fields in templates in Django. Tried {{ user.userprofile }}
I've tried to import {{ user.userprofile. }} and {{ user.userprofile }} with no success. In the django shell I can access the user profile with UserProfile.objects.all(). {{ user. }} works fine, so I think it's an issue with my model, but I've checked the Django docs 'Models', 'database query', and 'model instance reference' and related S/O posts, but if it's my model that's the issue, I don't know what else to search for. Thanks models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class UserProfileManager(models.Manager): pass class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user') can_inst_nat = models.BooleanField(verbose_name='I can explain grammar and word usage to people in my NATIVE language.', default=False) can_inst_tar = models.BooleanField(verbose_name='I can explain grammar and word usage to people in my TARGET language.', default=False) wants_nat_lang_inst = models.BooleanField(verbose_name='I would like grammar and vocabulary explained to me in my NATIVE language.', default=False) wants_tar_lang_inst = models.BooleanField(verbose_name='I would like grammar and vocabulary explained to me in my TARGET language.', default=False) wants_cont = models.BooleanField(verbose_name='I would like to continue working with the same partner for several consecutive exchanges.', help_text='(If you want continuity, check this; If you like speaking to a variety of people, leave it blank.)', default=False) … -
Django Error NoReverseMatch because it's missing a pk.
So currently I'm on a page with a url link like this urls.py : path('key/<int:pk>', views.KeyDetailView.as_view(), name='roomkey-detail'), views.py : class KeyDetailView(generic.DetailView): model = RoomKey this lists out a list of keys available to be borrowed for a particular room. Then when I try to head to the next page, where is a request I can make to borrow out one of the keys for that room, there is a button that on that page that links to a terms and agreement page that looks like this roomkey_request_form.html : <a href="{% url 'key-agreement' roomkey.pk %}">terms and conditions</a> urls.py : path('key/<int:pk>/request/agreement', views.KeyAgreement, name='key-agreement'), views.py : def KeyAgreement(request): return render( request, 'catalog/roomkey_agreement.html', ) however when try to click on that request button to request a key, django throws an error NoReverseMatch at /catalog/key/2/request Reverse for 'key-agreement' with arguments '('',)' not found. 1 pattern(s) tried: ['catalog\\/key\\/(?P<pk>[0-9]+)\\/request\\/agreement$'] I am thinking this had to do with something the keyagreement not being able to take in that pk from the details page, can someone please explain to me what I am doing wrong or point me to some resource that can help me understand how urls pass along the pk from view to view? I am fairly … -
ValueError: invalid literal for int() with base 10 In a queryset object
I have Ciname models, it has latitude and longitude fields and I need to calculatethe distance. I found gpxpy lib and make: get_cinema = Cinema.objects.filter(active_cinema='t') queryset= get_cinema.annotate(distance=models.Max(gpxpy.geo.haversine_distance(int(user_latitude), int(user_longtude), int('latitude'), int('longtude')), output_field=models.FloatField())) The fields: user_longtude and user_latitude I define above. Error: ValueError: invalid literal for int() with base 10: 'latitude' -
Wagtail-In django how to get page objects from page id
I get wagtail page id from url https://www.example.com/results?id=14&id=15 In views.py def get_data(request, **kwargs): resources = request.GET.getlist('id') how to get relevant page objects with the help of page id ? In models.py context['selected_resources'] = ?? so that i can render i in template like this In results.html % for resource in selected_resources %} <p>{{resource.title}}</p> <p>{{resource.description}}</p> {% endfor %} -
How to extract active user email address from Django
I want to extract a list of active users email addresses from Django's Home › Authentication and Authorization › Users page and put it into a template. Can someone help me achieve this? So far I'm trying to do something like this: from django.contrib.auth.models import User if User.is_active: emails = User.objects.get(email=request.user.email) -
django 2 admin tools pagination
I am create custom module in dashboard admin_tools in my django 2 project, here is dashboard code: class CustomIndexDashboard(Dashboard): ... def init_with_context(self, context): site_name = get_admin_site_name(context) self.children.append(CatalogModule(title='Каталог', rr = Organization.objects.all, rh = ('Название', 'Юридическое лицо', 'Адрес фактический', 'Адрес юридический', 'Присутствие'), p = 1 )) ... class CatalogModule(modules.DashboardModule): def is_empty(self): return self.results == '' def __init__(self, **kwargs): super(CatalogModule, self).__init__(**kwargs) self.template = 'blocks/catalog.html' org_list = Organization.objects.all() page = kwargs.get('p', '') paginator = Paginator(org_list, 10) try: org = paginator.page(page) except PageNotAnInteger: org = paginator.page(1) except EmptyPage: org = paginator.page(paginator.num_pages) self.result_headers = kwargs.get('rh', '') self.results = org and catalog.html: {% extends "admin_tools/dashboard/module.html" %} {% block module_content %} {% load i18n static %} {% if module.result_hidden_fields %} <div class="hiddenfields">{# DIV for HTML validation #} {% for item in module.result_hidden_fields %}{{ item }}{% endfor %} </div> {% endif %} {% if module.results %} <div class="results"> <table id="result_list"> <thead> <tr> {% for header in module.result_headers %} <th scope="col" {{ header.class_attrib }} style="width: 30%; text-align=center"> {% if header.sortable %} {% if header.sort_priority > 0 %} <div class="sortoptions"> <a class="sortremove" href="{{ header.url_remove }}" title="{% trans "Remove from sorting" %}"></a> {% if num_sorted_fields > 1 %} <span class="sortpriority" title="{% blocktrans with priority_number=header.sort_priority %}Sorting priority: {{ priority_number }}{% endblocktrans %}">{{ header.sort_priority … -
PointField does not become Point but Geometry
I am using a PointField: class Location(AbstractBase): id = models.BigAutoField(primary_key=True) level = models.IntegerField() gps = models.PointField(blank=True, null=True, srid=4326) However, when it is generated in postgresql, it becomes a GEOMETRY field. Why not data type "Point"? That one exists in PostgreSQL -
How to set cookie with django-webtest
I am trying to test piece of code which depends on cookie. code in question is like this: try: json_string = urllib.unquote(request.COOKIES['add_global_user']).decode('utf-8') initial = json.loads(json_string) if 'company_name' in initial.keys(): company_type = get_company_type(initial['company_name']) download_notifications = initial.get('download_notifs', False) form = AddUserForm(request=request, initial=initial) form.fields['needs_lms_access'].initial = True response = render(request, "accounts/users/adduserglobal.html", locals()) response.delete_cookie("add_global_user", path="/accounts/user/add") return response except KeyError: _logger.debug("KeyError, no add_global_user cookie found, displaying form w/o data") form = AddUserForm(request=request, initial={'first_name':'keyerror'}) except ValueError: _logger.debug("ValueError, No valid JSON could be decoded, displaying form w/o data; %s", request.COOKIES['add_global_user']) form = AddUserForm(request=request, initial={'first_name':'valueerror'}) except Exception as e: _logger.debug("Exception occurred while retrieving form data from cookie, %s", str(e)) form = AddUserForm(request=request, initial={'first_name':str(e)}) I am using django-webtest to write test cases, my attempt to test is: class TestAddUser(WebTest): def test_bound_form_with_cookie(self): company = G(Company) user = G(User, email='superuser@tarams.com', is_superuser=True) cookie_dict = { "email": "email", "first_name": "3rd", "last_name": "2018", } self.app.set_cookie("add_global_user", json.dumps(cookie_dict)) response = self.app.get('/accounts/user/add/', user=user) assert response.context['form'].initial['email'] == 'email' running it django-webtest calls set_cookie method of DjangoTestApp whose source code is: def set_cookie(self, *args, **kwargs): self.extra_environ = self._update_environ(self.extra_environ) return super(DjangoTestApp, self).set_cookie(*args, **kwargs) and it throws error: AttributeError: 'super' object has no attribute 'set_cookie' I have given considerable time but could not find anything or workaround. Help appreciated. Thanks -
Django - Annotation dictionary does not display correctly in template
I got these models in my models.py class Rating(models.Model): stars = models.IntegerField() user_rating = models.ForeignKey(UserProfile, related_name="rater", on_delete=models.CASCADE) user_rated = models.ForeignKey(UserProfile, related_name="rated", on_delete=models.CASCADE) ride_number = models.ForeignKey(Ride, related_name="rider", on_delete=models.CASCADE) class UserProfile(models.Model): user = models.ForeignKey(User) And my views def user_view(request): avg = user_avg total = user_count context = { 'avg': avg, 'total': total } return render(request, 'rating/home.html', context) def user_avg(): avg = (Rating.objects .values('user_rated').annotate(Avg('stars')) .distinct()) return avg and lastly my template looks like this {% for rating in avg %} {{ avg }} {% endfor %} Right now it renders like this; [{'user_rated': 1L, 'stars__avg': 3.2222}, {'user_rated': 2L, 'stars__avg': 3.625}] [{'user_rated': 1L, 'stars__avg': 3.2222}, {'user_rated': 2L, 'stars__avg': 3.625}] I've tried changing the template to {{ avg.user_rated }} but then it renders me nothing, so I'm not sure what im doing wrong here. And how do I get the name of the users avg rating instead of user_rated