Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot connect to redis://localhost:6379/0: Error 111 connecting to localhost:6379. Connection refused
I've deployed a minimal django/celery/redis project to heroku, and I'm trying to test it in the python shell: heroku run python >>> import tasks >>> tasks.add.delay(1, 2) The problem is tasks.add.delay(1,2) doesn't produce any output, it just hangs there whereas in local it gave an Async message. Also when i try to see the task running in application logs with "heroku logs -t -p worker" it gives me this error: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379/0: Error 111 connecting to localhost:6379. Connection refused.. -
I deployed the django website "rpa-berater.de". On localhost it works fine but on linux server with apache2 it is very slow
Does somebody have hints to optimize the Speed of the Website "rpa-berater.de". many thanks -
How can we Display and store a binary search tree in Django
I have written the program for Binary Search Tree but does not know how can i save it in the Django Database. How can i store it in the models: from __future__ import print_function class Node: # Constructor to initialize data # If data is not given by user,its taken as None def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right # __str__ returns string equivalent of Object def __str__(self): return "Node[Data = %s]" % (self.data,) class BinarySearchTree: def __init__(self): self.root = None While inserting values in a binary search tree, we first check whether the value is greater than, lesser than or equal to the root of the tree. We initialize current node as the root. If the value is greater than the current node value, then we know that its right location will be in the right subtree. So we make the current element as the right node. If the value is lesser than the current node value, then we know that its right location will be in the left subtree. So we make the current element as the left node. If the value is equal to the current node value, then we … -
Issue with Jquery Datepicker in Django app
I am new to django and trying to build my first booking app. I have working forms for reservation but having trouble in implementing the query form to retrieve the booking results based on date. I am using Jquery date picker and using POST method to fetch the booking info (following is the code). I am not able to pass date from jquery date picker to views, when I print request.POST I only get None response. I have been looking over for solution but couldn’t get through. Kindly suggest the workaround. Thanks in advance. HTML CODE: <head> <meta charset="utf-8" /> <title>Form</title> <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css"> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script> <script> $(document).ready(function() { $('#datepicker').datepicker(); }); </script> </head> <body> <form action="" method="post">{% csrf_token %} <!--{{ form.date }} --> <p>Date: <input type="text" id="datepicker"></p> <!-- The rest of my form --> <input type="submit" value="submit" /> </form> {% for rom in qdate%} {{rom.room}} {{rom.Purpose}} {{rom.start_time}} {{rom.end_time}} </br> {%endfor%} {% else %} Forms: My forms.py code to show Jquery datepicker widget and pass the date input from functools import partial DateInput = partial(forms.DateInput, {'class': 'datepicker'}) # import django_filters class DateFilter(forms.Form): date_input = forms.DateField(input_formats=['%m/%d/%Y',], required=False, widget=forms.DateInput(format = '%m/%d/%Y')) Views: My view.py code to dynamically query and show the … -
I have a problem with python Django 'Login' has no attribute 'filter'
I made a website with python Django. My models are two which called 'Login' and 'Ch'. And my website has 'signup' and 'home' page. The 'signup' page is literally signup page. User can register his/her ID and password. Then these information save in 'id' and 'pw' in the 'Login' model. Now, Typing his/her ID and password, user can login through 'home' page. This is my plan. However, the login process consistently happen problem with the sentence 'Login' has no attribute 'filter'. My partial code is log = Login.objects.all() try: ch = log.filter(id = request.POST["login_id"], pw = ghv(request.POST["login_pw"])) #ghv is user definition function for get hash value of password if (ch): id = request.POST["login_id"] return render(request,'pdg/home2.html') else: return render(request, "pdg/home_e.html") except ObjectDoesNotExist: return render(request, "pdg/home_e.html") Signup process has no problem. I think that after signup process complete, Being added the user data in 'Login' model is cause the problem. Because restarting the runserver is effective for solving this error. However I want to find a solution for this error without restarting the runserver. Please help me.. And THANK YOU. -
Method or something to run a complex query in a model
I would display some fields from a remote table according a common field (emails) between my models. I resume: My Django project displays a main table Prospect, related to another table Email (ForeignKey). Stored in my default Django DB (Postgres). Then I can display in another app a remote table from a third emailing tool, stored in a MySQL database, thanks to Django databases router system. All this coexists very well in my Django admin. Now I would display in my Prospect admin forms some fields from my remote table, in read only of course. In SQL/PHP, simplifying, I would do something like that: SELECT myfield FROM MyRemoteTable WHERE email = {EmailValue} But where and how can I do that with Django? I think to a special method in my Email model, but... not easy! THX -
How to retrieve data from database with autocomplete (Django)
I need to get data from database and put it on input field but I can't do it. This is my code. template.html <script type="text/javascript"> $(function () { $("#tags").autocomplete({ source: "/autocomplete/", minLength: 2, }); }); </script> <div class="ui-widget"> <input id="tags"> </div> urls.py path('autocomplete', views.autocomplete, name='autocomplete'), views.py def autocomplete(self, request, *args, **kwargs): data = request.GET product = data.get("term") if product: products = Product.objects.filter(product_name__icontains=product) else: products = Product.objects.all() results = [] for pd in products: pd_json = {} pd_json['id'] = pd.id pd_json['label'] = pd.product_name pd_json['value'] = pd.product_name results.append(pd_json) data = json.dumps(results) mimetype = 'application/json' return HttpResponse(data, mimetype) models.py class Product(models.Model): product_name = models.CharField(max_length=255) def __str__(self): return self.product_name Or maybe because I didn't import something? (such as something about 'json') -
Django modules to prevent scraping
Could you please recommend existing django applications(modules) intended to prevent scraping(crawling) of website? I have found this: https://github.com/litchfield/django-sentinel (but it seems too old) and https://djangopackages.org/grids/g/anti-spam/ (it's more about antispam) I am seeking for application that is able to analyze user behavior and block web-scrapers. -
Why does django Unittest throw an assertion error when comparing two instances of numpy.float64?
I'm writing some unit tests, one of which checks that the data provided in a dataframe is of the correct type (float). When I run the test assertIsInstance(type(foo), np.float64) the test fails with the following error message: AssertionError <class numpy.float64> is not an instance of <class numpy.float64> I would have expected this to pass. test_dataframe_functions.py import numpy as np from django.test import TestCase import pandas as pd from myapp import dataframe_functions class DataframeFunctionsTest(TestCase): dataframe_to_test = dataframe_functions.create_dataframe #passes def test_dataframe_is_definitely_a_dataframe(self): self.assertIsInstance(self.dataframe_to_test, pd.DataFrame) #passes def test_dataframe_has_the_right_columns(self): column_headers = list(self.dataframe_to_test.columns) self.assertEquals(column_headers, ['header1', 'header2', 'header3']) #fails with AssertionError <class numpy.float64> is not an instance of <class numpy.float64> def test_dataframe_header1_is_correct_format(self): data_instance = self.dataframe_to_test['header1'].iloc[1] self.assertIsInstance(type(data_instance), np.float64) I've checked that type(data_instance) does equal "class numpy.float64" with the following line of code: print(type(dataframe_to_test['header1'].iloc[1])) -
Python doesn't recognise Django app folder
I am new to Django and was following the tutorial here (https://simpleisbetterthancomplex.com/series/2017/09/04/a-complete-beginners-guide-to-django-part-1.html#hello-world) to get my first application running. I could not reference my application so I decided to name everything exactly as is in the tutorial in another Python project. I am unable to import view from boards no matter what I do (change it to projectname.appname and a number of different variations that I found on here). I have tried this tutorial on another computer I do not have access to at the moment and can confirm that it works usually. Is this an issue with PyCharm/my Python environment? Project Structure Error I am receiving -
from celery import Celery ModuleNotFoundError: No module named 'celery'
I've managed to get Django/celery/redis running on my local. I've then pushed this to heroku and am trying to run it there. However when i try to run my tasks.py file in python, it gives me the error: from celery import Celery ModuleNotFoundError: No module named 'celery' I've tried installing celery and redis on heroku using the "heroku run" command. But it does not seem to recognise this. Here is my tasks.py file: from celery import Celery app = Celery('tasks', broker='redis://localhost:6379/0') @app.task def add(x, y): return x + y -
How to display values that are less than a particular number in Django
I have created a model named Product containing these fields ('prod_name', 'company', 'quantity', 'price', 'units', 'prod_type') I want to display those products in the webpage that have less than 2 units remaining I tried using Model.Objects.filter(units__lte=2) but I am not getting the desired output Here is my views.py file: from django.shortcuts import render, redirect, get_object_or_404 from django.views.generic import TemplateView, ListView from django.db.models import Q from .models import * from .forms import * def get_stock(request): items=Product.objects.filter(units__lte=2) context={ 'items':items } return render(request, 'UpdateStock.html', context) here is my urls file: from django.conf.urls import url from django.urls import path from .views import * urlpatterns=[ url(r'^get_stock$', get_stock, name='get_stock'), ] here is my HTML file for the same {% extends 'base.html' %} {% block body %} <br> <h3>Update Stocks</h3> <br> <table class="table table-hover"> <thead> <tr> <th>Sr. No.</th> <th>Product Name</th> <th>Company</th> <th>Quantity</th> <th>Price</th> <th>Units</th> <th>Product Type</th> </tr> </thead> <tbody> {% for item in object_list %} <tr> <td>{{item.pk}}</td> <td>{{item.prod_name}}</td> <td>{{item.company}}</td> <td>{{item.quantity}}</td> <td>{{item.price}}</td> <td>{{item.units}}</td> <td>{{item.prod_type}}</td> </tr> {% endfor %} </tbody> </table> {% endblock %} But the results are not getting displayed -
Django (REST Framework) Returns Empty List Every Other Call
I have a simple function that generates a random sample list of items from the outer dictionary. def get_random_product_feed_for(mid, n=DEFAULT_AMOUNT_ITEMS_RETURNED): assert mid is not None, 'Merchant ID cannot be null while retrieving products feed' n = min(n, MAX_FEED_ITEMS_RETURNED) if mid in ADVERTISERS_PRODUCT_FEEDS: # check if merchant is present in the outer dict feeds = ADVERTISERS_PRODUCT_FEEDS[mid] # retrieve merchant's items # Sample list if len(feeds) >= n: random_feeds = random.sample(feeds, n) else: random_feeds = feeds return random_feeds return [] Where ADVERTISERS_PRODUCT_FEEDS = defaultdict(list). However, when I use this function in REST Framework API call, it returns empty list half the time; every other call. I don't think, however, the problem is in views or serializers. The setup is a little bit more complex than this. ADVERTISERS_PRODUCT_FEEDS is fetched asynchronously, because it is processed from large files that need to be downloaded. threads = [] # to keep only one active thread for the process def fetch_products_feed(): for thr in threads: if not thr.is_alive(): threads.remove(thr) if len(threads) > 0: logging.warning( 'Attempted to create multiple threads for product feeds fetching process. ' 'Wait until it is done!' ) return thread = threading.Thread(target=fetch_products_feed_sync, name='Fetch-Products-Thread') threads.append(thread) thread.start() So far I can only assume that fetch_products_feed_sync … -
NoReverseMatch at /friend/add_friend_link/PHByb3BlcnR5IG9iamVjdCBhdCAweDdmY2RlMTkwZjI3OD4/
No reverse match error: my urls.py : urlpatterns = [ url(r'^add_friend_link/(?P<uidb64>[0-9A-Za-z_\-]+)/$', add_friend_link, name='add_friend_link'), re_path(r'^accept_friend_request(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<status>[\w-]+)/$', accept_friend_request, name = 'accept_friend_request'), ] my view.py : def add_friend_link(request, uidb64): """Adding a link in email which is sent to friend through which one can accept or reject friend request""" status = "Pending" try: uid = urlsafe_base64_decode(uidb64).decode() # print(uid) user = User.objects.get(pk=uid) # print(user) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None return render(request, 'users/accept_friend.html', {"uidb64": uid, 'user':user}) This view will send email to friend for requesting in hyperlink: def accept_friend_request(request, uidb64, status): """Accept button will lead to entry in database as accepted and reject button will lead to entry in database as rejected based on status flag""" uid= urlsafe_base64_decode(uidb64).decode() status = 'Pending' friend_user = User.objects.get(id=Friend.to_user.id) print(friend_user) f = Friend.objects.filter(friend_id = friend_user) if f: f.status=status f.save() return request, "users/friend_list.html", {"uidb64": uid, "status": status} else: return render(request, 'blog/base.html') This view will be redirected to a template which has 2 buttons: Accept and reject and based on that it will be redirected to next page. my template.html: <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Confirm Friend Request</legend> <h5>Are you sure you want to confirm the friend request of {{ user.id }}</h5> <div class="form-group"> <a class="btn … -
How can I perform this join in django?
I have the following two models in django that represent a post and the post's likes: class Post(models.Model): title = CharField(max_length=200) content = TextField() num_comments = PositiveIntegerField(default=0) class Like(models.Model): LIKE_CHOICES = [('L', 'Like'), ('D', 'Dislike')] user = ForeignKey(User, on_delete=models.CASCADE) post = ForeignKey(Post, on_delete=models.CASCADE) state = CharField(default='L', max_length=1, choices=LIKE_CHOICES) created_at = DateTimeField(auto_now_add=True) updated_at = DateTimeField(auto_now=True) How can I perform a join in my view that would get all the posts and then perform a join to get the like state of the user sending sending the request for each of the posts (None if user hasn't liked or disliked)? The only way I can think to maybe do this would be to use select_related() but I don't know how I would use it in my case since Post doesn't have a reference to Like. -
AttributeError: module 'random' has no attribute 'choise' Django
so i'm kinda new to this world of programming and I took the Udemy course called Python and Django Full Stack Web Developer. Now i'm on the last part where we are using Django. I watched the video and followed his code and tried to run it bymyself. But then I encountered by this error. I looked after a solution online and in here also, but I saw solution that offer to check if there is another function or module with the same name by mistake or something, and I have not.. this is my code: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') import django django.setup() import random from first_app.models import AccessRecord, Webpage, Topic from faker import Faker fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choise(topics))[0] t.save() return t def populate(N=5): for entry in range(N): top = add_topic() fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() webpg.objects.get_or_create(topic=top, url=fake_url, name=fake_name)[0] acc_rec = AccessRecord.objects.get_or_create(name=webpg, date=fake_date)[0] if __name__ == '__main__': print("populating script!") populate(20) print("populating complete!") and I refer to the models.py code also: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') import django django.setup() import random from first_app.models import AccessRecord, Webpage, Topic from faker import Faker fakegen = Faker() topics = ['Search', … -
Complex M2M filtering using Django's ORM
I have the following models: class Sauce(models.Model): ... class Topping(models.Model): ... class Pizza(models.Model): sauces = models.ManyToManyField(Sauce, related_name='pizzas') toppings = models.ManyToManyField(Topping, related_name='pizzas') Now, lets say I want to query all the pizzas given a list of toppings and sauces. For example: sauces_ids = [1, 2] toppings_ids = [1, 2] What I am doing right now in my API view is as follows: pizzas = Pizza.objects.filter(restaurant=restaurant) if request.data.get('sauces_ids', []): pizzas = pizzas.filter( sauces__in= request.data['sauces_ids'] ) if request.data.get('toppings_ids', []): pizzas = pizzas.filter( toppings__in= request.data['toppings_ids'] ) return pizzas.distinct() There was a duplication problem which I solved using the distinct() function. However, now I am facing a different issue. I have 2 pizzas in my database: Pizza 1 with sauces = [1, 2], toppings = [1, 2] Pizza 2 with sauces = [1, 2], toppings = [1] With my above query parameters, I would like to return only Pizza 1 as the 2 M2M lists match exactly. However, the query I wrote is returning both the pizzas. How do I solve this? Thanks for any help. Moreover, is this an efficient way to do this? -
How to fix this TemplateSyntaxError at error in django
I get this error TemplateSyntaxError at / add requires 2 arguments, 1 provided Screenshot: ERROR SCREENSHOT I want to add pagination there but i get this error again and again Here is my html file <div class="pagination"> {% if buy_list.has_previous %} <li class="page-item"><a class="page-link" href="?page=1"></a></li> <li class="page-item"><a class="page-link" href="?page={{ buy_list.previous_page_number }}"></a></li> {% endif %} {% for num in buy_list.paginator.page_range %} {% if buy_list.number == num %} <strong>{{ num }}</strong> {% elif num > buy_list.number|add: '-3' and num < buy_list.number|add: '3' %} {{num}} {% endif %} {% endfor %} {% if buy_list.has_next %} <li class="page-item"><a class="page-link" href="?page={{ buy_list.next_page_number }}"></a></li> <li class="page-item"><a class="page-link" href="?page={{ buy_list.paginator.num_pages }}"></a></li> {% endif %} Thanks -
Uploading cropped picture fails with cropper.js and Django 2.2.7
I am trying to make a form that views users profile and displays a picture of a user. I have made a custom user class and added new field with profile picture (avatar). Idea is that when user is looking at the profile he can click on his picture and modal form pops up with displayed current picture (or default picture that looks like anonymous user). Then the user can click on upload new picture of any size and crop it using cropper.js to a standard format being set at 220 x 300 pixels. To develop this I took couple of examples on the Internet and made a mix of them. It works flawlessly until I wish to save the new picture in user database, this is just ignored with no error displayed whatsoever. Of course, when I do this from Admin interface and upload a picture it works every time. So, the part when I wish to save picture is triggered from modal form and it is part written in javascript to take data from cropper.js: $(".js-crop-and-upload").click(function () { var cropData = $image.cropper("getData"); $("#id_x").val(cropData["x"]); $("#id_y").val(cropData["y"]); $("#id_height").val(cropData["height"]); $("#id_width").val(cropData["width"]); $("#formUpload").submit(); console.log("BIO C&U"); $("#modalCrop").modal("hide") }); I have made a new save function … -
Unhandled exception in thread started by <function wrapper at 0x7f18aef9a758> Traceback (most recent call last):
Unhandled exception in thread started by Traceback (most recent call last): File "/var/www/html/patient_share/myenv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/var/www/html/patient_share/myenv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run autoreload.raise_last_exception() File "/var/www/html/patient_share/myenv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/var/www/html/patient_share/myenv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/var/www/html/patient_share/myenv/local/lib/python2.7/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/html/patient_share/myenv/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/var/www/html/patient_share/myenv/local/lib/python2.7/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) ImportError: No module named rest_framework -
How to Create a plugin based website to manage the access control and feature access for client?
I am working on a product that was very simpler in its initial phase but as the product is growing we are continuously working on new functionality and we are releasing 2-3 minor/major functionality every month. So working with access control and feature with access with the same huge codebase is going harder every day, and it is also affecting product stability. So we are thinking about the plugging based website like our current project will be the core app new feature we will be created as a plugin and based on the client feature access we will plug/unplug on our core app. Can someone help me a bit of design its architecture? Please share a link if anyone has a blog or other stuff. Technology We are using: Django React ES & Redis for search and caching respectively Please help me. Thanks in Advance. -
Read a csv file and fill in database with it's data in django application
in my Django application, i created a form which permit user to upload csv file. What i want is when user upload the csv file, the contained data is read and database is filled in with them. It works but not correctly. data are saved as tuples. Here's my code forms.py class SupplierCSVForm(forms.ModelForm): class Meta: model = SuplierCsv fields = '__all__' exclude = ('slug',) views.py @login_required def l_supplier(request): suppliers_list = Supplier.objects.all() paginator = Paginator(suppliers_list, 3, 2) page = request.GET.get('page') suppliers = paginator.get_page(page) # Supplier csv form if request.method == 'POST': form = SupplierCSVForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['csvfile'] with open('f.csv', 'wb') as destination: for chunk in uploaded_file.chunks(): destination.write(chunk) destination.close() #csvfile = io.TextIOWrapper(open('f.csv', 'rb')) with open('f.csv', 'r') as the_source: source_reader = csv.reader(sthe_source) next(source_reader) for Name, Email, Contact, City, Website, Activity, Cc, slug in source_reader: new_supplier = Supplier() new_supplier.name=Name, new_supplier.email=Email, new_supplier.contact=Contact, new_supplier.city=City, new_supplier.website=Website, new_supplier.activity=Activity, new_supplier.cc=Cc, new_supplier.slug=slug, new_supplier.save() return redirect('good:l_good') else: form = SupplierCSVForm() context = { 'suppliers': suppliers, 'form': form, } return render(request, 'supplier/l_supplier.html', context) -
Remain logged in even if user closes tab and reopens it (not browser close) - using Django and Pyrebase
I was wondering if there is a way to let the user remain logged in without having to sign in again if a user decides to close current tab and reopen it again. I am using Django and Python and here is the code I am using for signing in: def postsign(request): email = request.POST.get('email') passw = request.POST.get("password") try: user = auth.sign_in_with_email_and_password(email,passw) success = 1 except: success = 0 message = "invalid cerediantials" return render(request,"dashboard.html") session_id = user['idToken'] request.session['uid'] = str(session_id) context = { "success": success, "email": email, } return render(request, "dashboard.html", context) -
TypeError at /friend/accept_friend_requestPHByb3BlcnR5IG9iamVjdCBhdCAweDdmNTlhZTEzODI3OD4/status/
Error in the line as below: int() argument must be a string, a bytes-like object or a number, not 'ForwardManyToOneDescriptor' friend_user = User.objects.get(pk=Friend.to_user.id) -
How to create a new manytomany object and save it to a model in one view
I have a model repairOrders with 2 manytomany fields: class RepairOrder(models.Model): >>> labor = models.ManyToManyField(Labor) parts = models.ManyToManyField(Parts) I have the repairOrder displayed and have a button to create a new labor object by using the Labor modelForm. what I want to happen is after I create that obj I want it added to the manytomany field of the RepairOrder. how do I define that in the view? this is what I have now: def repairOrder_detail(request, pk): if request.method == "POST": form = laborForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('repairOrder_detail', pk=pk) else: repairs = get_object_or_404(RepairOrder, pk=pk) form = repairOrderForm() labor = laborForm() return render(request, 'repairOrders/repairOrder_detail.html', {'repairs': repairs, 'form': form, 'labor': labor}) Right now I can create as many labor obj as I want but they are not added to the repairOrder model. I don't know what I need to call to save the labor instance to the repairOrder.labor field. I would like for this all to happen in one step for the end user.