Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sqlite3.sqlite3.OperationalError: database table is locked on django LiveServerTestCase
I am updating project's django version from 1.11 to django 2.0.8. Bet when I run a test which inherits from LiveServerTestCase and getting this error, which says: sqlite3.OperationalError: database table is locked Traceback: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/utils/decorators.py", line 62, in _wrapper return bound_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/utils/decorators.py", line 58, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "/pipeline/source/core/api_views.py", line 21, in dispatch return super(CurrencyViewSet, self).dispatch(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch response = handler(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/mixins.py", line 48, in list return Response(serializer.data) File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py", line 765, in data ret = super(ListSerializer, self).data File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data self._data = self.to_representation(self.instance) File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in to_representation self.child.to_representation(item) for … -
pip install Valuerror while installing saleor on Ubuntu 14
I am setting up saleor on a new Ubuntu 14 Installation and when I run the following command: pip install -r requirements.txt I get an exception. I am not that knowledgeable on Linux and I am getting an error I don't understand how to address. I think it is complaining about the format of a specific line in the requirements.txt file but I don't know why. The exception I get is this: Exception: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 262, in run for req in parse_requirements(filename, finder=finder, options=options, session=session): File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1632, in parse_requirements req = InstallRequirement.from_line(line, comes_from, prereleases=getattr(options, "pre", None)) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 173, in from_line return cls(req, comes_from, url=url, prereleases=prereleases) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 71, in __init__ req = pkg_resources.Requirement.parse(req) File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2667, in parse reqs = list(parse_requirements(s)) File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2605, in parse_requirements line, p, specs = scan_list(VERSION,LINE_END,line,p,(1,2),"version spec") File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2583, in scan_list "Expected ',' or end-of-list in",line,"at",line[p:] ValueError: ("Expected ',' or end-of-list in", 'uwsgi==2.0.17 ; platform_system != "Windows"', 'at', ' ; platform_system != "Windows"') Storing debug log for failure in /home/edwin/.pip/pip.log -
Chained Selects in Django [Module: django-smart-selects]
I'm trying to use the django-smart-selects Module in order to create dependent dropdown lists. I've followed the documentation and defined models in which I used the 'ChainedForeignKey' in order to define a link between my companies and my products. models.py class Company(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Product(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) name = models.CharField(max_length=255) def __str__(self): return self.name class Rates(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) product = ChainedForeignKey( Product, chained_field = "company", chained_model_field = "company", show_all = False, auto_choose = True, sort=True) taux_comm_1 = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(1)]) taux_comm_2 = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(1)]) Then I have defined a form : forms.py class Rates(forms.ModelForm): class Meta: model = Rates fields= ['company', 'product', 'taux_comm_1', 'taux_comm_2'] The data is retrieved from my database and I can select a company from the first dropdown list. The second list (Product), though, is locked. I've associated products to companies in my database ( using the foreign key ). If you guys have any ideas how I could solve that problem, that would be really good. I've searched for a similar issue but I couldn't find anything like it. Here is a screenshot of the form. -
Django Dynamic Database
I Would like to create a web page in Django which allow a user to dynamically create a Data Base.Im using MySql Scenario : The user fills up a form with fields like firstname, lastname .. Then after the submit, django creates a brand new DB. The model is then stored in this new DB. Django save/store this DB setting for further use like post or get operation from the model. -
'UNIQUE constraint failed' when using django-import-export get_or_create()
I have three models, Artist, Venue and Event. The Event model links to both an Artist and a Venue. When using django-import-export to import Event data I would like to be able to add using Artist or Venue name, rather than it's Primary Key. So far I have managed to get this to work only if the imported models are not already created. My code looks like this; admin.py from django.contrib import admin from django import forms from .models import Venue, Artist, Event from import_export.admin import ImportExportModelAdmin from import_export import fields, resources from import_export.widgets import ForeignKeyWidget class ArtistForeignKeyWidget(ForeignKeyWidget): def clean(self, value,row=None,*args, **kwargs): #this takes the value of the input and passes it to 'get_or_create' artist, created = Artist.objects.get_or_create(artist_name=value) #if the artist already exist #this returns a UNIQUE constraint error, needs fixing if created == False: return artist #if the artist has been created (works fine) else: return artist class VenueForeignKeyWidget(ForeignKeyWidget): def clean(self, value,row=None,*args, **kwargs): venue, created = Venue.objects.get_or_create(venue_name=value) if created == False: return venue else: #return new venue element return venue class EventResource(resources.ModelResource): #create ForeignKeyWidget to replace Artist & VEnue primary key with name in import/export artist = fields.Field(column_name='artist', attribute='artist', widget=ArtistForeignKeyWidget(Artist, 'artist_name')) venue = fields.Field(column_name='venue', attribute='venue', widget=VenueForeignKeyWidget(Venue, 'venue_name')) class Meta: … -
Django GenericForeignKey update
I am trying to convert a ForeignKey to GenericForeignKey in django. I plan to do this in three migrations, mig1, mig2, mig3. Migration 1 (mig1) has the following code class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('post_service', '0008_auto_20180802_1112'), ] operations = [ migrations.AddField( model_name='comment', name='content_type', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType'), ), migrations.AddField( model_name='comment', name='object_id', field=models.PositiveIntegerField(null=True), ), ] Migration 2 (mig2) has the following code def change_posts_to_generic_key_comment(apps, schema_editor): Comment = apps.get_model('post_service', 'Comment') db_alias = schema_editor.connection.alias comments = Comment.objects.using(db_alias).all() for comment in comments: Comment.objects.filter(id=comment.id).update(content_object=comment.post) def reverse_change_posts_to_generic_key_comment(apps, schema_editor): Comment = apps.get_model('post_service', 'Comment') db_alias = schema_editor.connection.alias comments = Comment.objects.using(db_alias).all() for comment in comments: Comment.objects.filter(id=comment.id).update(content_object=) class Migration(migrations.Migration): dependencies = [ ('post_service', '0009_auto_20180802_1623'), ] operations = [ migrations.RunPython(change_posts_to_generic_key_comment, reverse_change_posts_to_generic_key_comment), ] I tried to use both update and direct assignment of object comment.content_object = content.post followed by comment.save() none of them seems to work. How do i update generic foreign key field. One method is to manually set content_type and object_id. Is there any better way of doing this? -
Recommendation for manipulating data with python vs. SQL for a djano app
Background: I am developing a Django app for a business application that takes client data and displays charts in a dashboard. I have large databases full of raw information such as part sales by customer, and I will use that to populate the analyses. I have been able to do this very nicely in the past using python with pandas, xlsxwriter, etc., and am now in the process of replicating what I have done in the past in this web app. I am using a PostgreSQL database to store the data, and then using Django to build the app and fusioncharts for the visualization. In order to get the information into Postgres, I am using a python script with sqlalchemy, which does a great job. The question: There are two ways I can manipulate the data that will be populating the charts. 1) I can use the same script that exports the data to postgres to arrange the data as I like it before it is exported. For instance, in certain cases I need to group the data by some parameter (by customer for instance), then perform calculations on the groups by columns. I could do this for each different … -
Registered redirect URI does not match in instagram intergration with Pyhthon Django
I am trying to add an instagram login using social-auth-app-django. When I try to login I get this error: {"error_type": "OAuthException", "code": 400, "error_message": "Redirect URI does not match registered redirect URI"} On the Instagram developer site I have added http://localhost:8000/oauth/complete/instagram as redirect URI. After adding the Instagram keys and backend setting, the settings.py looks like this (I have replaced the keys with placeholders): import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '<MY_SECRET_KEY>' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'authentication', ] 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', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTHENTICATION_BACKENDS = ( 'social_core.backends.instagram.InstagramOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_INSTAGRAM_KEY = '<MY_INSTAGRAM_KEY>' SOCIAL_AUTH_INSTAGRAM_SECRET = '<MY_INSTAGRAM_SECRET>' SOCIAL_AUTH_INSTAGRAM_REDIRECT_URL = 'http://localhost:8000/oauth/complete/instagram' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' The url.py looks … -
OAuth2 redirect_uri cannot open the application's authorization page
I am trying to implement OAuth2 in my django project. I am the consumer side and I need to get the "code" from the provider side. My application is being implemented in django. In my products/view.py; def auth_for_app(request): CLIENT_ID = "xxxxxx" CLIENT_SECRET = "xxxxxx" # In provider side, this redirect_uri is also saved # REDIRECT_URI = 'http://127.0.0.1/products/auth' AUTHORIZE_URL = "https://www.PROVIDER-WEBSITE.com/admin/user/auth" ACCESS_TOKEN_URL = "https://www.PROVIDER-WEBSITE.com/oauth/v2/token" if request.method == 'GET': if 'provider' in request.GET: # 1. Ask for an authorization code r = requests.get('{}?response_type=code&client_id={}&redirect_uri={}'.format(AUTHORIZE_URL, CLIENT_ID, REDIRECT_URI)) return render (request, 'products/auth.html') In my products/urls.py; from django.urls import path from django.views.generic.base import TemplateView from . import views app_name = 'products' urlpatterns = [ path('', views.IndexView.as_view(), name='base'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('auth/', views.auth_for_app, name='auth_for_app'), ] In my related html file (products/templates/products/example.html), I have a button for this request; <form role="form" action="{% url 'products:auth_for_app' %}" method="GET"> {{ provider_form.as_p }} <input type="submit" class="btn" value="Auth: App" name="provider"> </form> What I expect is that when I click "Auth: App" button, my application should go to the provider's related authorization page in order to provide the user to approve or deny. After that, it should redirect the user to my 'http://127.0.0.1/products/auth' page with the related code value. When I try this process … -
cookiecutter gh:agconti/cookiecutter-django-rest, how to use this cookie cutter
Im quite new in django rest framework. Im getting an error while trying to run cookiecutter for ddjango rest framework I get this error Examto.virtualenvs\dev-OG_Ndht5\lib\site-packages\django\conf__init__.py", line 125, in init raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. -
Select related of m2m through reverse key
I have the following definition: class ModelA(models.Model): modelb = models.ForeignKey('ModelB') class ModelB(models.Model): nextb = models.ForeignKey('ModelB', related_name='reverseb') modelc = models.ForeignKey('ModelC') I have a QuerySet of ModelA objects and I am trying to prefetch modelc for the reverse relationship of nextb for each modelb: ModelA.objects.filter(...).prefetch_related('modelb__reverseb__modelc') However modela_object.modelb.reverseb.all()[0].modelc is querying the database, where I would expect modelc to have been fetched already. Am I doing something wrong here or this is simply not possible? If so, how should I prefetch what I want? -
How do I create a Login System in Django Using Sessions?
I am trying to create a website which is authenticated by a custom login. But I have a custom Model for users. How do I authenticate my Website from anonymous Users. Is it possible to create login systems using based on sessions. Actually this is my first django project. Please Guide me. Thank you. -
How to use NTML Authentication in Angular 4 - Django REST project
In our project the frontend UI is being developed in Angular 4 which is ultimately communicating (calling REST APIs) with the backend Django REST Framework. Both are running in Linux Server. For authentication purpose we have to use the window NTML authentication system. We have to access the Active Directory to get access to the usernames and passwords for the users. For the first time users have to login using their own username & password, but after that from next logins (homepage URL hit from browser) the application will not prompt for the login credentials (login page will not appear) like other company web-apps that are running in system. It will be helpful if anyone can provide the steps to be perform to implement this type of authentication system. Setup requited at Django REST Framework, i.e. our backend Setup required at Angular 4, i.e. our frontend. Setup required at system level (OS level). Thanks in advance. -
Add value on IntegerField with a button(Django 1.11)
models.py likes = models.IntegerField() forms.py class LikeForm(forms.ModelForm): class Meta: model = Post fields = ("likes",) How could I make a button that add 1 to this IntegerField every time it's clicked? The default value is 0. I'm guessing I have to use "submit" button but I'm not sure how I can do that with out rendering the form on the page. -
how to write in django restapi[POST] to add database values of field1 and field2 to field3?
while inserting data through post in django restapi how to write a function to add filed values? EX: column1:900 ,column2:1000, column3=column2-column1 -
django crontab trigger import error
I am trying to use django-crontab in my django project. Now I am facing this problem My simple Django project structure is like this (venv_for_django_1_6) [pete@localhost crontab_ex]$ tree . |-- app | |-- admin.py | |-- cron.py | |-- __init__.py | |-- __init__.pyc | |-- models.py | |-- models.pyc | |-- tests.py | `-- views.py |-- crontab_ex | |-- __init__.py | |-- __init__.pyc | |-- settings.py | |-- settings.pyc | |-- urls.py | |-- urls.pyc | |-- wsgi.py | `-- wsgi.pyc |-- manage.py `-- manage.pyc And I added codes in setting.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'django_crontab', ) CRONJOBS=[ ('*/1 * * * *', 'crontab_ex.app.cron.my_job', '>> /tmp/crontab_job.log') ] My function in cron.py is like this import os def my_job(): job = os.system("date") return job However, when I tried to run command python manage.py crontab add ., I got a warning in terminal You have new mail in /var/mail/pete The content of this mail 2f4a6720d4241d072 >> /tmp/crontab_job.log # django-cronjobs for crontab_ex Content-Type: text/plain; charset=UTF-8 Auto-Submitted: auto-generated Precedence: bulk X-Cron-Env: <XDG_SESSION_ID=25> X-Cron-Env: <XDG_RUNTIME_DIR=/run/user/1000> X-Cron-Env: <LANG=en_US.UTF-8> X-Cron-Env: <SHELL=/bin/sh> X-Cron-Env: <HOME=/home/pete> X-Cron-Env: <PATH=/usr/bin:/bin> X-Cron-Env: <LOGNAME=pete> X-Cron-Env: <USER=pete> Message-Id: <20180804055902.2D5F020DCF40@localhost.localdomain> Date: Sat, 4 Aug 2018 13:59:02 +0800 (CST) Traceback (most … -
In My shell when i run that Script it show error and when i use ipdb it show me error on in line 30 TimeoutException: TimeoutException()
I use that script for WhatsApp integration with my website in python. Why My that Script is not working can you please check here in contact i maintain my contactfile and when use ipdb for trace code it show me error in line 30. from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import time driver = webdriver.Chrome('./chromedriver') driver.get('https://web.whatsapp.com/') wait = WebDriverWait(driver, 600) with open("contact") as f: for line in f: try: name = (line.rstrip('\n')) text = """Hello {}, My name is Rhevin Have a good day :) """.format(name) print 'Harish' inp_xpath_search = "//input[@title='Search or start new chat']" input_box_search = wait.until(EC.presence_of_element_located(( By.XPATH, inp_xpath_search))) print '@@@@@@@@@@@@@@@@',input_box_search input_box_search.send_keys(name + Keys.ENTER) #x_arg_contact = '//div[@class="chat-title"]' x_arg_contact = '//span[contains(@title,' + name + ')]' input_box_contact = wait.until(EC.presence_of_element_located(( By.XPATH, x_arg_contact))) print '-------------------',input_box_contact inp_xpath = "//div[@contenteditable='true']" input_box = wait.until(EC.presence_of_element_located(( By.XPATH, inp_xpath))) print '+++++++++++++++++++++++',input_box input_box.send_keys(text + Keys.ENTER) print '===============================' time.sleep(5) print("send") except: print("error") -
Django: Before or after __init__?
I am a bit confused with super(). Should self.order = order come before or after it? It seems to work both when I tested it. I just use it so often, so I think it's good I understand it better. def __init__(self, order, *args, **kwargs): self.order = order # BEFORE OR AFTER __init__? super().__init__(*args, **kwargs) -
Django: Use positional argument & keyword argument together
That approach here below wouldn't work as it's a positional argument & keyword argument in one function. I understood, generally, kwargs are better as you can 'mess' around with the order. But how do I have to change request.POST in order to use kwargs? form_refund = RefundForm( order=order, request.POST, ) -
django-progressbarupload {% progress_bar %} doesn't display progress
I'm building a small app that stores whalesong. I've got my forms uploading to an S3 via boto3 and django-storages. I've also installed the development version of django-progressbarupload and am running django 2.0.6 The progress bar element appears and is styled, but doesn't animate nor sync with the file upload. The files are going to an s3 via a spotty connection, and the transfer usually takes 10-15 seconds. I've attached a video of an upload in action. base template header <head> {% load progress_bar %} {% block title %}<title>Whale Song and other Cetacean Communication</title>{% endblock %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/app.css' %}"> <script type="text/javascript" src="{% static 'js/amplitude.min.js' %}"></script> <script src="{% static "js/jquery-3.3.1.min.js" %}"></script> {% progress_bar_media %} </head> form template snip {% extends "base_generic.html" %} {% load progress_bar %} {% block content %} <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.non_field_errors }} <div> <label for="{{ form.file.id_for_label }}">File</label> {{ form.file.errors }} {{ form.file }} {% progress_bar %} </div> Project Here: https://github.com/kidconcept/whalejams Video Here https://tinytake.s3.amazonaws.com/pulse/elpulpo/attachments/8400940/TinyTake29-07-2018-11-47-06.mp4 -
How can I transmit session in Django?
login.html `<h2>Login</h2> <form method="post" action=""> {% csrf_token %} {{ form.as_p }} </form> <a href="{% url 'loggedin' %}"><input type="submit" value="login" /></a>` loggedin.html `<h2>login success</h2>` views.py `def signin(request): if request.method == "POST": form = LoginForm(request.POST) #form = email, password email_input = str(request.POST['email']) password_input = str(request.POST['password']) user_Qset = Profile.objects.filter(email = email_input) if user_Qset is not None: password_saved = str(user_Qset.values('password')[0]['password']) if password_input == password_saved: response = render(request, 'registration/login.html',) request.session.modified = True request.session['name'] = user_Qset.values('name')[0]['name'] request.session['email'] = user_Qset.values('email')[0]['email'] request.session['password'] = user_Qset.values('password')[0]['password'] return response def loggedin(request): if request.session.has_key('name'): return HttpResponse("transmission success") else: return HttpResponse("transmission failed")` I have a result 'transmission failed'. How can I transmit sessions I added? When I push the login button, page url and templates should be changed and session be transmitted -
cross instance calculations in django queryset
Not sure that it's (a) doable and (b) if I formulate the task correctly. Perhaps the right way is refactoring the db design, but I would appreciate any opinion on that. I have a model in django app, where I track the times a user enters and exits a certain page (via either form submission or just closing the broswer window). I do tracking using django channels, but it does not matter in this case. The model looks like: class TimeStamp(models.Model): class Meta: get_latest_by = 'enter_time' page_name = models.CharField(max_length=1000) participant = models.ForeignKey(to=Participant, related_name='timestamps') timestamp = models.DateTimeField() enter_exit_type = models.CharField(max_length=1000, choices=ENTEREXITTYPES,) What I need to do is to calculate how much time a user spends on this page. So I need to loop through all records of Timestamp for the specific user, and calculate time difference between records of 'enter' and 'exit' types records. So the db data may look like: id timestamp type 1 20:12:12 enter 2 20:12:13 exit 3 20:18:12 enter 4 20:21:12 exit 5 20:41:12 enter so what is the right way to produce a resulting queryset that look like: id time_spent_sec 1 0:01 2 3:00 The last 'enter' record is ignored because there is no corresponding 'exit' … -
Python, Django Error
Traceback (most recent call last): File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\manage.py", line 17, in <module> execute_from_command_line(sys.argv) File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\core\management\base.py", line 350, in execute self.check() File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\core\management\base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\urls\resolvers.py", line 396, in check for pattern in self.url_patterns: File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\urls\resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "c:\users\misafir\source\repos\DjangoWebProject7\DjangoWebProject7\env\lib\site-packages\django\urls\resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "C:\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File ".\DjangoWebProject7\urls.py", line 23, in <module> django.contrib.auth.views.login, … -
Django: Is there anyway to get the value or data from an checkbox form that was previously checked, then unchecked
I have a view which displays many forms (which are individual checkboxes per form). I would like to get the value of the checkbox that was previously checked, but then unchecked. When I check one of the boxes, I get that value in request.POST data, but unchecking gives me nothing. Is it possible to access this data/form-label-id? def employee_output_table(request): table = Employees.objects.all() queue_exists = UserSurveyQueue.objects.filter(user=request.user) context = [] for user in table: d = {} d['user'] = user username = User.objects.get(username=user).username queue = None if queue_exists: queue = queue_exists.get(user=request.user) context.append(d) queryset = queue_exists.get(user=request.user) if request.method == "POST": form = UpdateSurveyQueueForm(request.POST, instance=queue, user=request.user.id, query=user, prefix=queue.id) if form.is_valid(): form.instance.user = request.user q = form.cleaned_data.get('queue').get() form.instance.queue.add(q) return HttpResponseRedirect(reverse('employee-table')) else: form = UpdateSurveyQueueForm(instance=queue, user=request.user.id, query=user, prefix=queue.id) d['form'] = form return render(request, 'surveys/employees_list.html', {'employee_table': context}) -
django haystack how do I know in result which field of the model contains the query
I use django-haystack in my django website, and I write a model containing four richtext fields. How should I know which field of the model instance contains the query if the model instance is returned by haystack? here is my code. #models.py class Version(models.Model): name=models.CharField('version',max_length=25) user = models.ForeignKey(User,on_delete=models.CASCADE,verbose_name='user') update_description = RichTextUploadingField('update description') description=RichTextUploadingField('description') publish_date = models.DateTimeField('publish date',auto_now_add=True) reports=RichTextUploadingField('report') scripts=RichTextUploadingField('script') #search_indexs.py class VersionIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return Version def index_queryset(self, using=None): return self.get_model().objects.all() #version_text.txt {{ object.name }} {{ object.update_description }} {{ object.description }} {{ object.reports }} {{ object.scripts }}