Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass a variable value in Django template URL name?
I need to pass the variable value in the Django template URL name. At first, I want to query the URL name from the database then the query URL name-value use in the Django template like as view.py: def user_home(request): user = request.user role = user.employinfo.designation element = role.sbtitleelement_set.all() context = { 'sb_title_element':element, } return render(request, 'home/index.html', context) Template: {% for element in sb_title_element %} <li class="nav-item"><a href="{% url 'element.url' %}" class="nav-link">{{element}}</a></li> {% endfor %} Here "{% url 'url-name' %}" i want to use URL name form {% url 'element.url' %}. How is it possible? Please help me to solve the problem.... -
How to write search query that gets input from separate fields in Django?
I need to create a search query that takes input from these fields. I would appreciate actual code example. I can query using one search field. But my project requires separated fields. Thank you. enter image description here -
Multiple Django services + centralised user authentication, management and provisioning
I have multiple running Django services, each with their own databases, and I'm trying to implement an authentication solution to achieve the following: Single Sign On. e.g. user can login to an authentication service at accounts.example.com, and when they browse to service-a.example.com or service-b.example.com, they will automatically be authenticated without any further login action. Centralised User Management. e.g. creating, updating an deleting accounts will all be done at accounts.example.com by an admin account Ability to provision service resources to new users even before the user's first login to the service. e.g. With an admin account, I created UserA at accounts.example.com, and then in service-a.example.com I would want to be able to assign tasks to UserA even if UserA has not first logged in to service-a.example.com yet. I have looked through and experimented with a number of SSO solutions such as OpenID, SAML, CAS, but it seems that with any of them I can't seem to achieve Point #3. This is because even if the new user account is created in the Identity Provider, the user object will not exist in the Django service until the user first login to the Django service (which only then the user object will be … -
What is the maximum length of TextField in django while using PostgreSQL
i wanna known what is the maximum length of TextField in django models while using PostgreSQL.. I just know Mysql uses the longtext data type to store the content, which can hold up to 4 Gigabytes but i wanna know what is the maximum length of TextField in django models while using PostgreSQL and if can increase it ? -
crispy form field type attribute ignored
I am trying to use crispy forms in my django app and I can not seem to get the type attribute to set on a field. #forms.py class ReminderForm(ModelForm): def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.helper=FormHelper() self.helper.layout = Layout( Fieldset('Reminder', Row( Div(Field('message'),css_class="col"), ), Row( Div(Field('messagetype'),css_class="col-md-6"), Div(Field('account'),css_class="col-md-6"), ), Row( Div(Field('reminddate',type="date"),css_class="col-md-6"), Div(Field('duedate', type="date"),css_class="col-md-6"), ), ) ) class Meta: model=Reminder exclude=['sentdate','confirmdate','completedate'] my modal form {% load cms_tags crispy_forms_tags %} <div class="modal fade" id="{{formid}}" tabindex="-1" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">{{title}}</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form > {% crispy form %} </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> rendered html for the inputs below show reminddate and duedate style with type="text" <div class="modal-body"> <form> <fieldset> <legend>Reminder</legend> <div class="form-row "> <div class="col"> <div id="div_id_message" class="form-group"> <label for="id_message" class=""> Message </label> <div class=""> <textarea name="message" cols="40" rows="10" class="textarea form-control" id="id_message"></textarea> </div> </div> </div> </div> <div class="form-row "> <div class="col-md-6"> <div id="div_id_messagetype" class="form-group"> <label for="id_messagetype" class=""> Messagetype </label> <div class=""> <select name="messagetype" class="select form-control" id="id_messagetype"> <option value="">---------</option> <option value="email">Email</option> <option value="sms">Text Message</option> <option value="internal">Internal Website</option> </select> </div> </div> </div> <div class="col-md-6"> <div id="div_id_account" class="form-group"> <label for="id_account" class=""> Account </label> … -
How to filter date According to Today Current Date in Django?
I am trying to filter date in Django according to current date, But it's displaying mr 0 results, Please let me know Where I am mistaking. Hers is my models.py file... class Customer(models.Model): name = models.CharField(null=True, blannk=True) customer_date = models.DateTimeField(null=True, blannk=True) here is my views.py file, where i am trying to get date according to today date... from datetime import datetime, timedelta, time, date def getdate(request): today=datetime.today() customer_data = Customer.objects.filter(customer_date=today).count() print(customer_data, "Count Values") -
How to send email in django with attaching dynamic context passed invite.ics file?
My is a simple celery asyncronus task which sends email attaching invite.ics file, but i dont know how to pass dynamic context in invite.ics file? my task file for sending email -> import os from django.conf import settings from celery import shared_task from time import sleep from django.core.mail import send_mail from django.core.mail import EmailMessage @shared_task def send_email_with_celery(company, date, sender, receiver): email = EmailMessage(f'Interview with {company}', f'You have been selected for the interview at time {date}', f"{sender} from {company}", [f'{receiver}']) email.attach_file('invite.ics', 'text/calendar') email.send() return None my invite.ics file--> BEGIN:VCALENDAR VERSION:2.0 PRODID:-//hacksw/handcal//NONSGML v1.0//EN BEGIN:VEVENT UID:{{ sender }} <-- dynamic sender context DTSTAMP:19970714T170000Z ORGANIZER;CN=Sonu Sud:MAILTO:{{ receiver }} <-- dynamic reciever context DTSTART:20201005T110000Z <-- should be dynamic time value in this format DTEND:20201005T114500Z <-- should be dynamic time value in this format SUMMARY:Interview with {{ company }} <-- should be dynamic Company name GEO:48.85299;2.36885 END:VEVENT END:VCALENDAR i want to pass the context like this -> context = { "sender":, "receiver":, "start":, "end":, "company": } how to pass the context in invite.ics file...? -
Django Class-based view pass custom request
I am using unittest in my project, and the following is my test code. import unittest from unittest.mock import patch, Mock from lists.views import NewListView @patch('lists.views.NewListForm') class NewListViewUnitTest(unittest.TestCase): def setUp(self): self.request = HttpRequest() self.request.POST['text'] = 'new list item' self.request.user = Mock() def test_passes_POST_data_to_NewListForm(self, mockNewListForm): NewListView(self.request) # The important bit mockNewListForm.assert_called_once_with(data=self.request.POST) I want to pass a custom request, which as you see has some POST data. I had originally had a view, so I could pass a custom request. Now, with a class based view, how can I do that? I am currently getting an error which says: TypeError: __init__() takes 1 positional argument but 2 were given I did try NewListView.as_view(self.request), but that says TypeError: as_view() takes 1 positional argument but 2 were given I know you should use the Django test client and make POST requests using the URL, not calling the actual view, but this is how they did it in the book I am currently studying (Test-Driven Development with Python by Harry Percival. Unfortunately, he doesn't seem to have updated his appendices, where he teaches the class based view stuff, so I am doing it my self. Or trying to.) Thanks. -
How to create one migration file for one model file in django
In a django app i created models folder, in which folder contains multiple model files, When i run command python manange.py makemigrations <app_name>, it generates one migration file for all the *.py models. So, is this possible to generate multiple migration files for multiple *.py models. -
How to send from JS to Python Django Server Backend
I have started learning about Javascript and I am trying to include it to my Django Project to calculate the time users are on the page so I found the answer to this question HERE but I am unable to implement it as it is the first time for me to link between JS and Django Python backend. Here is what I understand: Step 1 Add the following script for all HTML templates: <script src="timeme.js"></script> <script type="text/javascript"> TimeMe.setIdleDurationInSeconds(15); TimeMe.setCurrentPageName("my-home-page"); TimeMe.initialize(); window.onload = function(){ setInterval(function(){ var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds(); document.getElementById('timeInSeconds').textContent = timeSpentOnPage.toFixed(2); }, 25); } </script> Step 2 I am not sure exactly to place the below code to send the data to the backend to be read in Django Admin to know which user has been spending on each page xmlhttp=new XMLHttpRequest(); xmlhttp.open("POST","ENTER_URL_HERE",true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds(); xmlhttp.send(timeSpentOnPage); My questions are: Where should I place the 2nd Code? Should I start a new app in my django project to read the file sent from the JS? What is the TimeMe.setCurrentPageName("my-home-page"); what variable should I add? is it the HTML name of the name in the URL? -
Superuser dumpdata/loaddata in Django
I'm having a trouble on how can I dump a encrypted password data into authuser table in django, Currently I'm using python manage.py loaddata fixtures.json to dumpdata into database it works fine but the password is not encrypted, how can I encrypt it when using loaddata?. Is there any expert can share solutions or ideas with this problem, Much appreciate! [{"model":"auth.user", "pk" : 2, "fields" : {"password" : "superadmin", "is_superuser" : "1", "username" : "superadmin", "first_name" : "name" , "last_name" : "lname" , "email" : "a@gmail.com" , "is_staff" : "1", "is_active" : "1" }] -
Weird Concatenated Strings in browser URL
I am learning Django with materials in which the tutor used an old version of Django. I have been able to transform some of the codes into the currently supported version with the aid of some other recent material and by browsing through related questions here. The problem I have now is though everything works but the browser URL will display some weird strings concatenated together with the slug. Kindly help me point out what modifications I need to make on the following codes. Thanks in advance. This is the corresponding error part of the browser URL: (%3FP2020%5Cd%7B4%7D)/(%3FP11%5Cd%7B2%7D)/(%3FP03%5Cd%7B2%7D)/(%3FPsecond-post%5B-%5Cw%5D+) This is the method in the models.py: def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) These are the codes in the urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.post_list, name='post_list'), path('(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/', views.post_detail, name='post_detail'), ] These are the codes in views.py from django.shortcuts import render, get_object_or_404 from .models import Post def post_list(request, category=None): posts = Post.published.all() return render(request, 'list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'detail.html', {'post': post}) -
Guys I can't use my heroku domain name to generate a new Facebook access_token using postman like I used to do with my localhost
I did all steps mentioned here https://github.com/RealmTeam/django-rest-framework-social-oauth2 using POSTMAN to generate an access_token to login to Facebook using localhost:8000 and it generated perfectly and I got the the access_token and I can login perfectly but when I test the same way with a different url of my new domain name I can't get an access_token and I got an error said no module named 'social' so what should I do to do login with Facebook and generate access_token after pushed my project to heroku !!? There are all the steps I did after pushed my project to heroku : I Changed My Site Url Of My App On Facebook from localhost:8000 to https://whispering-hamlet-67095.herokuapp.com/ changed my ALLOWED_HOSTS In Settings.py To ALLOWED_HOSTS = ["localhost","whispering-hamlet- 67095.herokuapp.com"] This Step=> ### Testing On PostMan To Get facebook access_token As Usual Like I Used To Do When My Project is Only Running Locally But I Got This error When I Changed The Url From localhost:8000/ to https://whispering-hamlet-67095.herokuapp.com/ and my code of urls.py: from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views as auth_views from django.conf.urls.static import static from django.conf import settings from egystoreapp import views, apis urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', … -
Need currency format from a number in template
I am not a Django programmer but trying to look at how I can change the output of number which is supposed to printed to the page as USD. For example: It prints "Price: 3295000" when I would like it to say "Price: $3,295,000". This is the template part: <h5 class="card-title h5-size">Price: {{property.price}}</h5> What code can I put in the template to output this in the way that I'm looking for? -
How to check the file type of python InMemoryUploadedFile file?
I am creating an app using python Django to merge documents and I would want to check the file type of the uploaded files because the code can only merge pdf file. I have tried to use endswith and split function to check the file type but there was error saying InMemoryUploadedFile has no such attributes. Hence, are there any other methods to check for file type of InMemoryUploadedFile file ? My code is shown below: I want to make sure that check that if the uploaded files are not pdf files, the code will ignore it (adding if statement & continue) def mergedocument(request): doc = request.FILES.getlist("file[]") mergedoc =[] for docu in doc: fs = FileSystemStorage() file_path = fs.save(docu.name, docu) pdoc = documentsfile(docs=file_path) pdoc.save() mergedoc.append(docu) merger = PdfFileMerger() for pdf in mergedoc: merger.append(pdf) merger.write("C:\\Users\\Downloads\\Merged.pdf") merger.close() messages.info(request,a) messages.info(request,'Files merged and stored in your Downloads folder') return redirect('home') -
POST request to localhost using Python requests
I have my Django website running on my local server at port 8000. From a separate python file, I want to send a post request triggering one endpoint of my website. But unable to do that even after adding all the required info. Please help!! import requests URL = 'http://127.0.0.1:8000/api/org/create/' client = requests.Session() client.get(URL) csrftoken = client.cookies['csrftoken'] data = dict(csrfmiddlewaretoken=csrftoken) headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'} response = client.post(URL, data=data,cookies=client.cookies, headers=headers) print(response.status_code) It is giving me this error. EC:\Program Files\Python37\lib\unittest\case.py:643: ResourceWarning: unclosed <socket.socket fd=420, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 10510), raddr=('127.0.0 .1', 8000)> outcome.errors.clear() ====================================================================== ERROR: test_org_create (test_org.TestOrg) ---------------------------------------------------------------------- Traceback (most recent call last): File "\test_org.py", line 13, in test_org_create csrftoken = client.cookies['csrftoken'] File "\venv\lib\site-packages\requests\cookies.py", line 328, in __getitem__ return self._find_no_duplicates(name) File "\venv\lib\site-packages\requests\cookies.py", line 399, in _find_no_duplicates raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path)) KeyError: "name='csrftoken', domain=None, path=None" How to resolve this? Please comment for any other info. -
Django project "module markdown2 isnot found"
when i run python manage.py runserver in my project folder i get an error. like no module markdown2 I put import markdown2 top of my views.py file. Is anything else i need to do? anyone has any idea? thanks Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self.check(display_num_errors=True) File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/senayyakut/wiki/my_venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/senayyakut/wiki/encyclopedia/urls.py", line 3, in <module> from . import views File "/Users/senayyakut/wiki/encyclopedia/views.py", line 1, in <module> import markdown2 ModuleNotFoundError: No module named 'markdown2'``` -
Best way to structure site files before going live
I have built a website using Django and I'm about to go live. I had a question about the structuring of CSS files before I publish. Currently my site looks like this -Root -App 1 -App 1 Files -App 2 -App 2 Files -App 3 -App 3 Files -mysite -Templates -App 1 Templates -App 2 Templates -App 3 Templates -Static -Images -CSS Files -JS My main css was quite large so I split it up into separate css files for each section. I'm wondering if it would make sense to place the css files next to their corresponding templates, or if it would be best to leave them in the static folder as they are now. Thank you! -
django.db.utils.IntegrityError: NOT NULL constraint failed: new__profiles_userprofile.email
How can I fix it , I simple want to add email_address in UserProfile model and it showing me this django.db.utils.IntegrityError: NOT NULL constraint failed: new__profiles_userprofile.email error when i try to migrate. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_address = models.EmailField(max_length=254,default=None,blank=True,null=True) follower = models.ManyToManyField(User, related_name ='is_following',blank=True,) close_friends = models.ManyToManyField(User,related_name='my_close_friends', blank=True) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) background =models.ImageField(("Background"), upload_to='backgrounds', default = 'ak.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) -
DRF asking for CSRF Token with TokenAuthentication as the only auth method
My only auth system for DRF is TokenAuthentication and it is still asking for a CSRF Token on a function based view. I'm not having this problem with class based views. settings.py: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication' ] } views.py: @api_view(['POST']) @authentication_classes([TokenAuthentication]) def submit_vote(request): # ... On Postman's POST request: Forbidden (CSRF cookie not set.): /rest/submit_vote/ [04/Nov/2020 02:05:38] "POST /rest/submit_vote/ HTTP/1.1" 403 2864 What?! I don't have any pending migration. -
How to exclude fields from Forms created from Models in Django?
Hello Stack Overflow Community, I am attempting to follow DRY principles and generate a form with a model I defined for tables in the database. Unfortunately it seems that createlistings.html prompts users to fill out Listed by, when it shouldn't be. How do I remove that? Also how can I fix this really ugly formatting or atleast make it not look like spaghetti? Will I need to do it through css or are there some basic defaults through Django? Thanks. Here is my Model definition from models.py: class AuctionListing(models.Model): CATEGORY_CHOICES = [ ... ] listing_title = models.CharField(max_length=64) image = models.ImageField(blank=True) image_url = models.URLField(blank=True) description = models.TextField(max_length=400) category = models.CharField( max_length=6, choices=CATEGORY_CHOICES ) starting_bid = models.DecimalField(max_digits=10, decimal_places=2, default=0) date_posted = models.TimeField(auto_now=True) # When the referenced object (User) is deleted, also delete the # objects (Auction Listings) that have references to it. listed_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="listings") def __str__(self): return f"{self.listing_title} ({self.category})." Here is my form definition in views.py: class CreateListing(ModelForm): class Meta: model = AuctionListing exclude = ('listing_by', 'listings', ) # listed_by is filled out in view Also, for readability is it good practice to import my CATEGORY_CHOICES from a different file if it's a really long list? -
How do i create a static file in django
Please how can I correct this errorenter image description here I keep getting errors connecting BASE_DIRS to my static files -
How to create profile update view without profile create view?
Here I am trying to create profile update view , i haven't use profile create view in my views.py because that i am creating profile by signals so , i dont need profile create view but i need update view so that user can update his profile, i am getting an error ValueError at /profiles/profiles/admin/1/ The view profiles.views.ProfileUpdateView didn't return an HttpResponse object. It returned None instead. i dont know to fix it, here below is my code , If you think i am doing in very unprofessional way than please let me know and tell me the more professional way to do this. views.py class ProfileUpdateView(UpdateView): refirect_field_name ='profiles:final_detail.html' form_class = UserUpdateForm model = UserProfile def get_context_data(self, *args, **kwargs): context = super(ProfileUpdateView, self).get_context_data(*args, **kwargs) update_form = UserUpdateForm(instance = self.request.user) context['form']=update_form return context def form_valid(self,form): form.save() urls.py app_name = 'profiles' urlpatterns = [ path('final/<str:username>/',FinalProfileDetailView.as_view(),name = 'final_detail'), path('profiles/<str:username>/<int:pk>/',ProfileUpdateView.as_view(),name = 'update'), ] model.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follower = models.ManyToManyField(User, related_name ='is_following',blank=True,) close_friends = models.ManyToManyField(User,related_name='my_close_friends', blank=True) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) background =models.ImageField(("Background"), upload_to='backgrounds', default = 'ak.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) objects = ProfileManager() def __str__(self): return f'{self.user.username}' def save(self,*args, **kwargs): super(UserProfile,self).save(*args, … -
Django manytomany field shows all existing objects of that type in the admin
The title covers most of it. I have a model Game with a manytomany field called users this field has blank=True because it can be empty. Whenever I open this object in the admin it shows a list of all existing users instead of the users that are added to this particular game object. If i print the users in my consumer it shows that it is empty (which it is). How can I make the admin show the user objects that are in the users field. -
Calling properties using "Self" keyword and One-To-Many Relationships in Django
I'm new to Django, and having some trouble understanding how the self keyword works, compared to this in JS or C#. I've been working through the [Django REST API tutorial][1], and now am trying to add a second Model class. I'd like to have a one-to-many relationship between each Snippet and SubSnippets, but would like to have my SubSnippets inherit the language and style properties of the parent Snippet so that I can use them in the formatter for each SubSnippet. Here's the code I've added to models.py: snippet = models.ForeignKey(Snippet, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) owner = models.ForeignKey('auth.User', related_name='sub-snippets', on_delete=models.CASCADE) highlighted = models.TextField() class Meta: ordering = ['snippet', 'created'] def save(self, *args, **kwargs): lexer = get_lexer_by_name(self.snippet.language) linenos = 'table' if self.linenos else False options = {'title': self.title} if self.title else {'snippet title': self.snippet.title} formatter = HtmlFormatter(style=self.snippet.style, linenos=linenos, full=True, **options) self.highlighted = highlight(self.code, lexer, formatter)``` The problem is that `self.snippet.language` doesn't seem to be calling the actual Snippet class, because I'm getting an error that says "Instance of ForeignKey has no 'language' member." Same with `self.snippet.title` and `self.snippet.style`. I find the convention of putting all Models in a single file …