Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python Django model viewset -To get current user id
I want to get current user id to pass class document_typeViewSet(viewsets.ModelViewSet): user = User.objects.get(id=request.user.id) group = user.group.get() queryset = document_type.objects.filter(role_id=group) serializer_class = document_typeSerializer I am getting an error AttributeError: module 'request' has no attribute 'user'" -
Django, Salt: Can I get salt pillar values in django code?
I have a django project and saltstack formulas. My django project uses a django app in package form which is installed venv dist-packages. Django app reads config.ini in project root directory, there wasn't any problem when the django app's code live in project directory with config.ini together, but when I install my django app by pip install my app cannot read the config file with hard-coded path because the project's absolute path is defined by salt formula so it changes by salt pillar value. So, the question is, How can I use salt pillar's value(project directory definition) in my django app python code? Is there any library that I can use? import configparser def parse_config(): config = configparser.ConfigParser() config.read('config.ini') return config -
apache2 libapache2-mod-wsgi-py3 django
Previously my code was working with apache2 , django and libapache2-mod-wsgi. But i had to use python3 hence i removed libapache2-mod-wsgi and installed libapache2-mod-wsgi-py3 . Now I am getting error when i restart apache2. Below is the error from command "systemctl status apache2.service".. I dont know how to why WSGIScriptAlias is not working for libapache2-mod-wsgi-py3 The apache2 configtest failed. Output of config test was: AH00526: Syntax error on line 7 of /etc/apache2/sites-enabled/000-default.conf: Invalid command 'WSGIScriptAlias', perhaps misspelled or defined by a module not Action 'configtest' failed. The Apache error log may have more information. apache2.service: Control process exited, code=exited status=1 Failed to start LSB: Apache2 web server. apache2.service: Unit entered failed state. apache2.service: Failed with result 'exit-code'. -
How to use typeahead
I'm using typeahead for the first time. I don't know how to pass the URL and wildcard in typeahead. This is my typeahead: var getIsbn = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), queryTokenizer: Bloodhound.tokenizers.whitespace, remote: { url: '../data/films/queries/%QUERY.json', wildcard: '%QUERY' } }); $('#remote .typeahead').typeahead(null, { name: 'best-pictures', display: 'value', source: getIsbn }); I want to show the ISBN number of each book present in the database. I'm using Django 1.11 and python. Any suggestions? -
Where should I call custom method in django CBV? (DetailView)
I made a custom method that save session when call get() method in DetailView page. Here's sample of my code. class CustomDetailView(DetailView): model = Jobs template_name = "jobs/job_detail.html" context_object_name = "job" def custom_save_session(self, request): # save session and so on ... I wonder where should I call custom_save_session method. I tried to call it inside get(), get_context_data() and so on. All work well, but I have curiosity what is the best method. Should I call inside get() method? Cause I want to save session data every time get() called. Is there any method that call custom method when every time get() called in DetailView? (I also wonder not only DetailView, but also all CBV in django too) -
What is an best way of manipulating millions of records and saving back to database with option to cancel and pause?
Am using Django with python 2.7. am having an excel sheet with millions of rows. I have to manipulate rows data and save back to database (postgresql). I want to do it efficiently. Following are the approaches am thinking of : 1.) enqueue all the rows (data) in a queue (preferably RabbitMQ) and will fetch with a bunch of 100 entries at once. and will execute and will save it in database. 2.) thinking of using thread in background which will be managing 100 rows by each thread and will save back the result to database. I'm not sure how many database connections will be opened in this scenario. Can you please suggest me an efficient way to achieve this. it will be really very helpful. How to implement cancel and pause logic in this scenario? should i be using a database ? -
Refresh table content in django template on updation of mysqlDatabase content
I am new to django and Ajax .I am able to fetch the database content from mysql database,now I want everytime the data is updated in database ,my table also should get updated.I know I have to ajax ,but I dont have anyidea how to proceed with it.Please help me How I can proceed with it? This is my Views.py def index(request): testBenchdb = TestBenchDB.objects.all() template = loader.get_template('TestBench/MainView.html') context = { 'testBenchdb': testBenchdb, } return HttpResponse(template.render(context, request)) This is my model class class TestBenchDB(models.Model): Sl_No= models.IntegerField TestBenchID= models.CharField(max_length=200) project = models.CharField(max_length=200) status= models.CharField(max_length=200) TestPass = models.IntegerField TestFail=models.IntegerField FrameworkErrors=models.IntegerField LastUpdated=models.DateTimeField This is my template <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://fonts.googleapis.com/icon? family=Material+Icons"> <style> .blueboxed { border: 10px solid #b9fcff; background: #b9fcff; } .GreyBoxed{ border: 10px solid #f2f2f2; background: #f2f2f2; } .WhiteSpace { border: 5px solid #ffffff; background: #ffffff; } table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color:rgba(170,236,255,0.86); } th{ background-color: rgba(8,153,255,0.86) ; } tr{ -moz-box-shadow: 3px 3px 5px #535353; -webkit-box-shadow: 3px 3px 5px #535353; box-shadow: 3px 3px 5px #535353; -moz-border-radius: 6px 6px 6px 6px; -webkit-border-radius: 6px; border-radius: 6px 6px 6px 6px; } .roundbox { … -
Trying to add banned user into table, Django ADMIN
I have a function that bans users in my Admin User Model View.But i am unsure of how to then add that banned user to the Banned_User model. **Banning function** def ban_users(self, request, queryset): queryset.update(is_active = False) banned_user = Banned_User.objects.create(profile=profile) banned_user.save() self.message_user(request, "User banned") def remove_ban(self, request, queryset): print(queryset) queryset.update(is_active = True) self.message_user(request, "Users ban has been lifted") **Profile Admin view** class ProfileAdmin(admin.ModelAdmin): list_display = ('user', 'birth_date', 'sessions_played', 'total_reports') readonly_fields = (('sessions_played'),('birth_date'),('user'),('pref_server'),('teamwork_commends'),('skill_commends'),('sportsmanship_commends'),('communication_commends'),('discord_name'))#,'total_reports') def total_reports(self, obj): return Report.objects.filter(user_reported=obj).count() admin.site.register(Profile, ProfileAdmin) **User Admin View** class MyUserAdmin(UserAdmin): list_display = ('profileview','username', 'first_name', 'last_name' , 'email') readonly_fields = ('first_name' , ('last_name') , ('email') , ('username')) actions = ['ban', 'unban'] ban = ban_users unban = remove_ban def profileview(self, instance): return instance.profile.user admin.site.unregister(User) admin.site.register(User, MyUserAdmin) (Profile model has a OneToOneField to User) My Banning User Model is as follows: class Banned_User(models.Model): def __str__(self): return self.user.get_username profile = models.ForeignKey( 'Profile', on_delete=models.PROTECT, blank=False, null=False, related_name='banned_profile' ) report_reason = models.ForeignKey( 'report', on_delete=models.PROTECT, blank=False, null=False, related_name='reason_banned', ) date_banned = models.DateField(null=True, blank=False,) current errors are: name 'profile' is not defined but i am not sure if my code to add to the table is right either way. -
how to insert multiple records in django?
this is my views.py def input_transaksi(request): kode_pem = dict(request.POST)['kode_pem'] nominal = dict(request.POST)['nominal'] rincian = Transaksi(kode_pem=kode_pem,nominal=nominal) rincian.save() when i input data from this form {% for t in trans %} #for looping form <from method="post" action="{% url 'input_transaksi' %}" enctype="multipart/form-data"> <input type="hidden" name="kode_pem"> <input type="hidden" name="nominal"> <input type="submit" value="Insert" class="btn btn-primary"> </form> {% endfor %} but i get this error int() argument must be a string or a number, not 'list' how can i resolve it? -
`self.response_class` in `TemplateResponseMixin` don't call super()
Referencece to response_class in Django's code: django/base.py class TemplateResponseMixin: """A mixin that can be used to render a template.""" response_class = TemplateResponse def render_to_response(self, context, **response_kwargs): response_kwargs.setdefault('content_type', self.content_type) #here return self.response_class( #here request=self.request, template=self.get_template_names(), context=context, using=self.template_engine, **response_kwargs ) The class attribute setting response_class = TemplateResponse, while call it through instance's attribute self.response_class, I guess it might be super().response_class How to understand it? -
Nginx Proxy path to different port with Puppet
If I have an nginx server managed with Puppet, how would I go about using nginx as a proxy for any path that starts with hostname.com/api, and forward it to hostname.com:8000/api? Example puppet configuration for server: nginx::resource::server { "${site_name}": listen_port => 80, www_root => "/var/www/frontend", ssl_redirect => false, ssl => true, ssl_cert => "/etc/letsencrypt/live/${site_name}/fullchain.pem", ssl_key => "/etc/letsencrypt/live/${site_name}/privkey.pem", ssl_port => 443, } I tried this but it doesn't seem to be working (it still loads the react app instead of the api's front-facing template from django) nginx::resource::location{'/api': server => $site_name, ssl => true, proxy => "https://localhost:8000", } -
django duplicates my list in each request
I have a list of objects, each time the page is refreshed, the data are increases the same number of times: for example: if the list has 3 elements, in the second page refresh it will have 6 in the next 9 and thus in the following requests 12, 15, 18 and ever plus 3 I have a list of objects in django [ <cusomer 1 > <cusomer 2 > <cusomer 3 > ] when refresh mi site [ <cusomer 1 > <cusomer 2 > <cusomer 3 > <cusomer 1 > <cusomer 2 > <cusomer 3 > ] the same number of elements is increased in each request, this Class create list class EstablishmentData(object): all_equipments = [] all_technicals = [] all_service_orders = [] establishment = None dont_exist = 'El registro no existe' def __init__(self, id_establishment): try: self.establishment = Establecimiento.objects.get( pk=id_establishment ) except Exception: error = ' '.join([ self.dont_exist, 'id_establecimiento = ', id_establishment ]) logging.error(error) return False def getEquipments(self): all_equipments = EquipoEstablecimiento.objects.filter( id_establecimiento_id = self.establishment.id_establecimiento ) if not all_equipments: error = ' '.join([ self.dont_exist, 'id_establecimiento', str(self.establishment.id_establecimiento) ]) logging.error(error) logging.info('Establecimiento sin Equipos') return False for equipment in all_equipments: equipment = { 'equipment': equipment, 'model_equipment' : EquipoModelo.objects.get( pk = equipment.id_equipo_parametro_id ), 'service_orders': self.getAllServiceOrders( … -
docker container built and running but not working
My name is omar. I have a docker image and container for a project that I have just created and ran. So i am currently trying to test it on my local machine before pushing it to an online environment. I built it with no previous cache and it build the new docker which is running online. Why is it not working in my browser. Here is what I have. (MySplit) omars-mbp:mysplit omarjandali$ docker build --no-cache -t validation_test_1 . Sending build context to Docker daemon 56.07MB Step 1/7 : FROM python:3 ---> 79e1dc9af1c1 Step 2/7 : WORKDIR users/ Removing intermediate container 7030351beb91 ---> 30ac3f4ccbae Step 3/7 : COPY requirements.txt ./ ---> 57cbbd7335ab Step 4/7 : EXPOSE 80 ---> Running in 592407a176ff Removing intermediate container 592407a176ff ---> 523945ea529f Step 5/7 : RUN pip install -r requirements.txt ---> Running in 48347f772fbe Collecting Django==1.11.5 (from -r requirements.txt (line 1)) Downloading https://files.pythonhosted.org/packages/18/2d/b477232dd619d81766064cd07ba5b35e956ff8a8c5c5d41754e0392b96e3/Django-1.11.5-py2.py3-none-any.whl (6.9MB) Collecting gunicorn==19.7 (from -r requirements.txt (line 2)) Downloading https://files.pythonhosted.org/packages/96/4b/bc4bc2dad60defaa3f7d8590dc51331a225a5399380c161047c1224cd86d/gunicorn-19.7.0-py2.py3-none-any.whl (112kB) Collecting django-localflavor==1.5.3 (from -r requirements.txt (line 3)) Downloading https://files.pythonhosted.org/packages/da/47/69e53f69fb50a38766aa929c1f81fd2e6315edc7f3945174ead24ffcf6df/django-localflavor-1.5.3.tar.gz (4.7MB) Collecting synapse_pay_rest_native==3.1.1 (from -r requirements.txt (line 4)) Downloading https://files.pythonhosted.org/packages/43/27/b73d83dd50d4dfec1680d22896b800ddbb6bf8fb3f3a1755a916a6e4f732/synapse_pay_rest_native-3.1.1.tar.gz Collecting pytz (from Django==1.11.5->-r requirements.txt (line 1)) Downloading https://files.pythonhosted.org/packages/dc/83/15f7833b70d3e067ca91467ca245bae0f6fe56ddc7451aa0dc5606b120f2/pytz-2018.4-py2.py3-none-any.whl (510kB) Collecting requests (from synapse_pay_rest_native==3.1.1->-r requirements.txt (line 4)) Downloading https://files.pythonhosted.org/packages/49/df/50aa1999ab9bde74656c2919d9c0c085fd2b3775fd3eca826012bef76d8c/requests-2.18.4-py2.py3-none-any.whl (88kB) Collecting chardet<3.1.0,>=3.0.2 … -
ListView invokes the `get_template_names` without calling it
I am reading the Django source code of listview: django/list.py class MultipleObjectTemplateResponseMixin(TemplateResponseMixin): template_name_suffix = '_list' def get_template_names(self): try: names = super().get_template_names() class ListView(MultipleObjectTemplateResponseMixin, BaseListView): """ Render some list of objects, set by `self.model` or `self.queryset`. `self.queryset` can actually be any iterable of items, not just a queryset. """ When I defind ListViwe, template_name is assigned automatically class IndexView(generic.ListView): pass I assume there shoule have a assigning step in MultipleObjectTemplateResponseMixin as class MultipleObjectTemplateResponseMixin(TemplateResponseMixin): template_name_suffix = '_list' def get_template_names(self): try: names = super().get_template_names() .... template_name = self.get_template_names() How it invoke the get_template_names without call it? -
Trying to call is_active method from outside user model in Django ADMIN
Here I have a function that bans and unbans users.Currently I can use this in DjangoAdmin in my custom User Model. But what I am trying to do is ban users from the Profile model in my DjangoAdmin as well. Yet I keep receiving ERROR FieldDoesNotExist at /admin/api/profile/ Profile has no field named 'is_active' as is_active is a function of the User Model.I'm not sure how to go about being able to ban users from the Profile Model view in Admin. #Banning Function def ban_users(self, request, queryset): queryset.update(is_active = False) self.message_user(request, "User is banned and Email has been sent") def remove_ban(self, request, queryset): queryset.update(is_active = True) self.message_user(request, "Users ban has been lifted") #Admin functions will be created here,as well as registration of their specific models class ReportAdmin(admin.ModelAdmin): list_display = ('user_reported', 'report_reason', 'sent_by', 'session') admin.site.register(Report, ReportAdmin) class ProfileAdmin(admin.ModelAdmin): list_display = ('user', 'birth_date', 'sessions_played', 'total_reports') readonly_fields = (('sessions_played'),('birth_date'),('user'),('pref_server'),('teamwork_commends'),('skill_commends'),('sportsmanship_commends'),('communication_commends'),('discord_name'))#,'total_reports') actions = ['ban', 'unban'] ban = ban_users unban = remove_ban def total_reports(self, obj): return Report.objects.filter(user_reported=obj).count() admin.site.register(Profile, ProfileAdmin) class MyUserAdmin(UserAdmin): list_display = ('username', 'first_name', 'last_name' , 'email') readonly_fields = ('first_name' , ('last_name') , ('email') , ('username')) actions = ['ban', 'unban'] ban = ban_users unban = remove_ban admin.site.unregister(User) admin.site.register(User, MyUserAdmin) -
Django filter exclude foreign key
I'm coding a news website which has two models News and BestNews.News is a foreign key of BestNews. Now I have rendered News list and Best News list in index.html.But this two parts are duplicated. I hope news that in Best News list, will not appear in News list, and once I have removed the news from the Best News in admin, the news which has been removed from best news will appear News list. Here is my News model: class News(models.Model): title = models.CharField(max_length=100, verbose_name='标题') content = UEditorField(verbose_name="内容", width=600, height=300, imagePath="news/ueditor/", filePath="news/ueditor/", default='') class Meta: verbose_name = "新闻" verbose_name_plural = verbose_name def __str__(self): return self.title Here is my Best News model: class Best(models.Model): select_news = models.ForeignKey(News, on_delete=models.CASCADE, related_name='select_news',verbose_name='要闻') SELECT_REASON = ( ('左一', '左一'), ('左二', '左二'), ) select_reason = models.CharField(choices=SELECT_REASON, max_length=50, null=False) class Meta: verbose_name = "精选" verbose_name_plural = verbose_name def __str__(self): return self.select_reason + '-' + self.select_news.title Here is my News list view:I get News list and Best News list in one view. class NewsView(View): def get(self, request): all_news = News.objects.all().order_by('-pk') bestnews1 = Best.objects.filter(select_reason="左一")[0].select_news bestnews2 = Best.objects.filter(select_reason="左二")[0].select_news return render(request, 'index.html', { 'all_news': news, 'bestnews1':bestnews1, 'bestnews2':bestnews1, }) -
CodeDeploy running outdated appspec file?
I'm new to AWS CodeDeploy, in fact, I'm just experimenting. I'm trying to handle continuous integration using CircleCI 2.0 and AWS CodeDeploy so that when I push changes to my django project to development in github, it builds in CircleCI and then pushes the deploy to an S3 and after that the changes are deployed to the EC2. I did all the configurations in CodeDeploy, and I copied the appspec from a guy in github that used CodeDeploy with a Django/DRF project (such as mine). The only difference is that he was using another kernel in his EC2 instance (I think AWS linux) and I'm using ubuntu. So I had to change the username in the runas section of every hooks part. The first time I ran the create-deployment command in the aws cli the deployment failed with this message: LifecycleEvent - ApplicationStop Script - scripts/stop_application.sh [stderr]No passwd entry for user 'ec2-user' As it turned out, I forgot to change the runas useer in the ApplicationStop hook. Then I changed it, did the push and the create-deployment again, but the error remains to be the same. Do I need to do something else for the changes in the appspec to … -
Expected string or buffer Django
I've run into a wall while make an application. I can log into my home page but I run into the "Expected strong or buffer" . I found the error on line 16 of my views today=Appointment.objects.order_by('date').filter(date=now,user=user) I've done multiple things to fix this to no avail. views: #-*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, redirect from .models import User,Appointment from datetime import datetime from django.contrib import messages import bcrypt # Create your views here. def index(request): return render(request,'index.html') def home(request): now=datetime.now().strftime("%Y-%m-%d"), user =User.objects.get(id=request.session['user_id']) today=Appointment.objects.order_by('date').filter(date=now,user=user) laterdate=Appointment.objects.order_by('date').filter(user=user).exclude(date=now) context={ 'user':user, 'laterdate':laterdate, 'today':today, } return render(request,"welcome.html",context,now) def register(request): errors = User.objects.validate(request.POST) #print 'this process works', request.POST if len(errors) > 0: for error in errors: messages.error(request, error) return redirect("/") else: hashpwd = bcrypt.hashpw(request.POST["password"].encode(), bcrypt.gensalt()) newuser = User.objects.create( first_name=request.POST['first_name'], last_name=request.POST['last_name'], email=request.POST['email'], password=hashpwd) request.session['user_id'] = newuser.id request.session['name'] = newuser.first_name print "session info", newuser.id, newuser.first_name return redirect("/home") def login(request): errors = User.objects.loginvalidate(request.POST) if len(errors) > 0: for error in errors: messages.error(request, error) return redirect("/") else: user = User.objects.filter(email=request.POST['email'])[0] request.session['user_id'] = user.id request.session['name'] = user.first_name return redirect("/home") def logout(request): request.session.clear() print 'goodbye' return redirect('/') def delete(request,id): Appointment.objects.get(id=id).delete() return redirect('/home') def edit(request): appointment=Appointment.objects.get(id=id) context={ 'edit':appointment } return render(request,"update.html",context) def create(request): errors=Appointment.objects.appointvalidate(request.POST) if len(errors)>0: for … -
Issue with allowed ports - docker/django
I have a django project in dockerhub. I pulled and ran the docker image into a digital ocean droplet to test if working. I am getting the following error: Invalid HTTP_HOST header: '167.99.106.66'. You may need to add '167.99.106.66' to ALLOWED_HOSTS. now i did add the link into the allowed_hosts in my django setting file, but the url is still now working. is there anyway to fix it or any other info I need to add to get this working: the following is in the django settings file: ALLOWED_HOSTS = ['167.99.106.66', 'localhost', '127.0.0.1'] -
Mirroring my Django model validation logic in the database via constraints. Good idea, bad idea, or not worth it?
It's always rubbed me the wrong way to write code in my model's clean method to validate various constraints on the data when these same constraints aren't also present in the database. After all, the database already has constraints for some of my data, like NOT NULL. So, I've been writing RawSQL migrations that ADD CONSTRAINT some_logic in my most recent project that matches whatever logic I have in my clean() method. It works OK, but it isn't an insignificant task to remember to add these constraints. Also, of course, I'm violating DRY by writing code in two places to do the same thing. Should I give up this quixotic quest? -
Override the ListView attributes
When override the attributes of class view, it comes with: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' I assume it should be: class IndexView(generic.ListView): def __init__(self, *args, **kwargs): super().__init__(self, *args, **kwargs): template_name = 'polls/index.html' context_object_name = 'latest_question_list' How Django achieve it by assign variable directly? -
Deploying Django Application with PostgreSQL to Kubernetes Google Cloud cluster
I am having trouble trying to deploy my Django Application and PostgreSQL database to Kubernetes Google Cloud cluster that I've already configured. I have successfully created Docker containers for my Django Application and PostgreSQL database. Here is what my docker-compose.yml file looks like: version: '3' services: db: image: postgres environment: - POSTGRES_USER=stefan_radonjic - POSTGRES_PASSWORD=cepajecar995 - POSTGRES_DB=agent_technologies_db web: build: . command: python manage.py runserver 0.0.0.0:8000 --settings=agents.config.docker-settings volumes: - .:/agent-technologies ports: - "8000:8000" links: - db depends_on: - db I have already build the images, and tried sudo docker-compose up command, and the application works perfectly fine. After successfully dockerizing Django Application and PostgreSQL, I have tried to configure Deployment / Service YML files required by Kubernetes, but I am having trouble doing so. For example: deployment-definition.yml - File for deploying Django application: apiVersion: apps/v1 kind: Deployment metadata: name: agent-technologies-deployment labels: app: agent-technologies tier: backend spec: template: metadata: name: agent-technologies-pod labels: app: agent-technologies tier: backend spec: containers: - name: image: ports: - containerPort: 8000 replicas: selector: matchLabels: tier: backend Inside container list of dictionaries, I know that my container name should be web, but I am not sure where the image of that container is located so I do not know what … -
Created in test setup objects can not be accessed through database
I got a def setUpClass(cls): which initializes objects i need in my tests like this cls.user = User.objects.create(username="user1", password="password") In the view I test i use a db query like User.objects.get(id=given_id) and I get an empty queryset. How can I fix it? -
Weighted average in Django with filter and annotation
I am trying to get the weighted average from a table consisting multiple columns. My table looks like +----------------------------------+--- | WEIGHT |URBRUR |HHSTATE| |TRPMILES| +----------------------------------+--- |68170.67043 2 IN 15 |68170.67043 1 KS 12 |68170.67043 1 IN 22 |68170.67043 1 CA 20 |68170.67043 2 CA 20 |69589.49646 1 CA 22 |69589.49646 2 KS 14.5 |69589.49646 2 TX 22.4 |69589.49646 1 KS 23 |69589.49646 2 IN 21 |69589.49646 2 TX 22 |69589.49646 1 CA 20 |69589.49646 2 KS 20 |522885.4726 1 CA 34 |522885.4726 2 TX 4 |522885.4726 1 TX 6 |522885.4726 2 TX 23 |522885.4726 1 IN 16 |117718.4261 1 KS 11 |117718.4261 1 TX 5 +---------------------------------- I want to get the result for the weighted average trip miles made by each state where urbrur is 1 for every state like First, I will apply a filter in Django like table.objects.filter(urbrur__contains="1") then I want to to take weighted average for every state. The output, in this case, should be two different results one for the urbrur=1 and one for the urbrur=2. For urbrur=1 the results should be like CA 29446.43 TX 25.405 IN 132791.77 etc... similar kind of table for urbrur=2 as well. The entries are simply (weight*trpmile)/Sum(weight) for each state. … -
How to capture optional GET parameters django
Say someone wants to GET an entity called a Volume, which is a model in django. I have exposed an endpoint: urlpatterns = [ ... path('vol', views.volume_view, name='volume query'), path('vol/<str:volume>', views.volume_view, name='volume specific query'), ... ] and the view volume_view has a signature like (it's inside of a GenericViewSet): def volume_view(self, request, volume="", format=None): ... All is good when the user makes a request like: requests.get("http:/.../my_app/vol") or, if the user makes a request like: requests.get("http:/.../my_app/vol/some_prefix_here") which returns to the user all of the volumes that I currently have stored, and a subset, respectively. However, I wanted to allow for some smart, optional, options, like: page: do you want to paginate the responses? from and to: timestamps to give a range query. prefix: search for any volume matching this prefix. So I thought, put them inside the request.GET header dictionary. Once I put in for example: requests.get("http:/.../my_app/vol", params={"page":False}) The urlpatterns could not find it! Which makes sense, since in GET's, the params are appended to your url as a querystring: When I run python manage.py runserver on this, I get this with no querystring: [02/May/2018 22:23:13] "GET /my_app/vol HTTP/1.1" 200 123 And this when I do run it with a querystring: …