Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get and post different type multiple values in django?
Goal: Inserting multiple value that selected by checkbox to database. Description I have two(of course many models that don't want mentioned here) models: Products , SellInvoiceItems. I get list of all items that checked by checkbox via pdlist = request.POST.getlist("inproducts") and puting in Product list stkpd = models.Stocksupporter.objects.filter(stockid=6).exclude(numberqut=0).filter(productid__in = pd). with for loop i get all items in stkpd and done good look like productname. it inserted for each selected value. ** Problem:** how can i get qty from (<input type="number" name="innumber"> ) for all selected? i using request.POST.get("innumber") but it get latest value in list. View : class sale_initems(generic.DetailView): model = models.Sellinvoice template_name = "webapp/saleinitems.html" def get(self , request): if request.user.is_authenticated: list = models.Products.objects.exclude(numberqut = 0) return render(request, self.template_name , {'list ' : list}) def post(self, request): if request.user.is_authenticated: pdlist = request.POST.getlist("inproducts") stkpd = models.Products.objects.exclude(numberqut=0).filter(productid__in = pdlist) # sellinvoiceitems for item in stkpd: qty = "" <<-- problem price = int(item.price1) numinbox = int(item.numberinbox) models.Sellinvoiceitems ( productid = item.productid, productname = item.productname, totalnumber =qty, cartoonnumber = qty / numinbox, minorprice = price, totalprice = qty * price, sellinvoice = invoice, stockid = stock ).save() return redirect("webapp:saleinvoice") Template {% for pr in list%} <div> <span style="display: inline-block;"> <input type="checkbox" value="{{ … -
TypeError: WishListItems() got an unexpected keyword argument 'user' in django rest framework
I got this error saying got an unexpected error keyword "user" when calling api.In postman, it also shows this. Error in Postman : TypeError at /api/additemwishlist/7/products/2 Got a TypeError when calling WishListItems.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to WishListItems.objects.create(). You may need to make the field read-only, or override the WishListItemsTestSerializer.create() method to handle this correctly. This code was working few days ago, but I am getting this error now. I am not sure why. My models: class WishList(models.Model): owner = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) # item = models.ManyToManyField(Product,blank=True, null=True) def __str__(self): return self.owner.email class WishListItems(models.Model): wishlist = models.ForeignKey(WishList,on_delete=models.CASCADE, related_name='wishlistitems') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) def __str__(self): return self.item.name My view: class WishListItemsAPIView(ListCreateAPIView): permission_classes = [IsAuthenticated] queryset = WishListItems.objects.all() serializer_class = WishListItemsTestSerializer def perform_create(self, serializer): # user = self.request.user wishlist = get_object_or_404(WishList, pk=self.kwargs['pk1']) item = get_object_or_404(Product, pk=self.kwargs['pk2']) serializer.save(wishlist=wishlist,item=item) My serializer: class WishListItemsTestSerializer(serializers.ModelSerializer): wishlist = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = WishListItems fields = ['id','wishlist','item'] depth = 1 My url: path('api/additemwishlist/<int:pk1>/products/<int:pk2>', views.WishListItemsAPIView.as_view(), name='api-wishlistitems-add'), Here pk1 is wishlist id and pk2 is product id. -
React Invalid Token getting unauthorized, using axios , also unable to logout
React Invalid Token getting unauthorized, using Axios, also unable to logout from user account -
How to fix race condition in Django save_model method that calls Celery task?
I have a Django Model Admin where I override the save_model method like so: def save_model(self, request, obj, form, change): if not change and obj.to_be_called and not obj.task_called: if TrackableCeleryTasks.is_value_present(obj.task_name): super().save_model(request, obj, form, change) async_result = TrackableCeleryTasks.get_celery_task(obj.task_name) \ .apply_async((obj.object_id,), eta=obj.eta) obj.task_called = True obj.task_id = async_result.task_id async_result.forget() if not obj.content_type and obj.object_id: obj.content_type = TrackableCeleryTasks.get_content_type(obj.task_name) super().save_model(request, obj, form, change) In the code above, when I save a TrackedCeleryTask via Django Admin, if conditions are satisfied, I call a celery task by name. The task gets called successfully. Here is the task I call: @task(bind=True, name="Flip drop live", acks_late=True, track_started=True) def flip_drop_live(self, drop_id): try: drop = Drop.objects.get(id=drop_id, is_live=False) drop.is_live = True drop.save() update_tracked_celery_task.delay(self.request.id, goal=True) return f"drop {drop_id} flipped live" except Drop.DoesNotExist: update_tracked_celery_task.delay(self.request.id, goal=False) return f"not live drop {drop_id} doos not exist" Notice in the above task I end up making another .delay() call to another task which is responsible for updating the corresponding TrackedCeleryTask which spawned this celery task chain. Here is the celery task that get's called once the logic is executed succesfully: @task(name="update_tracked_celery_task") def update_tracked_celery_task(task_id, goal): try: celery_task_obj = TrackedCeleryTask.objects.get(task_id=task_id) async_result = AsyncResult(task_id) celery_task_obj.state = async_result.state celery_task_obj.goal = goal celery_task_obj.save() async_result.forget except TrackedCeleryTask.DoesNotExist: return f"{task_id} is not a tracked … -
assertHTMLEqual() via pytest
I prefer pytest-django to the Django way of testing. It works fine, except that I don't know how to assertHTMLEqual() via pytest. How to assert that the HTML snippets are almost equal? -
For single product: React TypeError: Cannot read property ‘map’ of undefined : [closed]
This is a single product data . const [single, setSingle]= useState([]) setSingle(res.data) (axios set state) { "id": 135, "device_detail": [ { "type": "high-speed", "brief": "dsf", "model": "ds", "serial": "ds" }, { "type": "low-speed", "brief": "dfg", "model": "hgj", "serial": "dsf" } ], "device_name": "Handpieces", "practice_name": "dsf", "unit": "dsf", "street": "dsf",, "status": 1, "created_at": "2021-03-02 14:00:58.295738+00:00" } When i use {single.device_detail.map((subd,index)=>( (index ? ', ' : '') + subd.type ))} its saying TypeError: Cannot read property ‘map’ of undefined : but when i make another state for device_detail and then its working like this: const [dd, setdd]= useState([]) setdd(res.data.device_detail) (axios set state) But, i this is not a proper solution. Any idea? -
Unable to start Django app in docker with Daphne
I was setting up Django app in docker with gunicorn + nginx + daphne. But I'm not able to get the app running with daphine error log showing this: Traceback (most recent call last): File "/usr/local/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) File "/usr/local/lib/python3.6/dist-packages/daphne/cli.py", line 191, in entrypoint cls().run(sys.argv[1:]) File "/usr/local/lib/python3.6/dist-packages/daphne/cli.py", line 252, in run application = import_by_path(args.application) File "/usr/local/lib/python3.6/dist-packages/daphne/utils.py", line 12, in import_by_path target = importlib.import_module(module_path) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 991, in _gcd_import File "<frozen importlib._bootstrap>", line 930, in _sanity_check ValueError: Empty module name Any idea what can be causing this error and any possible solution? -
Runtime Error Connecting Django with Firebase
I am trying to connect my Firebase Db with my django web app which will read the data from FireBase DB and post on Browser. I referenced the documentation from https://www.geeksforgeeks.org/how-to-create-a-new-project-in-django-using-firebase-database/ I am getting a runtime error- django.db.utils.DatabaseError: file is not a database. Here is the code view.py : from django.shortcuts import render import pyrebase # Create your views here. config = { "apiKey": "Use your Api Key Here", "authDomain": "Use your authDomain Here", "databaseURL": "Use your databaseUrl here", "projectId": "Use your projectId here", "storageBucket": "Use your storage Bucket here", "messagingSenderId": "Use your messageSenderId here", "appId": "Use your appId here" } firebase= pyrebase.initialize_app(config) auth = firebase.auth() database = firebase.database() def home(request): Day = database.child("Data").child('Day').get().val() ID = database.child('Data').child('ID').get().val() Projectname = database.child('Data').child("Projectname").get().val() return render(request, "home.html", {"Day":Day,"ID":ID,"Projectname":Projectname}) testto.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('home/', include('pro.urls')) ] pro/urls.py from django.urls import path from pro import views urlpatterns= [ path('', views.home) ] home.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Sample Project</title> </head> <body> <h1>Project Name is {{Projectname}}</h1><br> <h2>Project Id is{{id}}</h2><br> <h3>Day{{day}}</h3><br> </body> </html> settings.py INSTALLED_APPS = [ 'pro.apps.ProConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', … -
AssertionError: View function mapping is overwriting an existing endpoint function: newRoom
I am creating a game. I want it so that a player calls the "room/new_game", a new URL is created for them and a new newroom.html is rendered. Everything is fine the first time but if a another user tries to host their own room, I get an error. Here's my code @app.route('/') def index(): return render_template("index.html", server=server) @app.route('/room/new_game', methods=['POST']) def newGame(): game = Games.Game result = {} result["game_code"] = game.room_code @app.route('/room/' + game.room_code) def newRoom(): return render_template("newroom.html", room_code=game.room_code.upper()) return jsonify(result) Error Traceback (most recent call last): File "/usr/lib/python3/dist-packages/flask/app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "/usr/lib/python3/dist-packages/flask/app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/ianc/.local/lib/python3.7/site-packages/flask_cors/extension.py", line 165, in wrapped_function return cors_after_request(app.make_response(f(*args, **kwargs))) File "/usr/lib/python3/dist-packages/flask/app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "/usr/lib/python3/dist-packages/flask/_compat.py", line 35, in reraise raise value File "/usr/lib/python3/dist-packages/flask/app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "/usr/lib/python3/dist-packages/flask/app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/ianc/Documents/OneNightUltimateWerewolf/test.py", line 35, in newGame @app.route('/room/' + game.room_code) File "/usr/lib/python3/dist-packages/flask/app.py", line 1250, in decorator self.add_url_rule(rule, endpoint, f, **options) File "/usr/lib/python3/dist-packages/flask/app.py", line 66, in wrapper_func return f(self, *args, **kwargs) File "/usr/lib/python3/dist-packages/flask/app.py", line 1221, in add_url_rule 'existing endpoint function: %s' % endpoint) AssertionError: View function mapping is overwriting an existing endpoint function: newRoom … -
how to create a dowload function in django allow user to choose the file destination in django
i trying to a create download function which allow the user to select file destination. For example, while the user click on the download button, it will pop up the user PC directory and let them select the file destination such as download a image from google. -
Model is not throwing data to the backend in Django
def UpdateProfile(request): context = {} user = request. User if not user.is_authenticated: return redirect('login') if request. POST: form = PersonalInfo(request. POST, instance=user) if form.is_valid(): obj = form. Save(commit=False) user = user.id obj.user = user obj.save() return redirect('profile') else: #messages.error(request, ('Please correct the error below.')) context['personal_form'] = form else: form = PersonalInfo(instance=user) context['personal_form'] = form return render(request, 'admission/signup.html', context) #This is function for updating user's info, in views.py This is the model I have created for storing user info class Applicant Info(models.Model): infield = models.AutoField(primary_key=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) profile_pic = models.ImageField(upload_to='media/', blank= True, null= True) father_name = models.CharField(max_length=30) user = models.OneToOneField(User, on_delete=models.CASCADE) this is the form class i have creatwd. from .models import Applicant, ApplicantInfo from django import forms class PersonalInfo(forms.ModelForm): pass `The app has been able to load the form without any trouble but it just not throwing data to the backend. -
builtins.TypeError: _findCaller() takes from 1 to 2 positional arguments but 3 were given in django
I have a scraping project with django. Everything work fine, but terminal shows this error: builtins.TypeError: _findCaller() takes from 1 to 2 positional arguments but 3 were given What is this error? How can I handle it? -
upstream timed out (110: Connection timed out) while connecting to upstream
I wanted to deploy my django website on port number 8000 in my aws ec2 instance of ubuntu machine. But after running the nginx server, I'm getting following 400/Bad request error in the browser and in the nginx error log, it's showing as follows. upstream timed out (110: Connection timed out) while connecting to upstream, client: 23.104.74.85, server: , request: "GET / HTTP/1.1", upstream: "http://2.12.52.96:8080/", host: "2.12.52.96" Below are my code snippets. my_site.conf # the upstream component nginx needs to connect to upstream django { server unix:///home/ubuntu/my_site/my_site.sock; } # configuration of the server server { listen 8000; server_name 2.12.52.96; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media { alias /home/ubuntu/my_site/media; } location /static { alias /home/ubuntu/my_site/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass 2.12.52.96:8000; include /home/ubuntu/my_site/uwsgi_params; } } uwsgi_params uwsgi_param QUERY_STRING $query_string; uwsgi_param REQUEST_METHOD $request_method; uwsgi_param CONTENT_TYPE $content_type; uwsgi_param CONTENT_LENGTH $content_length; uwsgi_param REQUEST_URI $request_uri; uwsgi_param PATH_INFO $document_uri; uwsgi_param DOCUMENT_ROOT $document_root; uwsgi_param SERVER_PROTOCOL $server_protocol; uwsgi_param REQUEST_SCHEME $scheme; uwsgi_param HTTPS $https if_not_empty; uwsgi_param REMOTE_ADDR $remote_addr; uwsgi_param REMOTE_PORT $remote_port; uwsgi_param SERVER_PORT $server_port; uwsgi_param SERVER_NAME $server_name; my_site.ini [uwsgi] # full path to Django project's root directory chdir = /home/ubuntu/my_site/ … -
My dockerized django server is working in local, but not in AWS especially POST method
I made an website using django, gunicorn, nginx, docker, and docker compose. When I tested it in my local computer, it worked well as it was. However, this app is not working in AWS. I deployed this app in ec2, made an application load balancer for it, and used Route53 for set domain. I can see my first page and also can do GET method, but POST method isnt work. How can I fix it? docker-compose.yml version: "3" services: nginx: image: nginx:latest ports: - "80:80" - "443:443" volumes: - .:/project - ./nginx:/etc/nginx/conf.d depends_on: - web web: build: context: . dockerfile: Dockerfile volumes: - .:/project command: sh -c "cd project && gunicorn -k gevent project.wsgi:application --bind 0.0.0.0:8000 --timeout 400" expose: - "8000" /nginx/default.conf upstream web { ip_hash; server web:8000; } server { listen 80; server_name localhost, {my domain}; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location /static { alias /project/project/static; } location / { proxy_pass http://web/; proxy_set_header Host $http_host; proxy_connect_timeout 10080s; proxy_send_timeout 10080; proxy_read_timeout 10080; proxy_buffer_size 64k; proxy_buffers 16 32k; proxy_busy_buffers_size 64k; proxy_redirect off; proxy_request_buffering off; proxy_buffering off; } } Logs in my AWS ec2 nginx_1 | 172.31.16.174 - - [03/Mar/2021:05:19:21 +0000] "GET / HTTP/1.1" 499 0 "-" "ELB-HealthChecker/2.0" nginx_1 | 172.31.33.230 - - … -
why my django rest_framework does not work?
im trying to use a SearchFilter in django, but i dont understand why its not work here are my models: class Country(models.Model): ''' Modelo de pais ''' id = models.AutoField(primary_key=True) name = models.CharField(max_length=70, verbose_name='Nombre de pais', null=False, blank=False) class Category(models.Model): ''' Modelo de categoria ''' id = models.AutoField(primary_key=True) name = models.CharField(max_length=150, verbose_name='Nombre de ciudad', null=False, blank=False) class Client(models.Model): ''' Modelo de cliente ''' id = models.AutoField(primary_key=True) name_client = models.CharField(max_length=150, null=False, blank=False) country = models.ForeignKey(Country, verbose_name='Client country', on_delete=models.PROTECT, null=False, blank=False) city = models.CharField(max_length=150, verbose_name='Ciudad de residencia', null=False, blank=False) category = models.ForeignKey(Category, verbose_name='Client category', on_delete=models.PROTECT, null=False, blank=False) user_created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) updated_at = models.DateTimeField(auto_now=True) here is my view: class ClientViewset(viewsets.ModelViewSet): """ Api view encargada de administrar la informacion del modelo cliente """ queryset = Client.objects.all() serializer_class = ClientSerializer filter_backends = (OrderingFilter, SearchFilter,) search_fields = ('city') when i make a request to my api i get all records in database for model client. -
how to merge pdf FileResponse from different views into one pdf file
Here I am returning pdf file from first function, def file_pdf_to_merge(id): pdf=SimpleDocTemplate(file_name(id)) flow_obj=flow_obj_for_display(id) pdf.build(flow_obj) return FileResponse(pdf,as_attachment=False,content_type='application/pdf') and second file is from this function def file_get_ri_pdf(id): #response = FileResponse(content_type='application/pdf') #response['Content-Disposition'] = file_name(id) pdf=SimpleDocTemplate(file_name(id)) flow_obj=flow_obj_ri_display(id) pdf.build(flow_obj) return FileResponse(pdf,as_attachment=False,content_type='application/pdf') Here both views are called Method 1 def pdf_(request,id): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="ReceiptRequest.pdf"' estimate_pdf=file_pdf_to_merge(id) reimbInv_pdf=file_get_ri_pdf(id) pdfs=[estimate_pdf,reimbInv_pdf] pdfMerger=[] for pdf in pdfs: with open(pdf, 'rb') as f: pdfMerger.append(f) with open(response,'wb') as f: pdfMerger.write(f) return response Method 2 def pdf_(request,id): output='Jazz_Receipt_Request.pdf' pdfMerger=PyPDF2.PdfFileMerger() pdfMerger.append(file_pdf_to_merge(id)) pdfMerger.append(file_get_ri_pdf(id)) with open(output, 'wb') as f: pdfMerger.write(f) return output I have tried both methods non of them has worked. -
How do I pass a QuerySet from python to js?
So I'm currently working in Django and I wanted to grab data from my database and use it in my js script. This is what I'm trying to pass into js, stockhist=StockHistory.objects.filter(user_id=x).values() -
django channels & react WebSocket Still in Connecting state
WebSocket's readyState changes from 1 to 0 after a few seconds. It appears connected in Django, but disconnected in React. Also, a log called WebSocket Client Connected appears continuously. Why is that? What should I do? Please tell me the correct answer.... import { w3cwebsocket as W3CWebSocket } from "websocket"; function SelectChampR(props) { const client = new W3CWebSocket ('ws://[IP]:8000/ws/channel/'+props.room); client.onopen = () =>{ console.log('WebSocket Client Connected'); }; let [messages, setMesage] = useState([]); useEffect(()=>{ if(props.room !== null && props.room !== undefined && props.room !==""){ client.onopen = () =>{ console.log('WebSocket Client Connected'); }; client.onclose = (e) =>{ console.error("채팅 소켓이 닫힘",e); } client.onmessage = (message) =>{ const dataFormServer = JSON.parse(message.data); console.log(dataFormServer); if(dataFormServer){ setMesage( [...messages, { msg: dataFormServer.message, name:dataFormServer.name, }] ) }; } } }, [messages]); let nextId = useRef(1); const Select_right = async (img,name) =>{ if (nextId.current !== 6) { let form_data = new FormData(); form_data.append('pick_'+nextId.current, img); form_data.append('pick_champ_'+nextId.current, name); client.send(JSON.stringify({ type:"mesage", message:form_data, name:props.username })); nextId.current++; }; let banId = useRef(1) const Select_blue_ban = (img,name) =>{ if (banId.current !== 6) { let form_data = new FormData(); form_data.append('ban_'+banId.current, img); form_data.append('ban_champ_'+banId.current, name); client.send(JSON.stringify({ type:"mesage", message:form_data, name:props.username })); input_db_blue_ban(form_data); setBR(false); banId.current++; } } const [seconds_r, setSecondsR] = useState(30); const [seconds_b, setSecondsB] = useState(30); let [timeFlag, setTimeFlag] =useState(true); … -
Django: How do "chained" filters work in separate queryset statements?
From reading the documentation and this post here in SO, I understand that: .filter(A, B) - means only rows that satisfy both A and B will be returned .filter(A).filter(B) - means rows that satisfy either A or B will be returned But I have situations where an admin may have the ability to access all, while a normal user's access will depend on other factors, which require additional filters to be added to the queryset. Another use case is an auto-complete view, which builds the base queryset (for all rows), then modifies it only if a search value was provided. Here are a couple of examples: def get_queryset(self): user = self.request.user queryset = Client.objects \ .select_related('country') \ .prefetch_related('rates', 'tags', 'tags__tag') if self.view_type == 'archived': queryset = queryset.filter(status=StatusFieldModelMixin.Status.ARCHIVED) else: queryset = queryset.filter(status=StatusFieldModelMixin.Status.ACTIVE) if user.has_perm('access_all_clients', scope='global'): # Custom has_perm method return queryset queryset = queryset.distinct() \ .filter( Q(client_team_assignments__team_member__user=user) & Q(client_team_assignments__status=StatusFieldModelMixin.Status.ACTIVE) ) return queryset def get_queryset(self): project_id = self.kwargs['pk'] if 'pk' in self.kwargs else None queryset = Sprint.objects.filter(project__id=project_id, status=StatusFieldModelMixin.Status.ACTIVE) search_key = self.kwargs['search_key'] if 'search_key' in self.kwargs else None if search_key: queryset = queryset.filter(name__icontains=search_key) return queryset My question is, how do those subsequent queryset = queryset.filter(...) statements actually work? Is it an "AND", like … -
Django main query ordered by subquery
I want to make main queryset ordered by subquery list. The relationship between models can be briefly expressed as follows. class Firm(models.Model): cik = models.IntegerField(primary_key=True) class Stock(models.Model): ticker = models.CharField(max_length=5,primary_key=True) firm = models.ForeignKey(Firm, on_delete=models.CASCADE,null=True) class File(models.Model): accNumber = models.IntegerField(primary_key=True) firm = models.ForeignKey(Firm, on_delete=models.SET_NULL, null=True) What I want to query : SELECT ticker FROM Stock WHERE firm_id = ( SELECT firm_id, count(*) as total FROM File WHERE created_at >yesterday AND created at < today GROUP BY firm_id ORDER BY total ) I use django.db.models.Subquery to make the nested SQL above. Django code : firm_list = File.objects\ .filter(Q(created_at__gte=yesterday)|Q(created_at__lte=today))\ .values('firm_id')\ .annotate(total=Count('firm_id'))\ .order_by('-total') ticker_list = Stock.objects.filter(firm_id__in=Subquery(firm_list.values('firm_id'))).only('ticker') I want to make ticker list ordered by firm list order. firm list order is like >>>firm_list.values('firm_id') <QuerySet [{'firm_id': 1750}, {'firm_id': 1800}, {'firm_id': 4977}, {'firm_id': 3453}]> but the ticker list is not ordered by subquery. >>> ticker_list.values('firm_id') <QuerySet [{'firm_id': 1750}, {'firm_id': 1800}, {'firm_id': 3453}, {'firm_id': 4977}]> How can I make the main query ordered by subquery list order?? I'm using sqlite for db. Thank you. -
Conflicting with version dependencies when running pip install
Having issues with version dependencies when running pip install on docker. However, when installing on my mac without docker and just virtualenv, works perfectly fine. These are the versions I used on my local machine: Mac OS - macOS Mojave v10.14. Python Version - v3.7.3 Docker Compose Version - version 1.27.4, build 40524192 Here's the first error I got when running the docker-compose up ERROR: Cannot install -r ./python-project/requirements/base.txt (line 104), -r ./python-project/requirements/base.txt (line 109), -r ./python-project/requirements/base.txt (line 114), -r ./python-project/requirements/base.txt (line 116), -r ./python-project/requirements/base.txt (line 141), -r ./python-project/requirements/base.txt (line 144), -r ./python-project/requirements/base.txt (line 145), -r ./python-project/requirements/base.txt (line 87) and six==1.10.0 because these package versions have conflicting dependencies. The conflict is caused by: The user requested six==1.10.0 bcrypt 3.2.0 depends on six>=1.4.1 cvxpy 1.0.25 depends on six django-anymail 0.5 depends on six django-compat 1.0.15 depends on six>=1.10.0 django-extensions 2.2.1 depends on six>=1.2 drf-yasg 1.16.1 depends on six>=1.10.0 fake-factory 0.6.0 depends on six google-api-core 1.26.0 depends on six>=1.13.0 To fix this you could try to: 1. loosen the range of package versions you've specified 2. remove package versions to allow pip attempt to solve the dependency conflict ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/user_guide/#fixing-conflicting-dependencies ERROR: Service 'backend' failed to build : The … -
Django Test Redirect to login with next parameter
I'm trying to Test non-login user redirect to login url. Is there a way to pass get parameter (example 'next') to reverse_lazy? I'm using class-based views. class SecretIndexViewTest(TestCase): url = reverse_lazy('secret_index') login_url = reverse_lazy('login') client = Client() def test_http_status_code_302(self): response = self.client.get(self.url) self.assertEqual(response.status_code, 302) self.assertRedirects(response, self.login_url,) above fails with Response redirected to '/login?next=/secret', expected '/login'Expected '/login?next=/secret' to equal '/login'. tried class SecretIndexViewTest(TestCase): url = reverse_lazy('secret_index') login_url = reverse_lazy('login', kwargs={'next': url) client = Client() def test_http_status_code_302(self): response = self.client.get(self.url) self.assertEqual(response.status_code, 302) self.assertRedirects(response, self.login_url,) result is no reverse match django.urls.exceptions.NoReverseMatch: Reverse for 'login' with keyword arguments '{'next': '/secret'}' not found. 1 pattern(s) tried: ['/login$'] changing kwargs to args will result the same error. -
How to get django-filter to not overwrite get params
I am using django-tables2 along with django-filter. The URL to load the page looks like http://localhost:8000/pleasehelp/?param=abc. I need the param value to load the page. I am using a filter that looks like: class MyFilter(django_filters.FilterSet): class Meta: model = MyModel fields = { 'name': ['icontains'], 'city': ['icontains'], } which relates to the simple model: class MyModel(models.Model): name = models.CharField(max_length=20) city = models.CharField(max_length=20) I have also created a simple View which consists of: class MyView(SingleTableMixin, FilterView): model = MyModel template_name = "pleasehelp/index.html" context_object_name = 'items' paginate_by = 25 table_class = MyTable filterset_class = MyFilter And a table consisting of: class MyTable(tables.Table): extra_column = tables.Column(empty_values=()) class Meta: model = MyModel template_name = "django_tables2/bootstrap4.html" fields = ('name', 'city', 'extra_column') def render_extra_column(self, record): """Render our custom distance column """ param = self.request.GET.get('param', '') return param Lastly my index.html looks like: {% load static %} {% load render_table from django_tables2 %} {% load bootstrap4 %} {% block content %} {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='inline' %} {% bootstrap_button 'filter' %} </form> {% endif %} {% if items %} {% render_table table %} {% else %} <p>No items were found</p> {% endif %} <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script src={% static 'site/javascript_helpers.js' … -
How to get the local machine time zone in a Django application?
In Django you have a TIME_ZONE setting, which, as I understand, somehow patches the standard date and time packages in runtime, making them think the application is working in the time zone specified. As a result, generic Python methods for determining local time zone do not work (they just show the configured time zone). I can evaluate the link of /etc/localtime like in this answer or use another Linux-specific method but I am concerned about the portability issue, as some developers run the app on Windows. Can I find out in a platform independent way what was the original time zone on the machine? -
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> doesn't work
I link css to html on vs-code. center-aliend doesn't work here. Is there anyone who knows what part is wrong? I want to set the text 'Hello Static!!' to the center of the browser. <home.html> {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <title>Static Practice</title> </head> <body> <div>Hello Static!!</div> </body> </html> <style.css> body { text-align: center; } <static_ex / settings.py> # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] enter image description here