Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a server which hosts both PHP and Django sites on different domains
I am on ubuntu 16.04 server and seeking to deploy 3 domains on the ip. 1 is WordPress site rest 2 are Django site. But I can find a proper way of doing it. Should I create different docker containers? Or use Nginx blocks? Or should I deploy a LAMP server with virtual host and use nginx as reverse proxy? I have no issues with serving sites from different ports. -
Basic to use FFMPEG in Python (Django Rest Framework)
I'm writing a viewset in Django Rest Framework to convert images sequence into video by using FFMPEG but I don't understand how I can do it. I tried but not success. Please help me with my code. My code: class VideoRenderSerializer(ModelSerializer): imageSequence = ListField(required=False, child=FileField(max_length=100000, allow_empty_file=False, use_url=False)) class Meta: model = Video fields = [ 'imageSequence', ] class VideoRenderView(ModelViewSet): queryset = Video.objects.all() serializer_class = VideoRenderSerializer def render_video(self, request): imgSequences = request.FILES.getlist('imageSequence') render_from_img_sequences_cmd = 'ffmpeg -loop 1 -i image.png -vf format=yuv420p -t 30 C:\output.mp4' ffmpegresult = subprocess.call(render_from_img_sequences_cmd, shell=True, stdout=open(os.devnull, "w"), stderr=subprocess.STDOUT) return Response(ffmpegresult, status=200) Output is: 1 and I cant find where is output file! -
Django/DRY: Avoid repetition in template
Anyone know how to avoid this repetition my template? I tried it with a for loop, but it didn't work out. <p> Current:<br> {% for event in states.current %} <a href="{% url 'ambassadors:event' organizer=event.organizer.slug event=event.slug %}">{{ event.name }}</a> {% endfor %} </p> <p> Past:<br> {% for event in states.past %} <a href="{% url 'ambassadors:event' organizer=event.organizer.slug event=event.slug %}">{{ event.name }}</a> {% endfor %} </p> -
Django template's "extends" tag does not work
I also checked the similar questions here but my problem is not one of them. Actually I am not getting a specific error but getting anything literally. I have a main template called dashboard.html and it is in the project level template folder. I have a block in it like this; *** some code here *** <li class="nav-item"> <a class="nav-link" href="{% url 'products:test' %}"> <span data-feather="shopping-cart"></span> Products </a> </li> *** some code here {% block test_html %} {% endblock test_html %} I have an application called "products" and in its template folder, I have test.html file. Here its content; {% extends 'products/base.html' %} {% load static %} {% block test_html %} <h1>test</h1> <h1>test</h1> <h1>test</h1> {% endblock test_html %} My products/base.html file; {% extends 'dashboard.html' %} My products/urls.py file; app_name = 'products' urlpatterns = [ path('', views.IndexView.as_view(), name='base'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('', TemplateView.as_view(template_name='products/test.html'), name='test'), ] When I load the page, nothing happens. Here is also the screen shot link; http://i.prntscr.com/wtGNfcj4RZOClPndNfnX3w.png I am expecting h1 tags from my test.html file on that blank area shown on the screen shot. PS: Actually I am expecting to show IndexView from my urls.py but for testing purposes I created a test.html to check whether it … -
Defining two api end points with same generic class view Django Rest Framework?
I am new to Django. I was trying to use django generic views, class based. How do I implement following situation, I have two api end points login/ and logout/ and the same view class handles it ? # Login and logout class SignInActivity(generics.RetrieveUpdateAPIView): serializer_class = UserSerializer request = None def get_queryset(self): return User.objects.filter(Q(username=self.request.data["username"]) & Q(userpassword=self.request.data["userpassword"])) def update(self, request, *args, **kwargs): self.request = request query_set = self.get_queryset() if bool(query_set): query_set.update_or_create(username=self.request.data["username"], userpassword=self.request.data["userpassword"], defaults={ "lastlogin": timezone.now() }) return Response(data={"message": "User logged in successfully.", "response_code": 222}, status=201) else: return Response(data={"message": "User not found.", "response_code": 444}, status=201) And my urls.py is path('login/', SignInActivity.as_view()) This implementation hadles login/ with this class, PUT method. Now can I use same class with another method to handle logout/ PUT method? -
ModelBase object is not iterable error
I'm attempting to create a form which creates appointments for people. It will populate a selection box by taking data from a database. The models.py: class customer(models.Model): # Need autoincrement, unique and primary cstid = models.AutoField(primary_key=True, unique=True, default=1) name = models.CharField(max_length=35) age=models.IntegerField() mobile = models.CharField(max_length=15) place = models.CharField(max_length=80) def __str__(self): return self.name class doctor(models.Model): docid = models.AutoField(primary_key=True, unique=True) # Need autoincrement, unique and primary name = models.CharField(max_length=35) regid = models.CharField(max_length=15, default="", blank=True) photo = models.CharField( max_length=35, default="", blank=True) email = models.EmailField(default="", blank=True) phone = models.CharField(max_length=15) qualifications = models.CharField( max_length=50, default="", blank=True) about = models.CharField( max_length=35, default="", blank=True) specialities = models.CharField( max_length=50, default="", blank=True) department = models.CharField(max_length=50, default="ENT", blank=True) fees = models.FloatField(default=300.0) displayfee = models.IntegerField(default=0, blank=True) slotrange = models.CharField(max_length=50, blank=True) slotdurn = models.IntegerField(default=10) breakrange = models.CharField( max_length=50, default="", blank=True) slotsleft = models.CharField( max_length=50, default="", blank=True) def __str__(self): return self.name class appointment(models.Model): # Need autoincrement, unique and primary appid = models.AutoField(primary_key=True, unique=True, default=1) date = models.DateField(default=timezone.now) time = models.TimeField(default=timezone.now) docid = models.ForeignKey(doctor, on_delete=models.CASCADE, null=True) cstid = models.ForeignKey(customer, on_delete=models.CASCADE, null=True) The form - forms.py: class AddAppointmentForm(forms.Form): docchoices = [] for doc in doctor: docst = [doc.docid, doc.name] docchoices.append(docst) name = forms.CharField(label='Name', max_length=100) gender = forms.ChoiceField( required=True, widget=forms.RadioSelect, choices=docchoices, ) age = forms.IntegerField(max_value=100,min_value=1, required=True) … -
Docker/Kubernetes + Gunicorn/Celery - Multiple Workers vs Replicas?
I was wondering what the correct approach to deploying a containerized Django app using gunicorn & celery was. Specifically, each of these processes has a built-in way of scaling vertically, using workers for gunicorn and concurrency for celery. And then there is the Kubernetes approach to scaling using replicas There is also this notion of setting workers equal to some function of the CPUs. Gunicorn recommends 2-4 workers per core However, I am confused what this translates to on K8s where CPU is a divisible shared resource - unless I use resoureceQuotas. I want to understand what the Best Practice is. There are three options I can think of: Have single workers for gunicorn and a concurrency of 1 for celery, and scale them using the replicas? (horizontal scaling) Have gunicorn & celery run in a single replica deployment with internal scaling (vertical scaling). This would mean setting fairly high values of workers & concurrency respectively. A mixed approach between 1 and 2, where we run gunicorn and celery with a small value for workers & concurrency, (say 2), and then use K8s Deployment replicas to scale horizontally. There are some questions on SO around this, but none offer an … -
Delete image from media when object is deleted
When I delete an object from my database, the image previously uploaded stays in the media directory. I would like to delete it automatically. Here is my model: class Door(models.Model) : image = models.ImageField(upload_to=upload_location) color = models.ForeignKey(Color, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2, default='119.99') Here is my delete view: def door_delete(request, door_id) : door = get_object_or_404(Door, id=door_id) door.delete() return redirect("/dashboard/doors") I have tried to instert before door.delete() line door.image.delete() but that hasn't worked out as far I as know. Please help me if you know the answer. -
How to put an api into celery task in django?
I am using Django, celery, and DjangoRestFramework for APIs. I have an API that takes around 1 minute to show data in JSON format. The problem is Heroku ( server) shows application error if a function takes more than 30 seconds. Hence I want to put my API into celery tasks. Please suggest the way to do so. Thanks. -
looping declaration code improvement for django
I have 2 lists where rakam = 1 to 9 sakla_l = sakla,sakla,sakla etc 9 times. I want to join these 2 lists to become sakla0,sakla1,sakla2 etc till sakla9 then I want to declare all as one like sakla0 =1 sakla1= 1 sakla2= 1 etc.. I am accessing these declarations from below parts of my code now I declared manually but I didn't like to code and I am trying to improve with for loop but no success searched a lot within stackoverflow but I can't find nothing similar to that.Please don't say it's duplicate question because it's not. My aim not to print these items.My aim is to have that declaration of these items equal to 1. import string rakam= list(range(10)) sakla_l =["sakla"] * 10 for i in range(10): j_list=sakla_l[i].join(str(i)) j_list[i] = 1 print(j_list) My working undesired code is below: sakla0=1 sakla1=1 sakla2=1 etc... sakla8=1 sakla9=1 You might ask why you need to declare, the reason I am hiding some tables or unhiding some tables within the django html template based on these values. -
Automation with Celery Tasks in Django 1.11
I have implemented the following class based view below that creates a payslip and it's working perfectly. I was thinking further to automate this functionality by running it periodically i.e every month. How do I trigger the POST method with celery tasks.py to run periodically? I'm using celery==4.1.0,RabbitMQas my message broker,Python3andDjango 1.11anddjangorestframework==3.8.2`. class PayslipPostAPIView(APIView): """ .. http:get:: /payslip_create/ **Request**: .. sourcecode:: http GET /payslip_create/web HTTP/1.1 Host: {{theDomain}} Accept: application/json, text/javascript **Response**: .. sourcecode:: http HTTP/1.1 200 OK Vary: Accept Content-Type: text/javascript [ { "id": 123, "employee": 123, "basic_salary": ["server", "web"], "payment_mode": "I tried Nginx", "currency": "Currency", "payslip_no": "Payslip Number", "month_ending": "Date", "is_accounted": "True/False", "created_at": "Date" "modified_at": "Date", "total_allowances": 123, "total_deductions": 123, "net_pay": 123, "organization": 123 } ] :reqheader Authorization: JWT token required to authenticate .. http:post:: /payslip_create/ :param post_id: post's unique id :type post_id: int :reqheader Authorization: JWT token required to authenticate :status 201: Payslip successfully Created :status 400: Post parameters are invalid or missing """ permission_classes = (permissions.DjangoObjectPermissions,) queryset = Payslip.objects.all() model_list = [EmployeeProfile, Salary, Allowance, Deduction, PaymentMode] def get(self, request, format=None): payslip = Payslip.objects.filter(organization=get_auth(request)).all() serializer = PayslipSerializer(payslip, many=True) return Response(serializer.data) def post(self, request, format=None): try: allowance_list = request.data.pop('allowance_list') deduction_list = request.data.pop('deduction_list') # employee = EmployeeProfile.objects.get( # id=request.data.pop('employee'), organization=get_auth(request)) … -
How can i call variable into another function in django?
def upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): file_p = form.save().document df = pd.read_csv(file_p, header=None) #parsing CSV file df.drop([0], axis=1, inplace=True) return render(request, 'Data/csv.html', {'df': df}) else: form = DocumentForm() return render(request, 'Data/upload.html', { 'form': form }) This is a function. I need to call df in another function: def mean(request): df['Average_Income'] = df.mean(axis=1).astype(int) return render(request, 'Data/mean.html', {'df': df}) -
Django How do i get the id of User automatically?
i am newbie in django how do i get the id of customer model while submitting the form .for eg john is submitting the form of booking i want automatically get who submit the booking .means while customer register the form and the link will sended to the customer for booking. and in booking i want to initialize the customer automatically for the booking. means john booked the car and given detail for when he want the car for booking . Models class Booking(models.Model): class Meta(): db_table = "booking" verbose_name = "Booking" verbose_name_plural = "Bookings" ordering = ['-booking_date'] booking_car_car = models.ForeignKey( Car, on_delete=models.CASCADE, related_name='booking_car_car_key' ) booking_customer_customer = models.ForeignKey( Customer, on_delete=models.CASCADE, related_name='booking_customer_customer' ) booking_start_date = models.DateField( blank=False, null=False ) booking_end_date = models.DateField( blank=False, null=False ) booking_total_price = models.IntegerField( blank=False, null=False ) booking_approved = models.NullBooleanField( blank=True, null=True ) booking_date = models.DateTimeField( auto_now_add=True, blank=False, null=False ) def __str__(self): return self.booking_customer_customer.customer_firstname class Customer(models.Model): first_name = models.CharField(max_length=64,null= False) last_name = models.CharField(max_length=64) customer_age = models.IntegerField(blank=True, null=True) last_name = models.CharField(blank=True, max_length=100) license_year = models.IntegerField(blank=False, null=False) tlc_number = models.IntegerField(blank=False ,null=False) contact_num =models.IntegerField(blank=False, null=False) contact_email = models.EmailField(blank =False) def __str__(self): return self.first_name can anyone help me with the code because i am not getting the customer for the booking … -
Django local variable 'Tos' referenced before assignment
The function saves the user details also it gets the Tos object corresponding to the user def tos(request): data = Tos.objects.only('tos').get(user=request.user) if request.method == 'POST': form = TosForm(request.POST) if form.is_valid(): Tos = form.save(commit=False) Tos.user = request.user Tos.tos = True Tos.save() return redirect('home') else: form = TosForm() return render(request, 'qritive_app/tos.html', {'accept': accept}) -
TypeError: create_superuser() got an unexpected keyword argument 'email'
I need to create custom user model because I need to have one additional field called role. If the role is provided, it should be assigned to the user model otherwise provide agent as role in user model. I inherited the AbstractUser. This way when creating the user, first the password is saved as plain text and another is user cannot login it says unable to login. So i tried the below way as in docs but the problem is i don't need the email part so i excluded it and used just username and password but getting error like TypeError: create_superuser() got an unexpected keyword argument 'email' class UserManager(BaseUserManager): def create_user(self, username, password=None): """ Creates and saves a User with the given username, date of birth and password. """ if not username: raise ValueError('Users must have an username') user = self.model(username=username) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password): """ Creates and saves a superuser with the given username and password. """ user = self.create_user( username=username, password=password, ) user.is_admin = True user.save(using=self._db) return user class Role(models.Model): ROLE_CHOICES = ( ('agent', 'Agent'), ('agency', 'Agency'), ('manufacturer', 'Manufacturer'), ) role = models.CharField(max_length=15, choices=ROLE_CHOICES) def __str__(self): return self.role class User(AbstractUser): role = models.ForeignKey( … -
display contents of manytomany and foreignjey fields in Django
I'm new to Django and I'ma building a basic blog application. I cant show manytomany field (in tags) and a foreignkey field (comments) in my details page. models.py class BlogContent(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) content = models.TextField() date_published = models.DateField(auto_now=True) image = models.ImageField(upload_to='media/') def __str__(self): return self.title class TagName(models.Model): tag = models.ManyToManyField(BlogContent, null=True) name = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.name class Comment(models.Model): comt_text = models.TextField() comments = models.ForeignKey(BlogContent, on_delete=models.CASCADE) date_published = models.DateField(auto_now=True) name = models.CharField(max_length=200, blank=True, null=True) def __str__(self): return self.name views.py def details(request, blogcontent_id): data_blog = get_object_or_404(BlogContent, pk=blogcontent_id) data_tag = get_object_or_404(TagName, pk=blogcontent_id) data_comment = Comment.objects.select_related() return render(request, 'details.html', {'data_blog': data_blog, 'data_tag':data_tag, 'data_comment':data_comment}) details.html {% extends 'base.html' %} {% block body_base %} <img class="card-img-top img-responsive" src={{ data_blog.image.url }} alt="Card image cap"> <h2 class="blog-post-title">{{ data_blog.title }}</h2> <p class="blog-post-meta">{{ data_blog.date_published }} {{ data_blog.author }}</p> <p>{{ data_blog.content }}</p> {% endblock %} how do i show foreignkey and manaytomany fieds after this? -
search functionility doesn't work
I am trying to have search function in my page. I am new to python and i don't have good knowledge about python. I am trying the functions using the document https://docs.djangoproject.com/en/1.11/intro/tutorial01/ , but i am not able to do find the solution for search functionality. Only the urls changes not the search function. Could anyone help me with it. Thanks in advance form.py from .models import EmployeeModel from django import forms class EmployeeForm(forms.ModelForm): class Meta: model = EmployeeModel fields = ['name', 'address', 'dob', 'phone', 'emp_id'] models.py from django.db import models class EmployeeModel(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=200) dob = models.DateField() phone = models.IntegerField() emp_id = models.IntegerField() urls.py from django.conf.urls import url from django.views.generic import FormView from . import views from .views import EmployeeView from .views import EmployeeDetailView app_name = 'employee' urlpatterns = [ url(r'^$', EmployeeView.as_view(), name='employee'), url(r'^your-name/$', views.EmployeeView.as_view(), name='employee'), url(r'^your-name/thanks/$', views.EmployeeView.as_view(), name='employee'), url(r'^search/$', views.EmployeeDetailView.as_view(), name='employee'), ] views.py from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.views import generic from django.template.response import TemplateResponse from django.views.generic import CreateView from django.views.generic import DetailView from django.urls import reverse_lazy from .models import EmployeeModel from .forms import EmployeeForm class EmployeeView(CreateView): model_class = EmployeeModel form_class = EmployeeForm success_url = reverse_lazy('thanks') initial = {'your_name': … -
Django - Celery catch(try-except block) errors - issues with freezing/hang code
I'm using PythonDjango with Celery and Redis and I want to catch two erros: The first error OperationalError means the server is down If app.control.inspect().active() is None, the workers are down Functionality: If there is not an OperationalError it should check also app.control.inspect().active() If there is an OperationalError it shouldn't check app.control.inspect().active() because Celery will hang/freeze The Celery task will not work in both cases but just the Redis server down will have an exception Code: try: send_email_task.delay(subject=subject, ..., html_content=html_content) except OperationalError as e: # do something if not app.control.inspect().active(): # do something My issue, if I have an OperationalError the condition if not app.control.inspect().active() will hang the code -
django for loop emailing first dyncamic form only
I am making a dynamic form that uses the submitted data and sends an email. No matter how many forms there are it sends an email with the first forms data in the place of every form. The form-TOTAL_FORMS is updating I checked. views.py def order(request): extra_forms = 1 order_formset = formset_factory(order_form, extra=extra_forms) if request.method == 'POST': if 'additems' in request.POST and request.POST['additems'] == 'true': formset_dictionary_copy = request.POST.copy() formset_dictionary_copy['form-TOTAL_FORMS'] = int(formset_dictionary_copy['form-TOTAL_FORMS']) + extra_forms formset = order_formset(formset_dictionary_copy) else: formset = order_formset(request.POST) for form in formset: if formset.is_valid(): #Clean Form Data cleaned_quanity = form.cleaned_data['quanity'] cleaned_pack = form.cleaned_data['pack'] cleaned_grade = form.cleaned_data['grade'] cleaned_size = form.cleaned_data['size'] cleaned_variety = form.cleaned_data['variety'] cleaned_loading_date = form.cleaned_data['loading_date'] cleaned_notes = form.cleaned_data['notes'] #Convert Cleaned Data to Int int_pack = int(cleaned_pack) int_grade = int(cleaned_grade) int_variety = int(cleaned_variety) #Logic for choice options if int_pack == 1: int_pack = 'Carton' elif int_pack == 2: int_pack = '12/3# Bags' elif int_pack == 3: int_pack = '10/4# Bags' else: int_pack = '6/8# Bags' if int_grade == 1: int_grade = 'Standard' elif int_grade == 2: int_grade = 'Choice' else: int_grade = 'Fancy' if int_variety == 1: int_variety = 'Blood' elif int_variety == 2: int_variety = 'Cara' elif int_variety == 3: int_variety = 'Grapefruit' elif int_variety == 4: int_variety … -
Jinja accessing dictionary within url tag (Django)
I have the following Jinja code for my Django application: <ul> {% for key, value in course_avrg.items %} <li> <a href="{% url 'course-detail' pk=course_ids[key] %}">{{ key }}:</a> {{ value }} </li> {% endfor %} </ul> The course_ids is a dictionary with key course name (str) and value course id (int). The course_avrg is another dictionary with key course name (str) and value course average (int) In the above code, I'm trying to get the primary key value (int) of each course by passing the course name "key" into course_ids dictionary. However, I get the following error: Could not parse the remainder: '[key]' from 'course_ids[key]' so how should I access dictionary value from within the Jinja URL tag? -
Is it okay to disable CSRF for slack slash command api mad in Django?
Is it disabling CSRF functionality the best practice for Slack slash command server? I want to call an API view function in Django by a Slack slash command, for example, /test. When I call the URL for the view function with any browser (so it is a GET request), it works as expected. However, when I run /test in Slack, I got 403_client_error in slack, and Forbidden (CSRF cookie not set) in the Django shell. I believe this is because Slack sends a POST request, and Django requires CSRF token for any POST requests. My question is whether I should disable CSRF checking for this view. Will there be a significant risk? Or is there any workaround? -
django concurrency request two url, each request header is wrong to each url
concurrency to request django app with two url, each url request header I give one id, like urla id=1, urlb id=2, but when i get from django view from request header, I get urla's id from request header is 2 ...so confused...post body is ok client code #coding=utf-8 import threadpool import requests HOST = 'http://127.0.0.1:8000' urls = ['/health', '/x2'] headers = {'Content-Type': 'application/json', 'HOST': 'xx.com'} pool = threadpool.ThreadPool(5) def request_api(n): url = urls[n%2] print('---------------------start request url {}'.format(url)) headers.update(url=url) body = dict( url=url ) r = requests.post(url=HOST + url, headers=headers, json=body) print(r.status_code) reqs = threadpool.makeRequests(request_api, range(5)) [pool.putRequest(req) for req in reqs] pool.wait() print('over') server code # coding=utf-8 from rest_framework.views import APIView from django.http.response import HttpResponse class ApiHealthCheck(APIView): def post(self, request, request_id='', **kwargs): print('api_health_check: {},{},{}'.format(request.path, request.META.get('HTTP_URL'), request.data)) return HttpResponse("ok") class ApiHealthCheck2(APIView): def post(self, request, request_id='', **kwargs): print('api_health_check2: {},{},{}'.format(request.path, request.META.get('HTTP_URL'), request.data)) return HttpResponse("ok") server print api_health_check: /health,/health,{u'url': u'/health'} api_health_check2: /x2,/health,{u'url': u'/x2'} api_health_check: /health,/health,{u'url': u'/health'} api_health_check2: /x2,/x2,{u'url': u'/x2'} api_health_check: /health,/health,{u'url': u'/health'} attention one of them have wrong,path not match META's content,body is ok -
Django compatibility with BeautifulSoup's lxml parser
I create a website using Django 1.11.12 with Python 3.4. Yesterday, I stumbled over something strange. My function looks something like this: from bs4 import BeautifulSoup as Soup def foo(): t = "bla bla blubb" s = Soup(t, 'lxml') # do stuff When Django calls the function the first time, everything works and I get a result. However, when running the same function a second time, the website freezes and I get a Gateway Timeout after some time. When now only changing the parser: from bs4 import BeautifulSoup as Soup def foo(): t = "bla bla blubb" s = Soup(t, 'html.parser') # changed from lxml to html.parser # do stuff Everything works fine over and over again. Is this just with my system (perhaps I messed up something)? What may be the reason for this behaviour? I am glad for any suggestions. -
The meaning of vars() in Django?
In many functions in views.py the is a parameter called vars() that is passed to the render. I want to know what is the use of this parameter and is it better than passing local variable individually to render? return render(request, 'report.html', vars()) -
Adding data from model in extends
I'm trying to add the post with the most views in my header.html This page looks something like this: header.html <header> <p>{{ post.title }}</p> </header> {% block content %}{% endblock %} I have another page which is child.html that extends header: child.html {% extends 'header.html' %} {% block content %} //Some content {% endblock %} Only child.html is in views.py and it looks like this: views.py Class ChildView(TemplateView): template_name = 'child.html' I have a model named Post. I know I could query this model to find the Post with the most views in ChildView, but is this really necessary? Suppose I have multiple views all extending header.html I have to add query information to every view. Is there an easier way?