Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get list from two models (With addtional fields). Make Subquery
I have models Reserved and Room (default status is Free). And i want get list of all Rooms. Their statuses is Reserved (I have such table) Free (not price, state) Busy So in short i need to get all Rooms with their status. I don't need status fields and will not add it. No status field in my models. How can i get certain statuses? Shortly model class Room(models.Model): # Default all rooms are Free (Rooms state) number = models.ForeignKey(RoomNumber) expiry_date = models.DateTimeField() class Reserved(models.Model): visitor = models.ForeignKey(Visitor, on_delete=models.PROTECT) room = models.OneToOneField(Room) reserved_date = models.DateTimeField() begin_date = models.DateTimeField() I tried to do Subquery but no result :( reserved = Reserved.objects\ .filter(room=OuterRef('pk'))\ .filter(begin_date=timezone.now())\ .values(count=Count('pk')) Room.objects.annotate(reserved=Subquery(reserved[:1])) If 1 room is Reserved if 0 empty -
Learn about user status with token_for_business on Facebook
I want to delete the random facebook business id that was entered into the database years ago. An idea for that came to mind. Putting business id in the database on the facebook verification test. I entered the Facebook development environment. Here I wanted to test several business_ids in db. But I did not get the result I wanted. In the end, can I check with the token_for_business id to see if the user actually exists? -
Docker container does not recognize DJango Formtools
I have some code that uses DJango Form Tools (in particular, the SessionWizardView) . From what I can see, the Formtools appears to work outside a Docker Container but fails when it is used within one. The environment where it is working is development. The Docker container where it is not wokring is Production. The error message one gets is (in the log of the running contaner): from formtools.wizard.views import SessionWizardView ModuleNotFoundError: No module named 'formtools' **I have installed formtools on the C:\Users\dgmufasa>pip install django-formtools Requirement already satisfied: django-formtools in c:\work\software\python64bitv3.6\lib\site-packages Requirement already satisfied: Django>=1.8 in c:\work\software\python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg (from django-formtools) Requirement already satisfied: pytz in c:\work\software\python64bitv3.6\lib\site-packages\pytz-2017.3-py3.6.egg (from Django>=1.8->django-formtools) I have added it to INSTALLED_APPS in the settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', [..snip ..] 'formtools', ] I have used it as part of a program: from django.shortcuts import render, render_to_response from formtools.wizard.views import SessionWizardView #from django.contrib.formtools.wizard.views import SessionWizardView from django.contrib.auth.decorators import login_required [... snip ...] In this area (development) it all works - but - when taking the EXACT same code, creating a Docker file and putting it into production, I get errors. **requirements.txt for Docker build** file Django==1.11.7 psycopg2 Pillow==4.3.0 bcrypt==3.1.4 cffi==1.11.2 django-formtools django-phonenumber-field==1.3.0 googlemaps==2.5.1 geocoder==1.33.0 geopy==1.11.0 … -
Dynamic read-only field in Django Admin
In Django Admin I want all fields to be: 1) editable on creation 2) some of them on updating ( based on the instance fields values on creation). For example: 2-1. If attribute a has value the fields corresponding to attributes c and b to be readonly 2-2. If attributes are empty after creation, should not be editable on updating -
Understanding a hairy SQL situation
I have a Django app with pymysql to connect to my MySQL instance. Following is my python code for a post request: if request.method == 'POST': body = json.loads(request.body.decode('utf-8')) db = connect_to('table_name', 'key') for json_variable in body['json_key']: record = db.findFirst({'user_id': user_id, 'date': body['date']}) if not record: db.create({'column_name':value}) else: db.update({'column_name':value}, {'user_id': user_id}) In this connect_to, findFirst, create and update are helper methods to connect to the database, find first record with parameters, create a new record and update a table with parameter 1 where parameter 2 is true. The issue is that in many situations, despite a record being present a new one is created and not updated as it should be. The django app itself is on heroku and the mysql instance is on AWS. -
celery task not processed by celery
total celery and django noob here, so sorry if the problem is trivial. Basically the problem is that any function defined by @app.task is not being processed by celery, it just runs normally as if celery isn't there. My celery_app.py file is - from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery(broker=settings.CELERY_BROKER_URL) app.config_from_object('django.conf:settings') app.autodiscover_tasks() if __name__ == '__main__': app.start() While my tasks.py file is - from project.celery_app import app @app.task def mytask(): ... I get the following output on running celery in the terminal - -------------- celery@LAPTOP v4.1.0 (latentcall) ---- **** ----- --- * *** * -- Windows-10-10.0.16299-SP0 2017-12-20 19:27:24 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: __main__:0x229ce2884e0 - ** ---------- .> transport: amqp://user:**@localhost:5672/myvhost - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 8 (solo) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . tasks.send_sms [2017-12-20 19:27:24,085: INFO/MainProcess] Connected to amqp://user:**@127.0.0.1:5672/myvhost [2017-12-20 19:27:24,101: INFO/MainProcess] mingle: searching for neighbors [2017-12-20 19:27:25,126: INFO/MainProcess] … -
Django ORM Count by Related Field
I have the following models: class Profile(models.Model): pass class Team(models.Model): ... members = models.ManyToManyField("main.Profile", through='main.TeamMember') class TeamMember(models.Model): profile = models.ForeignKey('Profile') team = models.ForeignKey('Team') role = models.CharField(max_length=255) So, I try to order teams by count of profiles with a certain role, and I had a query, which doesn't work: Team.objects.filter(members__role='ExampleRole').annotate(example_role_count=Count('members')).order_by('example_role_count') It raises the following Exception: django.core.exceptions.FieldError: Related Field got invalid lookup: role because role is a TeamMember field, not Profile. So, how can I achieve ordering by count of members with a specified role? -
Django Listview for model related to user returning "No user" error
I'm trying to produce a list of user addresses so that a user can review and then update, delete etc... Currently I'm using ListView with: class AddressListView(LoginRequiredMixin, ListView): model = Address def get_object(self): return self.model.objects.get(user=self.request.user.pk) with the Address model: class Address(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) house_name = models.CharField(max_length=255, null=True) house_number = models.CharField(max_length=255, null=True) street_name = models.CharField(max_length=255, null=True) ....... And the url pattern: .... url( regex=r'^address/$', view=views.AddressListView.as_view(), name='address_list' ), ... However when I try to request that view I get an error "Page not found (404), No user found matching the query" -
How to rectify the error in defining the forms.ModelForm widgets
enter image description hereI am getting the following error when assigning a widget to forms.ModelForm. Please suggest how to rectify this error. forms.py from django import forms from django.forms import ModelForm, CharField from .models import * class CreateTaskMaster(forms.ModelForm): class Meta(): model = TaskMaster fields = ["sid", "tasktype", "task_title", "task_description", "datacenter", "priority", "sourceincident", "processingteam", "duedate"] widgets = { 'duedate': CharField(widget=forms.TextInput(attrs={'class': 'form- control mr-sm-2'})), } Model.py Class TaskMaster(models.Model): sid = models.CharField(max_length=3) processor = models.ForeignKey(User,null=True) tasktype = models.ForeignKey(TaskTypeTable, null=True) task_title = models.TextField(null=True) task_description = models.TextField(null=True) datacenter = models.ForeignKey(DatacenterTable,null=True) priority = models.ForeignKey(PriorityTable, null=True) status = models.ForeignKey(StatusTable,default=1, null=True) pid = models.IntegerField(null=True) sourceincident = models.URLField(null=True) errorincident = models.URLField(null=True) processingteam = models.ForeignKey(TeamTable, null=True) createddate = models.DateField(("Date"), default=datetime.date.today) duedate = models.DateField(("Date"), default=datetime.date.today) istaskactive = models.BooleanField(default=True) class Meta: ordering = ('duedate',) -
How to create equivalent LEFT JOIN query in Django's ORM (1.11)
With the following model setup (simplified for brevity): class Claim(models.Model): permalink = models.SlugField(max_length=255, blank=True, unique=True) author = models.ForeignKey(get_user_model(), db_index=True, on_delete=models.SET_NULL, null=True, blank=True) collaborators = models.ManyToManyField(get_user_model(), through='ClaimCollaborator', related_name='claims') # ...other fields class ClaimCollaborator(models.Model): claim = models.ForeignKey(Claim, db_index=True, on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), db_index=True, on_delete=models.CASCADE) # ...other fields I am trying to replicate the following SQL query in Django's ORM. SELECT * FROM claim c LEFT JOIN claim_collaborator cc ON cc.claim_id = c.id WHERE c.permalink = 'foo-bar' AND (c.author_id = 2 OR cc.user_id = 2) The logic I believe should be straightforward with usage of django.db.models.Q, but the bit I'm struggling on is the LEFT JOIN. Bit of a Django ORM noob, and I have attempted various usage of select_related() with the ClaimCollaborators model to no avail. Any ideas? -
Django Heroku deployment: OperationalError at /users/login/ no such table: auth_user [duplicate]
This question already has an answer here: Django: Deploying an application on Heroku with sqlite3 as the database 1 answer I built a django web app, using sqlite3 as database. my app works fine (create superuser, login as admin, and use the app) in local environment, but after I deploy it on Heroku I encountered issues: 1. 'heroku run python manage.py migrate' doesn't set up the live database (db.sqlite3) on Heroku. (cannot find any .sqlite3 files in /app) local$ heroku run python manage.py migrate local$ heroku run bash # cannot find any .sqlite3 files on live database ~$ ls manage.py Procfile requirements.txt runtime.txt myproject myapp users ~$ ls myproject __init__.py __pycache__ settings.py static urls.py wsgi.py So I typed 'python manage.py migrate' again inside 'heroku run' bash, creating db.sqlite3. ~$ python manage.py migrate ~$ ls myproject db.sqlite3 __init__.py __pycache__ settings.py static urls.py wsgi.py But, as soon as I exit the bash, the .sqlite3 disappears again. ~$ exit local$ heroku run bash ~$ ls dir_project # no db.sqlite3 file __init__.py __pycache__ settings.py static urls.py wsgi.py 2. cannot login as created superuser on live app. local$ heroku run bash ~$ python manage.py migrate ~$ python manage.py createsuperuser username: example_admin email: example@mail.com password: **** … -
avoid Circular import in Django
I have two models Company and Actions: from companies.models import Company class Action(models.Model): company = models.ForeignKey(Company, blank=True, null=True, related_name='activity', on_delete=models.CASCADE) I have then an utility in utils.py from .models import Action def create_action(user, verb, target_name=None, target=None): action = Action(user=user, verb=verb, target=target) This utility I called in Company model on def save, so on Company Model I have: import not.utils import create_action so Action Model import Company Model as FK, utils import Action Model, and Company Model import utils Now, because of circular import Django give an error: ImportError: cannot import name 'Company' I saw some q/a here to use import directly (without from) I tried but didn't worked -
max_length does not work
I have such field in my model: name = models.CharField(max_length=20, default='Anonymous') But when I enter more characters in that field, there is no errors, I can enter any amount of characters. And I can do it in my view, do it in admin/, there is no errors anyway. Somebody adviced me to make .full_clean() before saving entries, but it does not affect, this field still allows to enter more than 20 characters. Same with other fields. And I very, very, very sorry for my bad english. -
Django-rest-framework: No module named 'rest_framework.reverse_lazy'
I have tried reverse of DRF it works from rest_framework.reverse import reverse reverse("posts-api:article_year_month",args=(2017,1)) '/api/gaurnitai/posts/2017/1' whereas the reverse_lazy is not working: from rest_framework.reverse_lazy import reverse_lazy reverse_lazy("posts-api:article_year_month",args=(2017,1),request=request) ModuleNotFoundError: No module named 'rest_framework.reverse_lazy' -
PushPin with django - publish is not happending
I have two docker containers one for pushpin from here and one for my django project which i have created locally. My settings file contains following code for pushpin MIDDLEWARE = [ 'django_grip.GripMiddleware', ... ] GRIP_PROXIES = [{'control_uri': 'http://localhost:5561'}] And my views are as follows: from future import unicode_literals from django.shortcuts import render from django.http import HttpResponse from django.views import View from json import dumps from gripcontrol import HttpStreamFormat from django_grip import set_hold_stream, publish from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator # Create your views here. counter = [0] * 10 class HelloWorld(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(HelloWorld, self).dispatch(request, *args, **kwargs) def get(self, request, cnt_id): cnt_str = 'counter-%s' % cnt_id cnt_id = int(cnt_id) data = {"counter": counter[cnt_id]} response = dumps(data) + '\n' set_hold_stream(request, cnt_str) return HttpResponse(response, content_type='text/plain') def post(self, request, cnt_id): cnt_str = 'counter-%s' % cnt_id cnt_id = int(cnt_id) global counter counter[cnt_id] += 1 data = {"counter": counter[cnt_id]} resp = dumps(data) + '\n' publish(cnt_str, HttpStreamFormat(resp)) return HttpResponse(resp, content_type='text/plain') Now whenever i do curl to pushpin it halts but does not get updated result published whenever i do post request #$ curl http://localhost:7999/hello/say/1/ {"counter": 2} It does not get updated result even after hitting post request. But … -
Django 2.0 Tutorial - Error when executing python3 manage.py makemigrations
i am interested in learning Django for python. Therefore i followed their Tutorial - yet now i am stuck at the following point of the second tutorial element: Problem: According to the tutorial i shall run a "Database Migration" by using the following codes: python3 manage.py makemigrations python3 manage.py migratecode I do receive the following error message on execution of the first command (makemigrations): > (django_second_test) sebastian@sebastian-Lenovo-Y50-70 > ~/Dokumente/py_virtualenv/django_virtualenv/django_second_test/locallibrary/locallibrary > $ python3 manage.py makemigrations Traceback (most recent call last): > File "manage.py", line 15, in <module> > execute_from_command_line(sys.argv) File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line > utility.execute() File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute > self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/management/base.py", > line 288, in run_from_argv > self.execute(*args, **cmd_options) File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/management/base.py", > line 332, in execute > self.check() File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/management/base.py", > line 364, in check > include_deployment_checks=include_deployment_checks, File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/management/base.py", > line 351, in _run_checks > return checks.run_checks(**kwargs) File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/checks/registry.py", > line 73, in run_checks > new_errors = check(app_configs=app_configs) File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/checks/urls.py", > line 40, in check_url_namespaces_unique > all_namespaces = _load_all_namespaces(resolver) File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/core/checks/urls.py", > line 57, in _load_all_namespaces > url_patterns = getattr(resolver, 'url_patterns', []) File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/utils/functional.py", > line 36, in __get__ > res = instance.__dict__[self.name] = self.func(instance) File "/home/sebastian/Dokumente/py_virtualenv/django_virtualenv/django_second_test/lib/python3.5/site-packages/django/urls/resolvers.py", > line 536, in url_patterns > patterns = … -
django celery @app.on_after_finalize.connect called twice
Using supervisor I start command = celery worker --app project --loglevel info --concurrency 1 and command = celery beat --pidfile= --app project --loglevel info --scheduler django_celery_beat.schedulers:DatabaseScheduler In my django app in tasks.py I set up crontab schedules. e.g. @app.on_after_finalize.connect def setup_periodic_tasks(sender: Celery, **kwargs): logger.info("Setting up periodic tasks") sender.conf.timezone = 'Europe/London' schedule, _ = CrontabSchedule.objects.get_or_create( minute='45', hour='*', day_of_week='*', day_of_month='*', month_of_year='*' ) PeriodicTask.objects.filter(name='Rebuild Order Cache').delete() PeriodicTask.objects.update_or_create(crontab=schedule, name='Rebuild Order Cache', task='app.tasks.rebuild_sales_order_cache') I get the log message twice. It seems that both celery instances started with supervisor are triggering '@app.on_after_finalize.connect' What should I do to have it run only one? -
How can I pre-set some value on django form?
forms.py class UserCreateForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput(attrs={'value': 'Hello_1'})) email = forms.EmailField(widget=forms.EmailInput(attrs={'value': 'Hello_2'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'value': 'Hello_3'})) class Meta: model = User fields = ['username', 'email', 'password'] views.py def create(request): form = UserCreateForm() return render(request, 'create.html', {'form': form}) In views.py Not in forms.py, How can I set some values on form's page initially render? I want to set different value depending on the type of form's fields. -
TLS issue while calling stripe charge API from my local env
I am implementing Stripe payment gateway in sandbox mode. I have embedded checkout process and also created token which is used by server to call API to create charges. API version used is: stripe.api_version = '2017-06-05' charge = stripe.Charge.create( amount=1000, currency="usd", description="Example charge", source=token, ) When I call this charge create api, I receive the following error: b'{\n "error": {\n "type": "invalid_request_error",\n "message": "Stripe no longer supports API requests made with TLS 1.0. Please initiate HTTPS connections with TLS 1.2 or later. You can learn more about this at https://stripe.com/blog/upgrading-tls."\n }\n}\n' The stripe API used to create charges in local machine is: POST: https://api.stripe.com/v1/charges How can I make it work on my local machine? But when I deployed it to AWS it is working there. -
angular 2 file upload using form data
fileChange(event) { let fileList: FileList = event.target.files; if(fileList.length > 0) { let file: File = fileList[0]; console.log('file',file); var formData = new FormData(); formData.append('file', file, file.name); var options = { content: formData }; console.log('options',options); var jsonBody = {}; jsonBody['submoduleid'] = '3789e76489fc4e118f8dffad107fbbbd'; jsonBody['file'] = options; console.log('jsonbody',jsonBody); this.Module7Service.uploadFile(jsonBody) .subscribe( data => { console.log(data.Response) if (data.message == "module7 finish") { console.log('after success',jsonBody) alert('done file uploaded successfully'); } else{ alert('not uploaded'); } }); } } //service code uploadFile(file){ const body = file; const headers = new Headers({ 'Authorization': window.localStorage.getItem('token'), 'content_type' : 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW', 'Accept': 'application/json', 'Access-Control-Allow-Origin' : '*', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Methods': 'GET,HEAD,OPTIONS,POST,PUT', 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept', 'Source': 'WEB' }); return this.http.post(this.apiUrl + 'module7/', { body: body }, { headers: headers }) .map( res => { return res.json(); }, error => alert("आपली विनंती आत्ता पूर्ण करू शकत नाही, कृपया पुन्हा प्रयत्न करा.")); } <input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx"> hello i want to implement file upload feature in my angular 2 project.i want to restrict user to upload only .pdf,.doc,.docx type file to be upload. i have added all required key,formdata etc. but when i upload file i am getting some as 'XMLHttpRequest cannot load "apiurl". Request header field Access-Control-Allow-Methods is not allowed by Access-Control-Allow-Headers … -
Django command doesn't work using crontab
I've decided to try django-kronos for scheduling manage.py commands. I need to run python manage.py refresh_current_cities every minute. The problem is that it doesn't seem to work but crontab is set properly I think: CRONTAB (beduenovenv) milano@milano-Aspire-VN7-591G:~/PycharmProjects/Cingo/Bedueno$ crontab -l * * * * * /home/milano/.virtualenvs/beduenovenv/bin/python /home/milano/PycharmProjects/Cingo/Bedueno/manage.py crontab run 5c86aa78737b83b191b7d1e68e12c8cd # django-cronjobs for Bedueno * * * * * /home/milano/.virtualenvs/beduenovenv/bin/python /home/milano/PycharmProjects/Cingo/Bedueno/manage.py refresh_current_cities --settings=Bedueno.settings &> /dev/null # kronos:6ca663be58d9b8e907b7210724845477 LOG Dec 20 12:15:01 milano-Aspire-VN7-591G CRON[25128]: (milano) CMD (/home/milano/.virtualenvs/beduenovenv/bin/python /home/milano/PycharmProjects/Cingo/Bedueno/manage.py refresh_current_cities --settings=Bedueno.settings &> /dev/null # kronos:6ca663be58d9b8e907b7210724845477) Dec 20 12:15:01 milano-Aspire-VN7-591G CRON[25124]: (CRON) info (No MTA installed, discarding output) Dec 20 12:16:01 milano-Aspire-VN7-591G CRON[25169]: (milano) CMD (/home/milano/.virtualenvs/beduenovenv/bin/python /home/milano/PycharmProjects/Cingo/Bedueno/manage.py refresh_current_cities --settings=Bedueno.settings &> /dev/null # kronos:6ca663be58d9b8e907b7210724845477) Dec 20 12:16:01 milano-Aspire-VN7-591G CRON[25171]: (milano) CMD (/home/milano/.virtualenvs/beduenovenv/bin/python /home/milano/PycharmProjects/Cingo/Bedueno/manage.py crontab run 5c86aa78737b83b191b7d1e68e12c8cd # django-cronjobs for Bedueno) Dec 20 12:16:01 milano-Aspire-VN7-591G CRON[25168]: (CRON) info (No MTA installed, discarding output) If I run the command manually, it works. COMMAND logger = logging.getLogger('logs/commands.log') @kronos.register('*/1 * * * *') class Command(BaseCommand): help = 'Refreshes current locations for all users' def handle(self, *args, **options): logger.info('Refreshing current destinations...') for up in UserProfile.objects.all(): up.refresh_current_city() Do you know what I'm doing wrong? -
Trying to understand Django's communication between view and template
I come from a web2py background and find Django a much more complicated framework to learn and use than web2py. In my view I have: hr = dict(name="Some Name",photo="/static/images/HR.jpg",url="http://some.website.com/?page_id=3602"), js = dict(name="Some Name2",photo="/static/images/JS.jpg",url = "http://some.website.com/?page_id=3608") return render(request, "wos_2017_2/team.html", {team:[hr,js]}) In the template I have tried several things. First I tried to do a for loop which ended in no output. I do not understand how the template language handles what is passed to it through render So I tried this manually to try and figure out how I can use what is passed from the view: <h3>The data-management team</h3> <ul> <li>{{ team.0.name }}</li> <li>{{ team.js.name }}</li> </ul> Which shows an with two empty items. My first preference would be to use a for loop but after many hours of reading and searching inter alia Stackoverflow I did not succeed. I then tried: team = dict(hr = ["Some Name","/static/images/HR.jpg","http://some.website/?page_id=3602"], js = ["Someone Name2","/static/images/JS.jpg","http://some.website/?page_id=3608"]) return render(request, "wos_2017_2/team.html", team) with the following in the template: <h3>The data-management team</h3> <ul> <li>{{ team.hr.0 }}</li> <li>{{ team.js.0 }}</li> </ul> with the same result (an empty list). How do I do it? -
How to make periodic function by using Celery with Django?
There have been many updates but I really don't get it how I can make use of Celery Periodic task with Django. I tried creating celery.py with regular settings and used redis as broker and I am able to execute function asynchronously at the back. But when it comes to add periodic task, I am not sure how to do it. I have gone through documentation but it's hard to understand. Is there any sample which I can go through, so that I can understand the code structure. -
Selenium test URL not found in Django
I'm new to Selenium and I'm getting "URL not found" error during a test. It's kinda strange since everything is working in my production evnviroment. I tried to replicate my production DB in my test enviroment but I still get the same error. I was just improving the Tutorial project of Django documentation v. 1.11. Here is my models.py: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.PositiveIntegerField(validators=[MinValueValidator(0)], default=0) def __str__(self): return self.choice_text Here is the urls.py : app_name = 'polls' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^specifics/(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'), url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] And finally we have the tests.py part: ### SELENIUM ### class VoteTest(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super(VoteTest, cls).setUpClass() cls.selenium = webdriver.Firefox() cls.selenium.implicitly_wait(10) Question.objects.create(question_text="Sample_question", days=1) Choice.objects.create(choice_text="Sample_choice", question=q, votes=1) def test_vote(self): self.selenium.get('%s%s' % (self.live_server_url, '/polls/')) self.selenium.find_element_by_xpath('//a[@id="1"]').click() # Here I get the "URL not found error", the URL is '.../polls/specifics/1/ As I said the URL is reachable from the webserver. I also print the values of the test DB during the tests and everything seems fine with IDs. … -
reset_sequence in pytest-django
I have posted my question to the pytest-django. But it seems non-active at least 2 weeks. I decided to ask my question here. In my test I want to use reset_sequence=True. How to do that in pytest-django?