Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a search function in Django with multiple queryset?
Hi i'm having trouble with my search function, I want to get product and quantity items from DB as user inputs data in searchbar... but the problem is that im having getting no results.. any help? views.py def productsearch(request): try: product=request.GET.get['product'] quantity=request.GET.get['quantity'] product_result=Product.objects.filter(product_id__icontains=product) quantity_result=Product.objects.filter(quantity_onhand__icontains=quantity) return render_to_response('product/productlocation.html',{'product_result' : product_result,'quantity_result':quantity_result, 'product': product,'quantity':quantity}) except: return render_to_response('product/productlocation.html') template to show result {% if quantity_result %} {% for r in quantity_result %} {{r.quantity_onhand}} {% endfor %} {% else %} <h3>no results</h3> {% endif %} search bar <form action="{% url 'productsearch' %}" method="get"> <label for="from">Product</label> <input type="text" name="product" value={{request.GET.product}}> <br /><br /> <label for="to">Quantity &nbsp;</label> <input type="text" name="quantity" value={{request.GET.quantity}}> <br /> <input type="submit" value="Submit"> </form> models.py class Product(models.Model): product_id = models.CharField(max_length=100, primary_key=True) product_name=models.CharField("Product Name",max_length=50) product_unitprice=models.PositiveIntegerField("Unit Price") product_size=models.CharField("Product Size",max_length=10) productdetail=models.CharField("Product Detail",max_length=100) product_img=models.FileField() product_type= models.CharField(max_length=15,choices=product_choice, default='stockable') retailer_price=models.PositiveIntegerField() wholeseller_price=models.PositiveIntegerField() location=models.CharField("Locatiion",max_length=30) quantity_onhand=models.CharField("Quantity on Hand",max_length=30) product_status=models.CharField(max_length=15,choices=product_statuss, default='Available' ) -
django admin, how to check model instance belong to owner before deleting?
I tried overwriting def has_delete_permission(self, request, obj=None):, but obj is not passed when deleting a record in Django Admin. Any help would be appreciated! Thank you. -
iframe for Angular application not working, but only on mobile devices
I have an AngularJS application with a Django backend. I inserted an iframe onto another site and the application is working fine on desktop, and also on the Chrome debugger mobile menu. It also works on actual mobile devices when going to the actual Angular app. Its ONLY when I go to the iframe site on an actual mobile device where it doesn't work. It loads the html, but none of the data retrieved from our backend is populating the page like it does on the actual Angular app, and the iframe when on a desktop. Completely at a loss. I know its not my code since it works on all the other versions. Could this be an iframe issue, or perhaps an iOS issue ? -
Django ORM - Translate this self join query to ORM
Please help translate this SQL query to Django ORM query. select l.* from products l inner join products r on l.category = r.category where r.id = %s Please note that category is itself a ForeignKey that points to ProductCategory Model. Also, if possible combine this with this ORM query. Product.objects.prefetch_related('productrecipes', 'farmerprofiles', 'productfeedbacks') Thank you. -
How to pull values from a url and pass them in a text form field in my template page?
I am working on a DJANGO environment. I need to pull some values from a url. For instance : http://x.x.x.x/abc/abcde/?val1=123456&var1=random From the above url I need to pull the values of val1 and var1 and put/pass these values to a textbox field in a form in my HTML template. Later on, I need to pass these values to a Django views.py function. I had initially passed form values to views function using forms.py. I found that method to be better and easier than AJAX. However this time I need to first pull the url values. How can this be done ? I am pretty new in Django so I do not exactly know how to proceed. Thanks in advance -
null value in column "user_id" violates not-null constraint
I am working on a RSVP project based on Django. When I want to make a Event model and connect it with every user, It always has this error!The Event just has two fields: user and eventName. views.py def create_event(request): if request.method=='POST': form = CreateEventForm(data=request.POST) if form.is_valid(): form.save() return redirect('http://vcm-2971.vm.duke.edu:8080/rsvp/profile') else: form= CreateEventForm() args= {'form':form} return render(request, 'rsvp/create_event.html',args) else: form= CreateEventForm() args= {'form':form} return render(request, 'rsvp/create_event.html',args) models.py class Event(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) name = models.CharField(max_length=100,default='') forms.py class CreateEventForm(ModelForm): #name = forms.CharField(max_length=100,required = True) class Meta: model = Event fields=( 'name', ) -
Activate search, button Import and Export to Excel in Django Admin
I have the next code in Admin.py (Code 1), this code activate one search in the AdminDjango. But when I add code 2 and code 3 the search option is hidden I need that show the search option and buttons Import and Export from import_export import resources from import_export.admin import ImportExportModelAdmin from import_export.admin import ImportExportActionModelAdmin from app.models import Parte Code 1 class ParteAdmin(admin.ModelAdmin): list_display=['id','numero','modelo','unidad', 'proyecto','precio','tipo'] search_fields = ['unidad', 'proyecto','numero', 'modelo','tipo'] list_filter = ['tipo','nivel','unidad','proyecto'] code 2 class ParteResource(resources.ModelResource): class Meta: model = Parte code 3 class ParteAdmin(ImportExportModelAdmin): resource_class = ParteResource class ParteAdmin(ImportExportActionModelAdmin): pass admin.site.register(Parte,ParteAdmin) [enter image description here][1] [enter image description here][2] [enter image description here][3] -
Django authentication and cryptography - How does it works?
i’m new to django and I’ve wondered how the authentication system and hashed passwords worked in django? And why is it not possible to know the users password? (Even if i know the algorithm and the salt) In my mind, i see the authentication some what like a python condition: If input == password: authenticated =True (Obviously i know it isn’t coded like that) But I can’t figure out how it is hashed and unhashed, and if there is a way to know what the user password is? -
How to use deleteview for particular user and particular item in Django?
I have these models. Each reply can have none, one or more post. Post is user specific. How to make delete view so that user can only delete his post and not of posts by other on a reply. I tried this many time but my view is deleting post of some other user as well. Means any user can delete post of any other user. I want to make a button next to each post to delete, but button should be seen only to those who have written the post. class Reply(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL) Question = models.ForeignKey(Doubt, on_delete=models.CASCADE) reply = models.TextField(max_length=40000) last_updated = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to = upload_image_path, null = True, blank = True) created_at = models.DateTimeField(auto_now_add=True) def Post(self): return reverse("community:post", kwargs={"pk": self.pk}) class Post(models.Model): post = models.TextField(max_length=4000) reply = models.ForeignKey(Reply, on_delete = models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) time = models.DateTimeField(null=True) User = models.ForeignKey(settings.AUTH_USER_MODEL) -
Django QuerySet Count() Returns NoneType
In views, I have the following snippet: try: count = MembershipPurchaseHistory.objects.filter(user=self.request.user).count() except: count = 0 But somehow I got an error saying count has a NoneType value? How is this possible? -
Elastic Beanstalk Django App REST API Fails with Multiple EC2 Instances
I have a Django Application with the Django REST API framework setup on Elastic Beanstalk. My application works great when there is only 1 EC2 instance running. However when the application scales to more then 1 instance all API request start failing. Requests that don't require authorization fail. So it's not an authentication / token issue. These request also only seem to be failing within my Ionic application (v2+). My Django configuration has CORS_ORIGIN_ALLOW_ALL = True in it and like I said before this only stops working when multiple instances are spun up. The request fail in Ionic with the following message coming back in the Chrome Console. The requests fail in the browser, iOS but not Android. Failed to load https://xxxxxx/api/v1/series/?limit=30&offset=0: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://localhost:8100' is therefore not allowed access. The interesting part is if I make a request using Postman it works fine. So it seems to be something to do with the HTTP Request library in Angular / Ionic. Digging into this further it seems that it is definitely a CORS issue, which must be related to … -
How to fix the Django All-Auth SocialApp matching query Error?
I'm using the Django All-auth login template. My app runs but when I click on the GitHub link I get these errors. The template has: {% get_providers as socialaccount_providers %} so the GitHub login should work, right? What do these errors below mean? DoesNotExist at /accounts/github/login/ SocialApp matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/accounts/github/login/?process=login&next=%2F Django Version: 1.11.10 Exception Type: DoesNotExist DoesNotExist: SocialApp matching query does not exist. [09/Feb/2018 00:37:59] "GET /accounts/github/login/?process=login&next=%2Fhome HTTP/1.1" 500 87171 -
Django - how to get list of inputs, selects dynamically created with javascript?
I have a javascript code to create all combination of product based on characteristics that are added dynamically. HTML eesult of this script is: <table> <tbody> <tr> <td>1</td> <td><select id="combination[0].product" name="combination[0].product"> <option value="25"> product_desc pc.10 </option> <option value="26"> product_desc pc.5 </option> <option value="21"> product_desc </option> </select></td> <td><input readonly="readonly" value="5.00" id="combination[0].price" name="combination[0].price" class="form-control" type="text" /></td> <td><input readonly="readonly" value="a" id="combination[0].color" name="combination[0].color" class="form-control" type="text" /></td> <td><input readonly="readonly" value="1" id="combination[0].quantity" name="combination[0].quantity" class="form-control" type="text" /></td> </tr> <tr> <td>2</td> <td><select id="combination[1].product" name="combination[1].product"> <option value="25"> product_desc pc.10 </option> <option value="26"> product_desc pc.5 </option> <option value="21"> product_desc </option> </select></td> <td><input readonly="readonly" value="5.00" id="combination[1].price" name="combination[1].price" class="form-control" type="text" /></td> <td><input readonly="readonly" value="a" id="combination[1].color" name="combination[1].color" class="form-control" type="text" /></td> <td><input readonly="readonly" value="5" id="combination[1].quantity" name="combination[1].quantity" class="form-control" type="text" /></td> </tr> <tr> <td>5</td> <td><select id="combination[8].product" name="combination[8].product"> <option value="25"> product_desc pc.10 </option> <option value="26"> product_desc pc.5 </option> <option value="21"> product_desc </option> </select></td> <td><input readonly="readonly" value="5.00" id="combination[8].price" name="combination[8].price" class="form-control" type="text" /></td> <td><input readonly="readonly" value="c" id="combination[8].color" name="combination[8].color" class="form-control" type="text" /></td> <td><input readonly="readonly" value="50" id="combination[8].quantity" name="combination[8].quantity" class="form-control" type="text" /></td> </tr> </tbody> </table> Of course there can be many more characteristics (for example type, material...). How can I process it with request.POST? I tried getlist but without success. For the record I use Django 1.9. Is there any way I … -
django-admin, add hyperlink in list_display to other application
under : mydomain/admin, I have several applications App1, app1modle1, app2model2, App2, app2model1, app2model2, App3, app3model1. In App3model1, say for each 'user',I want to add a column in list_display, and the content is a hyperlink to a corresponding model/table in App2, say what does the user sell, one-to-many relation. eg: under app3model1 (the link is mydomain/admin/app3/model1) u1,link u2,link, u3,link. and under app2model2 (the original view, link is mydomain/admin/app2/model2) u1,apple,$5 u1,orange,$10 u2,apple, $10 u3, grape, $5 Once I click the 'link' next to u1 in app3model1, I want to see mydomain/admin/app2/model2/?q=u1 u1,apple,$5 u1,orange,$10 I have tried the following code in App3/admin.py: list_display = ['username', 'link'] def link(self, obj): seller_link = 'admin/app2/model2/?q=' + obj.username return format_html("<a href= %s >link</a>" % seller_link) but it directs me to mydomain/admin/app3/model1/admin/app2/model2...and what I want is mydomain/admin/app2/model2.. with parameters. How can I achieve this? -
Are middlewares an implementation of the Decorator pattern?
In Django, there is the idea of Middleware. It consists of changing the requests and passing it down to the next middleware and so on, and doing the reverse with the responses. Are middlewares implementation of the design pattern Decorator? Are they a particular case of the decorator? What are the differences between them? Also, what is the difference between the implementation of Decorator in Django and the GoF description of it? -
Implementing 404 page in Django, but receiving error
I'm trying to implement 404 page in my django project, and coming across this error. Can anyone help with this? Thanks in advance!! -
Django cart application allowing multiple instances of same product
I have a function in my views file that at the moment lets you either add a product and if the product is added it lets you remove it. What I want to achieve is to add multiple instances of the same product and not do a remove. What is the best way of amending this view to allow this? I have tried removing the else portion but that generates errors. def cart_update(request): product_id = request.POST.get('product_id') if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Show message to user, product is gone?") return redirect("cart:home") cart_obj, new_obj = Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) added = False else: cart_obj.products.add(product_obj) # cart_obj.products.add(product_id) added = True request.session['cart_items'] = cart_obj.products.count() # return redirect(product_obj.get_absolute_url()) if request.is_ajax(): # Asynchronous JavaScript And XML / JSON print("Ajax request") json_data = { "added": added, "removed": not added, } return JsonResponse(json_data) return redirect("cart:home") Thanks in advance. -
ImportError: No module named builtins - Google App Engine Standard - Django - Python 2.7
I'm trying to deploy an application and this error keeps coming up. I am using the commands below in my views/models/form/settings.py, in order to use the same code I did for Python 3. from __future__ import absolute_import, division, print_function from builtins import (bytes, str, open, super, range, zip, round, input, int, pow, object) I've already installed the library:future==0.16.0 on my requirements-vendor.txt On localhost I can run it, using a Conda Env (python 2.7) but the deployment on GAE(standard) I got the 500 Server Error. -
Django Using Multiple Forms in Calculator Program
How do I differentiate the post requests from different buttons in django? For instance, if I want to create a calculator, how do I make it so the POST of the "multiply" button is different from that of the "add" and the "subtract" buttons? EDIT: Here is my views.py: from django.shortcuts import render,get_object_or_404 from django.shortcuts import render_to_response from django.template import RequestContext from django.views.generic import TemplateView from django import forms # Create your views here. # def startPage(request): # return render(request, 'multiplication/detail.html') template_name1 = 'multiplication/detail.html' template_name2 = 'multiplication/multiplied.html' class myForm(forms.Form): quantity1 = forms.IntegerField(required=False) quantity2 = forms.IntegerField(required=False) def multiply_two_integers(x,y): return x*y def my_view(request): if request.method == 'POST': form = myForm(request.POST) if (form.is_valid()): x = form.cleaned_data['quantity1'] y = form.cleaned_data['quantity2'] product = multiply_two_integers(x, y) multiplied = True return render(request, template_name1, {'form': form,'product': product, 'multiplied': multiplied }) else: multiplied = False form = myForm() return render(request,template_name1,{'form': form, 'multiplied': multiplied} ) template_name1: <h1>Multiplication Function</h1> <form action = "{% url 'multiplication:my_view' %}" method = "POST"> {{ form.as_p }} {% csrf_token %} <input type = "submit" value ="Multiply"> <input type = "submit" value ="Add"> <!--<button type="submit"> Multiply </button>--> {% if multiplied %} <h1 style="color:blue; margin-left:75px;"> Answer: {{product}}</h1> {% endif %} </form> -
linux "date" is correct but python tzlocal reports utc in docker container
I am mounting in the docker compose file volumes: - /etc/localtime:/etc/localtime:ro When I go into the container with docker exec -it <containername> bash then run date it shows up properly. But in django and in python3 editor tzlocal shows UTC. ogixbuild$ docker exec -it qlogixwebapi bash root@3e1a15562c2f:/var/lib/django/webapi# date Thu Feb 8 15:14:31 MST 2018 root@3e1a15562c2f:/var/lib/django/webapi# python3 Python 3.6.4 (default, Dec 21 2017, 01:35:12) [GCC 4.9.2] on linux Type "help", "copyright", "credits" or "license" for more information. import tzlocal tzlocal.get_localzone() <StaticTzInfo 'Etc/UTC'> Anyone have any experience with this know how to get tzlocal to get the correct timezone? -
Running asynchronous code synchronously in separate thread
I'm using Django Channels to support websockets and am using their concept of a group to broadcast messages to multiple consumers in the same group. In order to send messages outside of a consumer, you need to call asynchronuous methods in otherwise synchronous code. Unfortunately, this is presenting problems when testing. I began by using loop.run_until_complete: loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.ensure_future(channel_layer.group_send(group_name, {'text': json.dumps(message), 'type': 'receive_group_json'}), loop=loop)) Then the stacktrace read that the thread did not have an event loop: RuntimeError: There is no current event loop in thread 'Thread-1'.. To solve this, I added: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(asyncio.ensure_future(channel_layer.group_send(group_name, {'text': json.dumps(message), 'type': 'receive_group_json'}), loop=loop)) And now the stacktrace is reading the RuntimeError: Event loop is closed, although if I add print statements loop.is_closed() prints False. For context, I'm using Django 2.0, Channels 2, and a redis backend. -
Jinja2 using {{ url() }}
I am trying to figure out how to pass my user_id within my html using {{ url('detail') }} I have tried the following with no success: {{ url('detail') }} {{ url('detail', user_id=User.id) }} {{ url('detail', User.id) }} Here's part of my views and html: views.py urlpatterns = [ path('dashboard/', dashboard), path('user/<int:user_id>/', detail, name='detail'), ] dashboard.html {% for User in all_users %} {{ url('detail') }} {% endfor %} Any help on this would be appreciated, thanks -
How to retrieve a single record using icontains in django
I'm trying to query a single record using the following but I get a 500 error. cdtools = CdTool.objects.get(product=product_record.id, platform=platform_record.id, url__icontains=toolname) models.py class CdTool(models.Model): product = models.ForeignKey(Product) platform = models.ForeignKey(Platform) url = models.CharField(max_length=300) a model instance has an full url, but in my query 'toolname' is the short form (ie: google instead of https://google.com), so I'm trying to figure out what the correct query would be here. I'm open to modifying models.py as long as there is no data migration stuff involved. -
How to create that logger for Django?
URL: / client /[client_id]/ log / operator Method: POST Data: { "access_token": "TOKEN", "limit": 100, "sort": "asc", "start_date": "2018-01-01T00: 00: 00Z" } OR { "access_token": "TOKEN", "limit": 100, "sort": "asc", "offset": "500" } Success Response: { "result": "ok", "logs": [ { "date": "2018-01-01T00: 00: 00Z", "text": "Log entry" }, ... ] } Log entry in the format: "message. User: name the name of the operator." I need to create a request to receive logs of operator activity. Which returns a formatted log of all user actions. I have an activity application in which there is an OperatorLog model. from django.db import models from users.models import User from .constants import ACTIVITY_ACTIONS class OperatorLogManager(models.Manager): """Manager for operator logs""" def active(self): """Mark object as active""" return self.filter(is_delete=False) def get_by_user_id(self, id): return self.active().filter(pk=id) def get_by_client_id(self, client_uid): return self.active().filter(client_uid=client_uid) class OperatorLog(models.Model): """Model for logs""" user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) is_deleted = models.BooleanField(default=False) action_type = models.CharField(max_length=32, сhoices=ACTIVITY_ACTIONS) message = models.TextField(max_length=2048) client_uid = models.CharField(max_length=50) bitrix_id = models.PositiveIntegerField() # Operator Manager objects = OperatorLogManager() def delete(self, **kwargs): self.is_deleted = True self.save() You need a public api (activity / api.py) to register events in other applications, There is also a file with a list of activity types … -
Django How to turn each list in a dictionary into a cloumn?
I have a dictionary with 6 keys and each key's value is a list with 100 elements my_dict = {"Key1":["name1", "name2", ..., "name100"], "Key2":["id1", "id2", ..., "id100"], ... "Key6":["type1", "type2", ..., "type100"]} I am trying to make a table that is 100 x 6, where each column will be a list. I have tried everything in the template and come up short every time. Is there some simple concept I am missing? Should I be manipulating the data in the backend to make it more manageable?