Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integration Django and Bokehn - does not display plot
I'm trying to integrate Django and Bokeh using enter link description here Unfortunately after writing the plot function it does not display anything. my views.py def homepage(request): x = [1,2,3,4,5] y = [1,2,3,4,5] plot = figure(title = 'Line Graph', x_axis_label='X-Ax',y_axis_label='Y-Ax',plot_width = 400,plot_height = 400) plot.line(x,y,line_width = 2) script,div = components(plot) return render(request,'repositorys.html',{'script': script,'div': div}) urls.py urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^repositorys/',views.homepage,name='repositorys'), url(r'^repositorys/(?P<pk>\d+)/$', views.repositorys_board, name='repositorys_board'), url('admin/', admin.site.urls), ] and repositorys.html <html> <head> <link href=”http://cdn.pydata.org/bokeh/release/bokeh-1.4.0.min.css" rel=”stylesheet” type=”text/css”> <link href=”http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.4.0.min.css" rel=”stylesheet” type=”text/css”> <script src=”http://cdn.pydata.org/bokeh/release/bokeh-1.4.0.min.js"></script> <script src=”http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.4.0.min.js"></script> {{ script | safe }} </head> <body> {{ div | safe }} </body> </html> My bokeh version is 1.4.0 Unfortunately on my localhost nothing is displayed -
How do I put links in spreadsheets to django that don't redirect to the login screen
Apologies, there is probably already responses to this but I can't even isolate where the problem is - Django or Excel I have an Excel spreadsheet that I've created with urls to Django resources e.g. rows that look like http://site/app/object/17234/ I built them as database extract with a string concatenation of id and the rest of the url. (e.g. select 'http://site/app/object/'||obj.id||'/' from ...) As far as I can see in excel they have the right structure and nothing weird. I've already authenticated on the site with 14 day token expiry If I copy and paste them into chrome they work If I create desktop shortcuts using the URLS they work BUT if I click on them within excel they open chrome but go to the login screen http://site/accounts/login/?next=/app/object/17234/ If I log in from there it correctly redirects but this is a step I don't think I should have to do. I am hoping someone can explain where this is happening, why and how to fix it. -
how to implement the idea of dependent model fields in django?
I am creating an app that has Post and Tag as models the post has tags, each tag describing the post somehow, for example a post has the following tags #backend_development #coding and I am relating the Post model to the Tag model by a ManyToManyField and each post creator chooses the tags from a pre-populated list from the database, meaning they don't create the tags on the post, they just choose them. the thing is I am trying to classify those tags somehow, for example , to have all the tech related tags are under a tech field in the list when clicked it displays all the tech related tags, if it's a business field for example it displays all the business related tags how can I implement this classification ? should I build another model called SubjectTag for example to include the subjects of all the tags and relate it with the Tag model? should I not do that and use some kind of html magic that can do this trick for me ? I don't know , what do you think ? -
python fragmented data pandas , DASK
what is the difference of using //DASK b = db.from_sequence(_query,npartitions=2) df = b.to_dataframe() df = df.compute() //PANDAS df = pd.DataFrame(_query) I want to choose the best option to fragment large amounts of data and without losing performance -
How to access request url pk from throttle class?
I am a newbie to Django and I am building a Django application that uses REST API. I have a throttle class and I want to restrict users to send more than 5 number of invitations to the same user in one minute. I send user ID with URL and I should access pk in order to use it for the caching operation. How can I access pk from the throttle class? For example: api/users/3299143165471965406/resend-invitation-email/ Pk will be: 3299143165471965406 views.py @decorators.action(methods=['post'], detail=True, serializer_class=None, permission_classes=[core_permissions.IsCompanyAdmin], url_path='resend-invitation-email', throttle_classes=[throttles.ResendInvitationThrottle]) def resend_invitation_email(self, request, pk=None): user = get_object_or_404(User, pk=pk) if user.invitation_status == User.INVITATION_STATUS_ACCEPTED or user.invitation_status is None: raise ValidationError("This user is already registered.") else: invitations_tasks.send_invitation_email.delay(pk) return response.Response(status=200) throttle: class ResendInvitationThrottle(SimpleRateThrottle): scope = 'invitation' def get_cache_key(self, request, view): invited_user_id = 1 # Here I should use PK return self.cache_format % { 'scope': self.scope, 'ident': invited_user_id } -
django why i can't see image file?
I tried to load img file, but it dosen't work. I upload img file by admin. thanks to help! here is my code in urls.py path('main/archive/<int:video_id>/', views.loadphoto, name='loadphoto'), in views.py def loadphoto(request, video_id): target_img=get_object_or_404(Record, pk=video_id) context={'target_img':target_img.picture} in models.py class Record(models.Model): record_text = models.CharField(max_length=50) pub_date = models.DateTimeField('date published') picture=models.ImageField(blank=True) def __str__(self): return self.record_text in img.html <img src="target_img"> <a href="{%url 'main'%}">Main</a> -
How to correctly "prompt" the user for a value based on logic in views.py in Django?
I'm trying to modify a page that essentially keeps tracks of when users enter/leave an area. Currently all the logic works fine, but I would like to add the functionality to ask a user to enter their own "estimate" of the time they entered/left in the case they forgot to do so, since these instances get flagged upon submission. I'm fairly new to Django/Python, and I have a very basic understanding of how this all works, so I apologize in advance if my suggestions on handling this are a bit off. These is a summarized version of what the models look like: models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area") station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True) edited_timestamp = models.DateTimeField(null=True, blank=True) time_exceptions = models.CharField(max_length=2, blank=True) time_in = models.DateTimeField(help_text="Time in", null=True, blank=True) time_out = models.DateTimeField(blank=True, help_text="Time out", null=True) def __str__(self): return self.employee_number I figured that the easiest way to do this is by adding it to the logic in views.py, to prevent updating a wrong record, in such a way that, right after an entry gets flagged, the user is prompted to enter the date/time they … -
Concurrency issue or something else? .save() method + DB timing
So the situtation is this: I have an endpoint A that creates data and calls .save() on that data (call this functionA) which also sends a post request to an external 3rd party API that will call my endpoint B (call this functionB) def functionA(): newData = Blog(title="new blog") newData.save() # findSavedBlog = Blog.objects.get(title="new blog") # print(findSavedBlog) r = requests.post('www.thirdpartyapi.com/confirm_blog_creation/', some_data) # this post request will trigger the third party to send a post request to endpoint calling functionB return HttpResponse("Result was: " + r.status) def functionB(): blogTitle = request.POST.get('blog_title') # assume this evaluates to 'new blog' # sleep(20) try: findBlog = Blog.objects.get(title=blogTitle) # again this will be the same as Blog.objects.get(title="new blog") except ObjectDoesNotExist as e: print("Blog not found!") If I uncomment the findSavedBlog portion of functionA, it will print the saved blog, but functionB will still fail. If I add in a sleep to function B to wait for the DB to finish writing and then trying to fetch the newly created data, it still fails anyway. Anyone with knowledge of Django's .save() method and/or some concurrency knowledge help me out here? Much appreciated. Thanks! -
Error creating merged queries with Q() and filter() in a viewset with djangoORM
I am trying to create a filter with multiple elements in a queryset for a view. I am overwriting the get_queryset method to fetch the results according to a user role. I am using Q() and works perfectly when i try to a single filter, for example: Cohort.objects.filter(Q(mode="p") ) or this: Cohort.objects.filter(Q(participant__user__id=self.request.user.id)) Both works perfectly filtering the queryset, but when i combine then as this... Cohort.objects.filter( Q(participant__user__id=self.request.user.id) | Q(mode="p") ) The queryset multiply the number of registries and bring to many results, repeated results, to the point that the request fails. This is the complete method: def get_queryset(self): user_role = self.request.user.rol if user_role == '0': base_qs=Cohort.objects.all() elif user_role == '1': base_qs=Cohort.objects.filter( Q(participant__user__id=user.id) ) elif user_role == '2': base_qs = Cohort.objects.filter( Q(participant__user__id=self.request.user.id) | Q(mode="p") ) scope = self.request.query_params.get('isNext', None) if scope is None: return base_qs elif scope: return base_qs.filter(fecha_final > datetime.date.today()) return base_qs.filter(fecha_final < datetime.date.today()) I don not recieve any error messages. checking the documentation this is the way to use Q but something is happening. What am i doing wrong? I am using Django==2.2.4 djangorestframework==3.10.2 -
sync Django urls with Nginx location matcher
As I'm adding new sever endpoints (Django) I need to manually update the server location matcher in the proxy server (Nginx) Is there an automatic way to sync nginx.conf with urls.py? -
ModuleNotFoundError: No module named 'django.contrib.auth.decoraters'
I am trying to create a login and logout page for my sample project and have coded all logic up. The tutorial I was following used the following code from django.shortcuts import render from basic_app.forms import UserForm from django.contrib.auth import authenticate,login,logout from django.http import HttpResponseRedirect,HttpResponse from django.urls import reverse from django.contrib.auth.decoraters import login_required # Create your views here. def index(request): return render(request,'basic_app/index.html') def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() registered = True else: print(user_form.errors) else: user_form = UserForm() return render(request,'basic_app/registration.html', {'user_form':user_form, 'registered':registered }) @login_required def special(request): return HttpResponse("You are logged in!") @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username,password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Account Not Active") else: print("Someone tried to login and failed") print("Username:{} and password: {}".format(username,password)) return HttpResponse("Invalid login details supplied") else: return render(request,'basic_app/login.html',{}) The error I am getting is this from django.contrib.auth.decoraters import login_required ModuleNotFoundError: No module named 'django.contrib.auth.decoraters' -
Django Image field doesn't update image
I recently got a problem that my django image field in my django app doesn't update the image after pressing "Post". In admin panel everything works fine. Maybe I missed something... Let me know. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) categories = models.ManyToManyField('Category', related_name='posts') image = models.ImageField(upload_to='images', default="images/None/no-img.jpg") def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Category(models.Model): name = models.CharField(max_length=20 ) views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .models import Post from django.contrib.auth.models import User from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView def home(request): content = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', content) def blog_category(request, category): posts = Post.objects.filter(categories__name__contains=category).order_by('-date_posted') content = { 'category': category, 'posts': posts } return render(request, 'blog/blog_category.html', content) #<--(didn't add content block) bug found 05.11.19 def upload_pic(request): if request.method == 'POST': form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): m = ExampleModel.objects.get(pk=course_id) m.model_pic = form.cleaned_data['image'] m.save() return HttpResponse('image upload success') return HttpResponseForbidden('allowed only via POST') ... class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content', 'categories', 'image'] def form_valid(self, form): form.instance.author = … -
How can I get into folders and out of them in cmd?
I have saw a question about activating V-Env in Django (Virtual Environment), I took action with the first answer. Here's the link: How to activate Virtual Environment in DJango The answer is for "Shariful Islam"... The first step was this: cd C:\Users\User\Desktop\UserDjangoProject> pip install virtualenv I wasn't able to operate this command in CMD (as he said at the answer's heading) Can anyone help me in that? -
Django model form field language is not changing
I am using django 2.2. and python 3.6. I have a template and crispy form inserted in template. This form is created from model. There is an imagefield field in model. photo = models.ImageField(upload_to="staff/", null=True, blank=True, verbose_name=_("Fotoğraf")) The crispyform is creating the field in the template but the language shown in the field is english. But i want to show turkish language. The Choose File and Browse should be turkish. So i changed settings.py as; LANGUAGE_CODE = 'tr-tur' But still it is written Choose File and Browse in the field in the page. You can see in the screenshot that everything is Turkish language except "Choose File" and "Browse". -
How to store mutiple time in django fields?
I have a situation like this where I have to store multiple values for a single row. For example, let us say I am creating a doctor's appointment model to store the doctor's name and available timing for that particular doctor. doctor_name | available_timing ABC | 7:00-11:00, 17:00-22:00 I am thinking about using JSON field like this from django.db import models from django.contrib.postgres.fields import JSONField class DoctorAppointment(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100) available_timing = models.JSONField() Is there any better approach to deal with a problem like this? -
how can i get redirect url using function based view?
I have 2 views: display_quote and quoteline_update After updating a quoteline, I want to redirect to "display_quote" (quote to which the quoteline updated belongs). I obtain the error:Reverse for 'display_quote' with no arguments not found. 1 pattern(s) tried: ['\^display_quote/\(\?P(?P[^/]+)\\d\+\)\$$'] Exception Type:NoReverseMatch Views: def display_quote(request, pk): items_quote = Quote.objects.filter(pk=pk) items_quote_line = LineQuote.objects.all().filter(num_quote_id=pk) form = QuoteLineForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() total = 0 for item in items_quote_line: total = total + item.get_price() context = {'items_quote': items_quote, 'items_quote_line': items_quote_line, 'form': form, 'total':total } return render(request, 'quote/quote_display.html', context) def quoteline_update(request, pk): model = QuoteLine cls = LigneDevisForm item = get_object_or_404(model, id=pk) if request.method == "POST": form = cls(request.POST, instance=item) if form.is_valid(): form.save() return redirect('display_quote') else: form = cls(instance=item) return render(request, 'quote/quoteline_update.html', {'form': form}) -
how to make the Serialization of a Dict of models
I have to serialize a Dict of Models with django rest framework /Serializers.py : class MapFilterSerializer(serializers.Serializer): bedroom_1 = ProjectsSerializer(many=True) bedroom_2 = ProjectsSerializer(many=True) bedroom_3 = ProjectsSerializer(many=True) bedroom_4 = ProjectsSerializer(many=True) /views.py : class MapFilter(generics.ListAPIView): .... return selected_Projects where selected_projects have this struture: { bedroom_1 : ProjectModelQuerySet, bedroom_2 : ProjectModelQuerySet, bedroom_3 : ProjectModelQuerySet, bedroom_4 : ProjectModelQuerySet, } where ProjectModelQuerySet is a queryset of the model Project How I should achieve this using the Project model serializer -
Need Proper DJANGO ORM Filter for DATE in Single Quotes
Here I am passing 2 dates aandb from my browser. I need to filter data by those dates. a = request.GET.get('date1') b = request.GET.get('date2') TestDB.objects.filter(start_date__range=(a,b)).order_by('-name').query SELECT "TestFilter_testdb"."id", "TestFilter_testdb"."name", "TestFilter_testdb"."start_date", "TestFilter_testdb"."end_date" FROM "TestFilter_testdb" WHERE "TestFilter_testdb"."start_date" BETWEEN 2019-11-04 AND 2019-11-05 ORDER BY "TestFilter_testdb"."name" DESC Here the SQL Query is like this "start_date" BETWEEN 2019-11-04 AND 2019-11-05 but Actually I need the passing date in single quotes like this "start_date" BETWEEN '2019-11-04' AND '2019-11-05'" -
Django Templates: Use context variables inside `{% include ... with ... }` statement
I want to implement variables from context inside an include statement. Code: views.py historic_trends_parameters = {'kpi':'kpi_name', 'dimension':'dimension_name'} context = {'historic_trends_parameters':historic_trends_parameters} return render(request, 'homepage.html', context=context) The template i want to put in the include statement: myTemplate.html <div class='MyClass'> <object class='tableauViz' width='{{ width }}' height='{{ height }}' style='display:none;'> <param name='show_tabs' value='{{ show_tabs }}' /> <param name='filter' value='{{ filter_values }}' /> </object> </div> homepage.html // some code <div> {% include "myTemplate.html" with width='700' height='400' show_tabs='yes' filter='KPIParameter=historic_trends_parameters.kpi' %} </div> // some more code Results: When I activate django and go to the homepage this is what i see in the Page Source: <div class='MyClass'> <object class='tableauViz' width='700' height='400' style='display:none;'> <param name='show_tabs' value='yes' /> <param name='filter' value='KPI Parameter=historic_trends_parameters.kpi' /> </object> </div> I didn't find a way to pass the historic_trends_parameters.kpi value from the context correctly. My desired outcome should be: <div class='MyClass'> <object class='tableauViz' width='700' height='400' style='display:none;'> <param name='show_tabs' value='yes' /> <param name='filter' value='KPI Parameter=kpi_name' /> </object> </div> Meaning historic_trends_parameters.kpi turns to 'kpi_name' -
Uploading file to website with android - site cant be reached
I am trying to upload a file in a website using the django framework. When i use my laptop i have no problem at all, but when trying to upload the exact same file with my android device i get 'This site cant be reached' views.py from django.shortcuts import render from django.http import HttpResponse from django.core.files.storage import default_storage from .Uploaded_files import C_Convert as conv from django.utils.datastructures import MultiValueDictKeyError def main_view(request): return render(request, 'main.html') def get_file(request): if request.method == 'POST': print(1) try: uploaded_file = request.FILES['file'] except MultiValueDictKeyError: return HttpResponse('<h1>Error</h1>') default_storage.save('CSD_Project/Uploaded_files/'+uploaded_file.name, uploaded_file) result = conv.convert(uploaded_file.name) return HttpResponse('<h1>%s</h1>'%result) else: return HttpResponse('<h1>Error</h1>') urls.py from django.contrib import admin from django.urls import path from .views import get_file,main_view urlpatterns = [ path('admin/', admin.site.urls), path('', main_view), path('get_file/', get_file) ] main.html <!DOCTYPE html> <html lang="en" style = "background-color: darkslategrey"> <head> <meta charset="UTF-8"> <title>HY100 Tests</title> </head> <body> <div style="text-align: center;"> <form action="get_file/" method="POST" enctype=multipart/form-data> {% csrf_token %} <input type="file" name="file"> <button style="color: white; background-color: #222222; padding: 15px 32px; font-size: 15px;" class="button">Submit file</button> </form> </div> </body> </html> -
Keyerror from celery task delay
Following the celery getting started with Django instructions, I am able to run tasks, but not run the same task asynchronously using delay(). I added the following requirements to my Django project: celery==4.3.0 redis==3.3.11 django-celery-results==1.1.2 psycopg2==2.7.3.1 django-cors-headers~=3.1.0 Created this celery.py in the pop_model project directory: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pop_model.settings.local') app = Celery('pop_model') # namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) Inserted this code in the project init.py: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) Configured cors in the project settings and added these settings: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'django-db' # defined in django_celery_results CELERY_ACCEPT_CONTENT = ['json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' I can start redis, then run celery using these commands: export DJANGO_SETTINGS_MODULE=pop_model.settings.local celery worker -A pop_model --loglevel=info In a python3 shell, I get these results: >>> … -
Image files are not accessable inside aws s3 bucket in browser
error: This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>AEAD5281D0CECD9C</RequestId> <HostId> JAeTP/f1wVEh86IYn9709nJ6+CaVE+7/AB5GDwwkQimiubeMZW6mz6pZsfZs4hODpKeqkjJeb4Y= </HostId> </Error> Bucket Policy: <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>AEAD5281D0CECD9C</RequestId> <HostId> JAeTP/f1wVEh86IYn9709nJ6+CaVE+7/AB5GDwwkQimiubeMZW6mz6pZsfZs4hODpKeqkjJeb4Y= </HostId> </Error> CORS configuration: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Authorization</AllowedHeader> </CORSRule> </CORSConfiguration> Here i am trying to upload image file to aws s3 bucket. As i can see i am getting my image urls in database. <QuerySet [{'bio': 'ddd', 'logo': 'https://maxfitness-storage.s3.amazonaws.com/media/newFile_hV4hFpU.jpeg', 'coach_id': 1, 'id': 22, 'banner': 'https://maxfitness-storage.s3.amazonaws.com/media/newFile_EPSIeyM.jpeg'}]> But when i am checking my s3 bucket it is showing bucket is empty. And when i am going to https://maxfitness-storage.s3.amazonaws.com/media/newFile_hV4hFpU.jpeg (getting from database) url it is showing above error shared on the top. Please have a look. -
Django proper way to save global API client instance variable
How to store some API client instance and make it available across the whole project. API client instance - is some AppApi() and I need to call it's methods in different views (and even apps) from whole django project. As for me, there are two ways: create a global variable in some core django app core/apps.py module; create singleton wrapper; What is the best and proper way to do in this case? -
Django Hostname in Testing
I am wondering if there is a way to obtain the hostname of a Django application when running tests. That is, I would like the tests to pass both locally and when run at the staging server. Hence a need to know http://localhost:<port> vs. http://staging.example.com is needed because some tests query particular URLs. I found answers on how to do it inside templates, but that does not help since there is no response object to check the hostname. How can one find out the hostname outside the views/templates? Is it stored in Django settings somewhere? -
Django related model field querying (mutual friends)
I have a friendship model: class Friendship(models.Model): user = models.ForeignKey( Account, on_delete=models.CASCADE, related_name="friend1", null=True, blank=True) other_user = models.ForeignKey( Account, on_delete=models.CASCADE, related_name="friend2", null=True, blank=True) date_created = models.DateTimeField(auto_now=True) objects = FriendshipManager() class Meta: verbose_name = "friendship" verbose_name_plural = "friendships" unique_together = ("user", "other_user") def __str__(self): return f'{self.user} is friends with {self.other_user}.' and this function to return all users who are mutual friends of two accounts def mutual_friends(self, account1, account2): mutual_friends = Account.objects.filter( Q(friend2__user=account1) & Q(friend2__user=account2)) return mutual_friends Based on my (limited) understanding of how the query api works, I would think this should return all users who have a "friend2" relationship with the Friendship table where the "friend1" user is either account1 or account2. I'm still getting used to querying with django, so if someone can let me know what I'm doing wrong that'd be great. Thanks!