Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Selenium Django/Python error:Unable to find a matching set of capabilities
Running this Django tests on chat app that has uses selenium tests.py from channels.testing import ChannelsLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.wait import WebDriverWait import os print(os.environ['PATH']) class ChatTests(ChannelsLiveServerTestCase): serve_static = True # emulate StaticLiveServerTestCase @classmethod def setUpClass(cls): super().setUpClass() try: # NOTE: Requires "chromedriver" binary to be installed in $PATH cls.driver = webdriver.Firefox() except: super().tearDownClass() raise ... when I run the test I get this error (chatenv) muiruri_samuel@train:~/webapp/chatsys$ python manage.py test chat.tests /home/muiruri_samuel/webapp/chatenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games: /usr/local/games:/snap/bin Creating test database for alias 'default'... System check identified no issues (0 silenced). E ====================================================================== ERROR: setUpClass (chat.tests.ChatTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/muiruri_samuel/webapp/chatsys/chat/tests.py", line 17, in setUpClass cls.driver = webdriver.Firefox() File "/home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py" , line 170, in __init__ keep_alive=True) File "/home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 156, in __init__ self.start_session(capabilities, browser_profile) File "/home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 245, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 314, in execute self.error_handler.check_response(response) File "/home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.SessionNotCreatedException: Message: Unable to find a matching set of capabilities ---------------------------------------------------------------------- Ran 0 tests in 1.012s FAILED (errors=1) Destroying test database for alias 'default'... The results suggests that firefox isn't configured correctly. This is also running on a ubuntu vm server also. I've checked to see … -
How to edit the ctime of Django?
In my Order model: class Order(models.Model): order_num = models.CharField(max_length=128, unique=True) ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) I have ctime you see. But in my Order's update APIView: class OrderUpdateAPIView(UpdateAPIView): serializer_class = OrderSerializer permission_classes = [IsSuperAdminOrFinanceAdmin] queryset = Order.objects.all() lookup_field = "order_num" I can not edit the Order's ctime although the API return success. -
os.stat in python 3.6 on windows is throwing error
def index(request,cdate=None,desc=None): l=[] save_path = settings.MEDIA_ROOT print(type(save_path)) for i in os.listdir(save_path): l.append(i) stat = os.stat(l) birth_time = stat.st_birthtime() return render(request,'a_app/index3.html',{'dirs':l,'cdate':cdate,'desc':desc}) I am getting the error "stat: path should be string, bytes, os.PathLike or integer, not list" at the below command stat = os.stat(l) I am not able to understand why this error is coming. -
Django: Url routing to the wrong file, but correct location: TemplateDoesNotExist Error
I am trying to display a file named visit-form.html, but for some reason Django keeps looking for a file named visit_form.html (the difference being the underscore). Therefore, I keep getting the TemplateDoesNotExist error. I've tried clearing the browser cache, invalidating the Pycharm cache (File>invalidate caches). I have searched throughout the entire program for a visit_form.html file or code, but none can be found (I found one in an old file path and deleted the file with no change). The error is as follows, and the first Url is in the correct file location, but the problem seems to be the filename I can't get rid of. TemplateDoesNotExist at /clincher/visit/add/2 clincher/visit_form.html Request Method: GET Request URL: http://127.0.0.1:8000/clincher/visit/add/2 Django Version: 2.0.4 Exception Type: TemplateDoesNotExist Exception Value: clincher/visit_form.html Exception Location: /Users/nrsmoll/venv/lib/python3.6/site-packages/django/template/loader.py in select_template, line 47 Python Executable: /Users/nrsmoll/venv/bin/python Python Version: 3.6.4 Python Path: ['/Users/nrsmoll/PycharmProjects/clincher', '/Users/nrsmoll/PycharmProjects/clincher', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Users/nrsmoll/venv/lib/python3.6/site-packages', '/Users/nrsmoll/venv/lib/python3.6/site-packages/setuptools-28.8.0-py3.6.egg', '/Users/nrsmoll/venv/lib/python3.6/site-packages/pip-9.0.1-py3.6.egg', '/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend'] Server time: Wed, 6 Jun 2018 09:20:19 +0000` and then: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /Users/nrsmoll/PycharmProjects/clincher/templates/clincher/visit_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/nrsmoll/PycharmProjects/clincher/clincher/templates/clincher/visit_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/nrsmoll/venv/lib/python3.6/site- packages/django/contrib/admin/templates/clincher/visit_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/nrsmoll/venv/lib/python3.6/site- packages/django/contrib/auth/templates/clincher/visit_form.html (Source does not exist) Urls.py urlpatterns … -
django restframe work Direct assignment to the forward side of a many-to-many set is prohibited
I have a Recipe and Ingredient class where i have a m2m placed on the ingredient model. I tested out the model in the admin panel and was working fine. However when i tried creating them in the shell i got an error(see the error below). class Ingredient(models.Model): name = models.CharField(max_length=50) amount = models.IntegerField(default=1) ingredients = models.ManyToManyField(Recipe, related_name='ingredients') class IngredientSerializer(ModelSerializer): class Meta: fields = ['name', 'amount'] model = Ingredient class RecipeSerializer(ModelSerializer): ingredients = IngredientSerializer(many=True) owner = ReadOnlyField(source='owner.username') class Meta: fields = ['owner', 'name', 'description', 'image', 'ingredients'] model = Recipe class Recipe(models.Model): owner = models.ForeignKey('auth.User', related_name='recipes', on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.TextField(max_length=200, blank=True) image = models.CharField(max_length=100, blank=True) Shell Command beefsoup = Recipe.objects.create(owner=user, name="beef", description="goot", image="httplo") tomatoes = Ingredient.objects.create(ingredients.set(beefsoup) ,name='tomatoes', amount=2) Error TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use ingredients.set() instead. -
Django Filter only getting the last item
I made the below code where I want to filter with selected id's from checkbox values where the variable is "item" and I also wants to get columns where the variable is "pfast_type". The issue is that I am only getting the last item.I am not getting the whole list.Where am I doing wrong ? elif pfast_type and item: object_list = FP.objects.filter(pk__in=[item]).values('FP_Item',pfast_type) -
How to document response schema for Django REST Framework documentaion?
I'm documenting a custom endpoint using default DRF documentation API. The output of the endpoint is quite complex and I need a pretty way to display it to the frontend-developers in documentation API. Current solution is to use method's docstring which is not that pretty. There is a clean way to describe input parameters using schema, but I'm unable to find examples to describe schema for the output. There is screenshot in the official documentation that indicates that it is possible (note a response schema at the picture), but unfortunately no example. -
Django - Javascript does not load
I have seen so many questions and answers on this but nothing is working. I have a base.html which looks like so: {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello Django</title> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" href="{% static "css/style.css" %}"> <link rel="stylesheet" href="{% static "css/style2.css" %}"> <script src="{% static 'js/jquery.1.12.4.min.js' %}"></script> <script type="text/javascript" src="{% static "js/main.js" %}"></script> <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> {% block js %}{% endblock %} </head> <body> {% block content %}{% endblock content %} </body> </html> I then have a template which looks like so: {% extends "base.html" %} {% block javascript %} <script> alert("hello"); </script> {% endblock %} {% block content %} In both cases, 1) The JavaScript file main.js is not loaded in. If I look at the DOM, the JavaScript file is not there. If I add in another CSS file, that works fine. Its just JavaScript. 2) The JavaScript in the block in the template doesn't run either. -
Problems with UpdateView
I have a url defined as: url(r'expand/(?P<pk>[0-9]+)/$', ExpandData.as_view(), name='expand'), Which is based on an UpdateView: class ExpandData(SuccessMessageMixin, UpdateView): But this gives me the following error: Reverse for 'expand' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['app/expand/(?P<pk>[0-9]+)/$'] This happens when loading the application at the root url. I have no calls to reverse('expand') in my code. Why is this happening. What is the workaround? -
django custom user model gives me lazy reference error
My code is as shown below: models/user.py from __future__ import unicode_literals from django.db import models from django.utils import timezone from django.contrib.auth.models import ( AbstractBaseUser, PermissionsMixin,BaseUserManager ) class UserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email,and password. """ if not email: raise ValueError('The given email must be set') try: with transaction.atomic(): user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user except: raise def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self._create_user(email, password=password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): """ An abstract base class implementing a fully featured User model with admin-compliant permissions. """ email = models.EmailField(max_length=40, unique=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def save(self, *args, **kwargs): super(User, self).save(*args, **kwargs) return self models/init.py from user import User settings.py 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', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'django.middleware.clickjacking.XFrameOptionsMiddleware' ] AUTH_USER_MODEL = 'dashboard.User' After this when I run python manage.py migrate, it gives me the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File … -
Can we use django orm to get a output like shown below
[ {'month_number':[1,2,3,4,5]}, {'month_number_2':[6,6,8,8,8,10]} ] class Test(Modelbase): student_id = models.IntegerField(null=True) Above is the model and created_at is a default field to get the month_number. I have used the below query to filter data, but using this we will have to loop again to differentiate for different month. Model.objects.filter(created_at__month__gte=3).values(*['student_id','created_at']) Can we do this using Django ORM in a single go? -
Can't open gunicorn log
The current directory is with manage.py. This command previously worked fine: gunicorn --log-file=- myapp.wsgi:application However now when I execute it, it freezes after I load my s3 bucket: (env) james@postr:~/postr$ gunicorn --log-file=- draft1.wsgi:application [2018-06-06 09:14:32 +0000] [19585] [INFO] Starting gunicorn 19.7.1 [2018-06-06 09:14:32 +0000] [19585] [INFO] Listening at: http://127.0.0.1:8000 (19585) [2018-06-06 09:14:32 +0000] [19585] [INFO] Using worker: sync [2018-06-06 09:14:32 +0000] [19588] [INFO] Booting worker with pid: 19588 BEGIN REQUEST++++++++++++++++++++++++++++++++++++ Request URL = https://ec2.amazonaws.com?Action=DescribeRegions&Version=2013-10-15 RESPONSE++++++++++++++++++++++++++++++++++++ Response code: 200 <?xml version="1.0" encoding="UTF-8"?> <DescribeRegionsResponse xmlns="http://ec2.amazonaws.com/doc/2013-10-15/"> <requestId>63c5zfc8-5aa8-4eaa-m88e-3080cb8x7e81</requestId> <regionInfo> <item> <regionName>ap-south-1</regionName> <regionEndpoint>ec2.ap-south-1.amazonaws.com</regionEndpoint> </item> <item> <regionName>eu-west-3</regionName> <regionEndpoint>ec2.eu-west-3.amazonaws.com</regionEndpoint> </item> <item> <regionName>us-west-1</regionName> <regionEndpoint>ec2.us-west-1.amazonaws.com</regionEndpoint> </item> <item> <regionName>us-west-2</regionName> <regionEndpoint>ec2.us-west-2.amazonaws.com</regionEndpoint> </item> </regionInfo> </DescribeRegionsResponse> It just stops there^ Any idea what the problem is? PS: This is my live, remote server (django) via digitalocean. -
Django email log file "sent" growing
I have a sent file that keeps growing on my staging server. It stores a log of all emails sent and I don't know what's causing this behaviour, it doesn't look like a feature from the Django framework (1.8). I can't find any reference of this log file in the source code. It's an issue for several reasons, including the fact that it causes the server to run out of disk space. Maybe I'm missing something obvious in the Django config. I don't see how to fix this issue besides running a cron task to delete that file regularly. I'm open to better ideas. -
Set INITIAL_FORMS value in code
I got an UpdateView method and I want to set the formset-INITIAL_FORMS value to the .count() of children of the main form. While I can easily get the number of the children, when I try to set the value of formset-INITIAL_FORMS overriding get_form_kwargs() method, I get an error message saying 'This QueryDict instance is immutable'. def get_form_kwargs(self): kwargs = super(RandomUpdateView, self).get_form_kwargs() value = ..... kwargs['data'].update({'id_formset-INITIAL_FORMS': value}) return kwargs -
Why oauth is done on the server side
I'm implementing oauth using python social auth, on a django web app. I've searched through many examples and implementations, and found every one of them does oauth in the server side. (even examples used in the official document) So for example, when a client tries to fetch data from their google drive, since authorization token is stored in the server side, the content is downloaded to the server and then forwarded to the client. A diagram for the above example is drawn below: Client Server Google 1. oauth --(provide id/pw)--> --(request oauth)--> <--(send auth token)- <--(grant access)-- 2. file download --(select file)--> -(auth token+request file)--> <--(file content)-- <--(forward file)-- However for me, it feels more right that the authorization process is done in the client side. Because first of all, by letting client download directly from google, great amount of server<-->google traffic can be reduced. And second, the server does not store auth token, so better safety for client. So here are my questions: Is this a widely accepted oauth flow? If it is, what is the reason? Is there a good oauth template that uses django and google drive? Thank you! -
Is it possible to use build-in template tags and filters inside flatpage.content?
I am little bit confused with flatpages application of Django. QUESTION: Is it possible to use build-in template tags and filters inside flatpage.content? Let me try to explain it with example. Lets say I have home and license pages. Inside home page I have dynamic content at the top (slides=Slide.objects.all()), all other part of page is static content. license page has only static content. How in this case to send queryset object to flatpage.content in home page? html: # Dynamic content {% for slide in slides %} {{ slide }} {% endfor %} # Static content {{ flatpage.content }} -
Image Doesn't display in django from sqlite db
i am creating website which have several images, but none is displayed, i have tried several ways to solve it but no changes image's URL is saved in sqlite db views.py def add_story(request): if request.method == "POST": form = StoryCreate(request.POST, request.FILES) if form.is_valid(): storyitem = form.save(commit=False) storyitem.save() else: form = StoryCreate() return render(request, 'story_form.html', {'form':form}) urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root= settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(SITE_ROOT, 'statics') MEDIA_URL = '/media/' html <img name="Story" style="height: 100px; width: 100px" src="{{item.LogoUrl.url}}"/> -
How to combine the dictionaries in python
I have 2 dictionaries dict1 = {'color': {'attri': ['Black']}, 'diameter': {'attri': ['(300, 600)']}} dict2 = {'size': {'op':'in'}, 'diameter': {'op':'range'}, 'color': {'op':'in'}} I want to combine the 2 dictionaries such that dict3 = {'color': {'op': 'in', 'attri': ['Black']}, 'diameter': {'op': 'range', 'attri': ['(300,600)']}} -
Virtualenv 'activate' is not recognized as an internal or external command
I am working on a django app where i use virtualenv everything has been fine until one point where i wanted to activate the virtualenv i get this error 'activate' is not recognized as an internal or external command,operable program or batch file. I have been activating and developing on the app and i do not know what has happen to this and there is no activate.bat file in Scripts. Path C:\venv\blog\Scripts\activate -
BOOTSTRAP // not working despite adding cdn links and reference style link // PYTHON
I'm currently in the middle of building this Django app and after I got the main parts that I wanted which were the login page and the homepage working, I decided on updating the look of my page because it was VERY basic. I've used bootstrap a ton before and I'm in love with it. However, this problem to me is a first. As you will see down below I have linked bootstrap via CDN (TWICE) and also via reference stylesheet link. Despite all these different ways of getting bootstrap my page still looks like this . Here is my base_generic.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>Local Library</title>{% endblock %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">--> <!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>--> <!--<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>--> <!-- Add additional CSS in static file --> {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}"> <!--<img src="{% static 'catalog/images/local_library_model_uml.png' %}" alt="My image" style="width:555px;height:540px;"/>--> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap-3.3.7-dist/css/bootstrap.min.css' %}" /> </head> <body> {% include "header.html" %} <div class="jumbotron"> <div class="container"> {% block content %}{% endblock %} {% include "pagination.html" %} </div> </div> </body> </html> And here is my header.html … -
Match string with database in django
A user will come on website and fill the registration form. Registration form has a question displayed below Which subjects you want to study? Answer by user - I want to study Hindi and english sentence="I want to study Hindi and english" I have 2 database displayed below. Now the answer by the user should match with the one database table with maximum accuracy , The database table matching with maximum accuracy should get selected . I am not able to match with accuracy and if the users write in a different way like I am studying hindi and english I want to study hindi and english . The above 2 sentences means the same but proper matching with database table is not being done by me properly. Kindly help me to resolve this issue. Database: Class_A id subject 1 Hindi 2 English 3 Physics Class_B Id subject 1 Hindi 2 Math 3 Science view.py def submission(request): obj = Registration.objects.latest('id') obj1 = Registration.objects.filter(name__contains=obj1) for a in obj1: sentence= a.subject word = sentence.split() class_a=class_A.objects.all() class_b=class_B.objects.all() if class_a in word: return render(request,'data/submission.html',{'Class':'Your Are in Class A'}) elif class_b in word: return render(request, 'data/submission.html', {'Class': 'You are in Class B'}) Registration is user … -
Show loading in django while subprocess.popen finshes
i want to show a loading image in django while a process i call with subprocess finishes, how can i do this? def core(request) proc = subprocess.popen(...) return render(request, 'core/temporaryloading.html', {'Proc': proc}) The html page shows me a loading bar and then i want it to switch to a final html with some info when the "proc" finishes. how do i handle Proc on the other side? Thanks -
Insecure Login Facebook API
I want to create Facebook authorization in my django site. I find many libraries that can do this. I am using social_django (This is link for tutorial, not for docs). I am doing all written in tutorial, but I get error in facebook API, when I redirected in it. I am using ngrok so insteadlocalhost i use https connection, but when I try authorize i get this error: Insecure Login Blocked: You can't get an access token or log in to this app from an insecure page. Try re-loading the page as https:// I can understand what is wrong. One place when i find not https is redirect_url in get parameter, instead of https social_django use http, I don`t know why. The question is how i can test my application with facebook api local? -
Django : An AppRegistryNotReady raised error when trying to connect a signal between different apps
I want to build an notification system in my django project. So I started to create an new app called notification. To create the notification I have to listen to the actions of the other models of my project. To reach this purpose I created in my notification app a signal handler : in notification/signals.py def create_subscription(sender, **kwargs): pass I connect this handler to my signal in my notification/apps.py from django.apps import AppConfig from django.db.models.signals import post_save from notification.signals import create_subscription from django.conf import settings class NotificationConfig(AppConfig): name = 'notification' def ready(self): post_save.connect(create_subscription, sender=settings.AUTH_USER_MODEL, dispatch_uid="create_subscription") This works fine. I used my custom User model defined in my settings. But whenever I want to use another model of my project, like : from django.apps import AppConfig from django.db.models.signals import post_save from notification.signals import create_subscription from member.models import Participation class NotificationConfig(AppConfig): name = 'notification' def ready(self): post_save.connect(create_subscription, sender=Participation, dispatch_uid="create_subscription") I get an AppRegistryNotReady error, no matter which model I use. I checked the order of declaration of my settings.INSTALLED_APPS, 'member' is declared before 'notification'. When referring to the User model by passing threw the settings.AUTH_USER_MODEL it's working fine, but when referring directly to the model it creates an error. Any ideas? -
Django: BaseFormSet & url slug
How do I get the slug organizer from my url in my class BaseReserveFormSet? Anyone did that before? I am really struggling how to solve that. BaseFormSet: class BaseReserveFormSet(BaseFormSet): def clean(self): queryset = Organizer.objects.filter( # MY PROBLEM: HOW DO I GET <slug:organizer> IN HERE? slug='lorem-2', ) max_qty_per_ticket = queryset.first().max_qty_per_ticket urls.py urlpatterns = [ path('<slug:organizer>/<slug:event>/', event_detail_view, name='event'), ]