Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why django.setup() raise error?
I have celery.py file with next code. This code raise error when I tryto make this command: python manage.py runserver. But in the same time celery task works with this command: celery -A TestProject worker -l info -B I use: Celery==4.1.1 Django==1.11.5 Redis==3.0.6 celery.py: from __future__ import absolute_import import os import sys from celery import Celery from celery._state import _set_current_app import django from django.conf import settings app = Celery('TestProject') app.config_from_object('django.conf:settings', namespace='CELERY') _set_current_app(app) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TestProject.settings') sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../EnjoyJumping'))) django.setup() app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) ERROR: AttributeError: 'Settings' object has no attribute 'ACCOUNT_PASSWORD_STRIP' If I remove django.setup() from celery.py file runserver command works but celery command don't work. It raise error: [2018-06-04 01:17:21,407: ERROR/MainProcess] Received unregistered task of type 'custom_app.tasks.counting'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: b'[[], {}, {"chain": null, "chord": null, "callbacks": null, "errbacks": null}]' (77b) Traceback (most recent call last): File "/home/ubuntu/enjoy_jumping/lib/python3.5/site-packages/celery/worker/consumer/consumer.py", line 557, in on_task_received strategy = strategies[type_] KeyError: 'custom_app.tasks.counting' I am realy confused. How to fix this problem? -
Import model from another app Django
I have a problem importing a model from another app. I am using Django 2.0. My project structure looks like this: --api --api --settings.py --urls.py --wsgi.py --product --models.py --chat --models.py --manage.py To show only the problem I have I simplified the structure. If you are missing something important let me know it. The file causing the error: chat/models.py from api.product.models import Product from django.contrib.auth.models import User from django.db import models class Chat(models.Model): product = models.ForeignKey(Product) enquirer = models.ForeignKey(User) product/models.py from django.db import models from django.contrib.auth.models import User class Product(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, related_name='category', on_delete=None) front_image = models.ImageField(upload_to="") title = models.CharField(max_length=100) price = models.PositiveIntegerField() description = models.CharField(max_length=5000) date = models.DateTimeField(auto_now_add=True) settings.py INSTALLED_APPS = [ 'account.apps.AccountConfig', 'product.apps.ProductConfig', 'profileInfo.apps.ProfileInfoConfig', 'chat.apps.ChatConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', ] The error is the following: ModuleNotFoundError: No module named 'api.product' I do not understand why Django even can not find api.product. Is that a common problem ? Thank you for your help. -
Websocket gets disconnected several seconds later after handshake in django Channels 2
WebSocket gets disconnected in django channels2. And before it following error was thrown. 2018-06-03 19:05:40,238 - ERROR - server - Exception inside application: [Errno -2] Name or service not known File "/usr/lib/python3.5/asyncio/tasks.py", line 241, in _step result = coro.throw(exc) File "/home/lusine/projects/DjangoTest/venv/lib/python3.5/site-packages/channels/consumer.py", line 54, in call await await_many_dispatch([receive, self.channel_receive], self.dispatch) File "/home/lusine/projects/DjangoTest/venv/lib/python3.5/site-packages/channels/utils.py", line 57, in await_many_dispatch await task File "/usr/lib/python3.5/asyncio/futures.py", line 363, in iter return self.result() # May raise too. File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result raise self._exception File "/home/lusine/projects/DjangoTest/venv/lib/python3.5/site-packages/channels/utils.py", line 49, in await_many_dispatch result = task.result() File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result raise self._exception File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step result = coro.send(None) File "/home/lusine/projects/DjangoTest/venv/lib/python3.5/site-packages/channels_redis/core.py", line 184, in receive self.receive_loop_task.result() File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result raise self._exception File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step result = coro.send(None) File "/home/lusine/projects/DjangoTest/venv/lib/python3.5/site-packages/channels_redis/core.py", line 202, in receive_loop real_channel, message = await self.receive_single(general_channel) File "/home/lusine/projects/DjangoTest/venv/lib/python3.5/site-packages/channels_redis/core.py", line 218, in receive_single async with self.connection(index) as connection: File "/home/lusine/projects/DjangoTest/venv/lib/python3.5/site-packages/channels_redis/core.py", line 447, in aenter self.conn = await aioredis.create_redis(**self.kwargs) File "/home/lusine/projects/DjangoTest/venv/lib/python3.5/site-packages/aioredis/commands/init.py", line 177, in create_redis loop=loop) File "/home/lusine/projects/DjangoTest/venv/lib/python3.5/site-packages/aioredis/connection.py", line 107, in create_connection timeout, loop=loop) File "/usr/lib/python3.5/asyncio/tasks.py", line 373, in wait_for return (yield from fut) File "/home/lusine/projects/DjangoTest/venv/lib/python3.5/site-packages/aioredis/stream.py", line 19, in open_connection lambda: protocol, host, port, **kwds) File "/usr/lib/python3.5/asyncio/base_events.py", line 651, in … -
how to deserialize data from jquery/ajax in django view
I want to deserialize the this data csrfmiddlewaretoken=5U9Fgv8Gdmft6wU1zwPJlRxwIsXHaElfvKTtqkT2HtzWc6uNqFq1AeogAOkIjWb5&title=jstree+inline+HTML+demo&ubc=1&company-name=teste&company-cnpj=222.222.222-22&company-email=teste%40gmail.com but when I try json.loads(data) or data.json() I get this error raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) -
TypeError at /accounts/register/ __init__() got an unexpected keyword argument 'instance'
When trying to register a user with the custom user model in Django 2.0, I get the following error. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/accounts/register/ Django Version: 2.0.5 Python Version: 3.6.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'homepage', 'account'] Installed 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'] Traceback: File "C:\Users\mittr\Desktop\MLASSI~1\mom\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\mittr\Desktop\MLASSI~1\mom\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\mittr\Desktop\MLASSI~1\mom\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mittr\Desktop\MLASSI~1\mom\lib\site-packages\django\views\generic\base.py" in view 69. return self.dispatch(request, *args, **kwargs) File "C:\Users\mittr\Desktop\ML Assignments\mom\src\account\views.py" in dispatch 39. return super(RegisterView, self).dispatch(*args, **kwargs) File "C:\Users\mittr\Desktop\MLASSI~1\mom\lib\site-packages\django\views\generic\base.py" in dispatch 89. return handler(request, *args, **kwargs) File "C:\Users\mittr\Desktop\MLASSI~1\mom\lib\site-packages\django\views\generic\edit.py" in get 168. return super().get(request, *args, **kwargs) File "C:\Users\mittr\Desktop\MLASSI~1\mom\lib\site-packages\django\views\generic\edit.py" in get 133. return self.render_to_response(self.get_context_data()) File "C:\Users\mittr\Desktop\MLASSI~1\mom\lib\site-packages\django\views\generic\edit.py" in get_context_data 66. kwargs['form'] = self.get_form() File "C:\Users\mittr\Desktop\MLASSI~1\mom\lib\site-packages\django\views\generic\edit.py" in get_form 33. return form_class(**self.get_form_kwargs()) Exception Type: TypeError at /accounts/register/ Exception Value: __init__() got an unexpected keyword argument 'instance' Urls.py path('register/', RegisterView.as_view(), name='register'), views.py class RegisterView(CreateView): form_class = UserRegistrationForm template_name = 'registration/register.html' success_url = '/' def dispatch(self, *args, **kwargs): if self.request.user.is_authenticated: return redirect('/login') else: return super(RegisterView, self).dispatch(*args, **kwargs) Forms.py class UserRegisterForm(forms.ModelForm): password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Email'})) password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Email'})) class Meta: model … -
Django channels custom routing doesn't work
i'm trying to add custom routing and consumer, but on sending request it does nothing. Seems it can't see consumer. Routing.py channel_routing = [ route("websocket.connect", ws_add, path=r"^/some-data/(?P<table_id>[a-zA-Z0-9_]+)/$"), route("websocket.receive", ws_message, path=r"^/some-data/(?P<table_id>[a-zA-Z0-9_]+)/$"), route("websocket.disconnect", ws_disconnect, path=r"^/some-data/(?P<table_id>[a-zA-Z0-9_]+)/$"), #THIS ONE DOESN'T WORK route("queue", msg_consumer, path=r"^/test/$"), ] consumers.py def msg_consumer(message): print('testing') # And i'm adding it to Group Group("queue-%s" % room).send({ "text": message.content['message'], }) my js socket = new WebSocket("ws://" + window.location.host + '/test/'); socket.onopen = function() { socket.send(JSON.stringify({ text: "test" })); } // Call onopen directly if socket is already open if (socket.readyState == WebSocket.OPEN) socket.onopen(); First Consumers work fine but last one not. -
django query - show new players count grouped monthwise
I am trying to create a dashboard in django for a gaming site. I need to show a monthly "new players who joined game" graph. I am already getting total players, and players joined in current month and last 7 days using the following code: queryset = Players.object.all() current_year = datetime.now().year current_month = datetime.now().month one_week_ago = datetime.today() - timedelta(days=7) count['players_all'] = queryset.count count['players_current_month'] = queryset.filter(joined__month=current_month, created_at__year=current_year).count count['players_last_seven_days'] = queryset.filter(joined__gte=last_seven_days).count Now I want to add a new dict which will show me count of players who joined last 12 months, grouped by month. Something like: count['players_last_twelve_months'] = get_players_last_twelve_months() Then I want to define this function get_players_last_twelve_months() such that it will return something like: { Jul:12 Aug:15 Sept:9 Oct:22 Nov:11 Dec:7 Jan:14 Feb:19 Mar:20 Apr:12 May:25 Jun:8 } I am very new to python and django. Using my minimal knowledge I know I can use variations of the queryset.filter I used above like. queryset.filter(joined__month=11, current_year = 2017) queryset.filter(joined__month=12, current_year = 2017) queryset.filter(joined__month=1, current_year = 2018) queryset.filter(joined__month=2, current_year = 2018) However I dont want to hardcode month numbers etc. Can anyone provide me some pointers on the proper way to try to achieve this? -
error in django and angular 4 No 'Access-Control-Allow-Origin' header is present on the requested resource.
here is my django code I get this error when i test my delete function. and this is the error that given when i test. thanks. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access. The response had HTTP status code 500. def delete(self): ''' Deletes an existed file or folder. ''' file = self.request.GET.get('path').lstrip("/") path = os.path.join(self.root,file) response = FileManagerResponse(path) response.set_response() if (self.is_safe_path(path)): if os.path.isdir(path): shutil.rmtree(path) elif os.path.isfile(path): os.remove(path) return JsonResponse(response.response) else: return self.fileManagerError(path=file) here is my angular 4 code deleteFile(id) { let url = `http://127.0.0.1:8000/files/connectors/python/filemanager?time=1528047056540&mode=delete&path=${id}&_=1528045987217`; console.log(url); return this.http.get(url); } -
django 2.0 form render
I heve a problem w/ django rendering forms. In a project im using django 2.0.5 and python 3.6.4 When i want to render simple form which just heve to take url but for some reason it dose not appear on a final web page <form action="/videoConverter/" method="get"> {{ form }} <input type="submit" value="Submit"/> </form> Here is form.py file from django import forms class videoUrlExtract(forms.Form): video_info = forms.CharField(label='Video URL:', max_length=200) I think problem in the diference of django from tuturial and django which i use tutorial it in russian but u can read code sorry for my spelling -
Django(2.0.6): update m2m related objects in signals
I was kind of trying to get updated related objects list from m2m field E.g. I have following models class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField(default='N/A') price = models.DecimalField(decimal_places=2, max_digits=20, default=10.00) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) category = models.CharField(blank=True, max_length=20, choices=CATEGORIES) size = models.CharField(max_length=100, choices=AVAILABLE_SIZE, blank=True) choice = models.CharField(max_length=100, choices=AVAILABLE_CHOICE, blank=True) objects = ProductManager() def get_absolute_url(self): return "/products/{slug}/".format(slug=self.slug) def __str__(self): return self.title class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=True) products = models.ManyToManyField(Product, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = CartManager() def __str__(self): return str(self.id) Now I update my "products" field via django admin by just removing and adding items. So I expect that the signal below, will print updated product (which I have just added/removed ). However, I'm still getting all the products (all products from Product model) def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs): if action == 'post_add' or action == 'post_remove' or action == 'post_clear': print(action) products = instance.products.all() print(products) total = 0 for x in products: total += x.price if instance.subtotal != total: instance.subtotal = total instance.save() m2m_changed.connect(m2m_changed_cart_receiver, sender=Cart.products.through) I'm new to django, anyone … -
Slug is always None Django
I'm trying to implement a Top-rated list of Books in my Django project (e-commerce bookstore). The problem is that I have a two pretty much the same view functions for list of "all books" and for "top-rated books", and when I switching between genres of books on my template, the list of related books is not refreshing correctly because genre_slug is always of type None. Note: the template code for both lists is the same views.py def book_list(request, genre_slug=None): cart = Cart(request) genre = None genres = Genre.objects.all() books = Book.objects.all() print(genre_slug) if genre_slug: genre = get_object_or_404(Genre, slug=genre_slug) books = genre.book_set.filter(available=True) return render(request, 'store/book/list.html', locals()) def book_list_top_rated(request, genre_slug=None): cart = Cart(request) genre = None genres = Genre.objects.all() books = Book.objects.get_queryset().none() print(genre_slug) if genre_slug: genre = get_object_or_404(Genre, slug=genre_slug) for book in genre.book_set.filter(available=True): if book.average_rating() is not None: if book.average_rating() >= 2: books = books | genre.book_set.get_queryset().filter(name=book.name) else: for book in Book.objects.get_queryset().filter(available=True): if book.average_rating() is not None: if book.average_rating() >= 2: books = books | Book.objects.get_queryset().filter(name=book.name) return render(request, 'store/book/top_list.html', locals()) urls.py urlpatterns = [ path('', views.index, name='index'), path(r'reviews/', views.review_list, name='review_list'), path(r'book_list/', views.book_list, name='book_list'), re_path(r'top/', views.book_list_top_rated, name='book_list_top_rated'), re_path(r'^(?P<genre_slug>[-\w]+)/top/$', views.book_list_top_rated, name='book_list_top_rated'), re_path(r'^(?P<genre_slug>[-\w]+)/$', views.book_list, name='book_list_by_genre'), re_path(r'^(?P<id>\d+)/(?P<slug>[-\w]+)/$', views.book_detail, name='book_detail'), re_path(r'^review/(?P<review_id>[0-9]+)/$', views.review_detail, name='review_detail'), re_path(r'^book/(?P<book_id>[0-9]+)/add_review/$', views.add_review, name='add_review'), ] … -
Python from django.contrib.auth.views import logout ImportError: cannot import name 'logout'
I have configured my python env with python 3.5, but I am getting the following error when I run my server with the command python manage.py runserver from django.contrib.auth.views import logout ImportError: cannot import name 'logout' this is my config dj-database-url==0.5.0 Django==2.1a.1 gunicorn==19.8.1 numpy==1.14.3 psycopg2==2.7.4 pytz==2018.4 whitenoise==4.0b4 I tried reinstalling my env and changing python version but issue stills happening. Thanks for your questions guys -
Directly Sending User to ?page=2
I have a webpage from which I'm sending user to another page. . Content for more data please visit, <a href="{% url 'data:more' data.id %}">See more</a> Means when user clicks on See more, he/she goes to another webpage with URL www.website.com/1/ But, on that page (www.website.com/1/) i'm using django pagination. So, I want to send user to the www.website.com/1/?page=2 page directly instead of first one www.website.com/1/. How can I do that? Thank You . . . -
How to import contents of an external CSS into Django template directly?
I have a CSS file and I'm importing it to the page like below: <html> <head> <link rel="stylesheet" href="{% static 'css/common.css' %}" /> </head> <body> Hello world. </body> </html> I want to import CSS file's contents into the template directly. After this process, template should look like this: <html> <head> <style type="text/css"> /* this is the contents of common.css */ body{ background: black; } </style> </head> <body> Hello world. </body> </html> Maybe there is a template filter or something like that. How can I do this? -
existing django module name clashes with new pip package
I already had a module inside my django project called (let's say) abcxyz. Now after several months into the project, i came across a new pip package which might be useful for some new features that we are thinking of. Unfortunately, it's registered in PyPI as abcxyz also - conincidence, huh? After installing this new found package via pip install abcxyz, now when i try to import the package by using import abcxyz it ends up importing the existing abcxyz module (which i already had in my django project for months) and not the new package that i just installed. How do i resolve this issue? Is there any way i could install the PyPI package under a different name in my project since i already have that name being used for an existing module? -
vuejs v-for with django not working for dynamic data
I am implementing a table using vuejs + django. When I am declaring row and column statically, it is working. but when I am taking the value from django, it is not working anymore, though it is printing correct value. My HTML code looks like {% verbatim %} <div class="col-9"> <label><h4>Position</h4></label> col: {{tableCols}} : row: {{tableRows}} (here it is printing correct value) <table> <tr v-for="row in tableRows"> <td v-for="col in tableCols" v-bind:class="{selected: selectedData === counter(row,col)}" v-on:mousedown="mouseDown(counter(row,col))" v-on:mouseover="mouseOver(counter(row,col))" v-on:mouseup="mouseUp" > {{rowName[row-1]}}:{{col}}:{{counter(row,col)}} </td> </tr> </table> </div> <input type="hidden" name="containerIDs" v-model="selectedData"> {% endverbatim %} and vuejs code looks like new Vue({ el: '#testtube', data: { tableCols : {{testtubeplate.number_of_columns}}, // 12, tableRows : {{testtubeplate.number_of_rows}}, //8, rowName: RowName, selectedData: [], cellNo: 0, isMouseDown:false }, methods: { ... in HTML I have printed col: {{tableCols}} : row: {{tableRows}}, which is printing right value, but only 1 row and 2 column is creating instead of 8 and 4. But if I put 12, 8 statically it is working. (pic attached) Any suggestion? Thanks in advance -
Django Watson partial search or combine with queryset
I am using Django-watson to search my model which is having title and tags field. How to enable partial search also in django-watson. If I am searching for python program it is not searching for individual words(partial matches) also. So after django-watson search I have implemented my own partial search and I want to combine django-watson returned queryset with my search queryset. I tried using union but getting error KeyError: u'"watson_searchentry"'. I need a single queryset which is having django-watson results and my partial search results because have to work with pagination and all. Or is there a way to enable partial search also in django-watson? -
Django: List of users in a model's field
I have a User model and PromoCode model. In the latter, I want to list users that have inputed and matched with one of the promocodes i put in the admin view. What field type should I use in the PromoCode model to create a list of users, to which I can add more users over time in my views? -
How do I effectively make changes to a 3rd party django app?
I am working on a Django application which uses django-leaflet, but this question applies to any python library. I want to change some django-leaflet code to see if the changes would solve a problem we are having. What are my options? Do I need to create an example app in the django-leaflet repository and preform my modify-test loop there? Or do I need to upload individual re-named versions of django-leaflet to pypi? -
How would I pass in a variable when someone submits a form without changing the URL?
I am trying to pass in a variable when someone submits a form without changing the URL. Example (views.py): if request.method == "POST": # set a variable value Example (index.html): # form here # when the user clicks submit a modal comes up, I want it to show the variable value in the body Thanks, Cameron. -
Python cannot access variable within for loop
When I test the value of employees before the for loop it shows up fine def employee_list(request): employees = Employee.nodes.order_by('name') alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',] employees_by_letter = [] # import pdb; pdb.set_trace()... employees.all() => lots of values! But when I try to use the employees value within the for loop it shows up as blank. Why? for letter in alphabet: # compare the first letter of the name to the current letter # import pdb; pdb.set_trace()... employees.all() => [] no values! employees_by_this_letter = employees.filter(name__istartswith=letter) employees_by_letter.append(employees_by_this_letter) It's all within that def employee_list function so shouldn't i be able to access that variable inside the for loop? UPDATE BY REQUEST: all code in employee_list def employee_list(request): user = request.user employees = Employee.nodes.order_by('name') alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',] employees_by_letter = [] for letter in alphabet: # compare the first letter of the name to the current letter employees_by_this_letter = employees.filter(name__istartswith=letter) employees_by_letter.append(employees_by_this_letter) import pdb; pdb.set_trace() context = { … -
Concurrency issue? Standalone python script sharing settings.py and ORM with django server has unreliable view of DB objects?
I'm having a strange problem that is difficult to reproduce (everything worked 2 days ago but some time between then and now no longer does--with no changes in the interim!) I have a django server program which we are running via gunicorn with multiple worker subprocesses and a separate small REST webservice which shares the settings.py of the server program and acts on the same DB objects. The code for this server program is roughly as follows: # my app's models.py class TestConfig(models.Model): ## various attributes class Test(models.Model): ## some attributes def startTest(self): return TestExecution.objects.create(test=self) class TestExecution(models.Model): test = models.ForeignKey( Test, on_delete=models.CASCADE ) config = models.ForeignKey( TestConfig, on_delete=models.CASCADE, null=True ) # excerpt from a post() method in my app's views.py test = Test.objects.get(test_id) if config_form.is_valid(): config = config_form.save() config_id = config.id test_exe = test.start() test_exe.config = config test_exe.save() webservice_response = requests.get( 'http://{}:{}/rest/add_to_queue/{}'.format( webservice_ip, webservice_port, test_exe.id)) The other program (small REST webservice) sharing the same settings.py as the django server program looks as follows: os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings' import django django.setup() # the REST endpoint referenced from the django server program @app.route('/rest/add_to_queue/<test_exe_object_id>/') @app.route('/rest/add_to_queue/<test_exe_object_id>') def add_to_queue(test_exe_object_id): from myapp.models import TestExecution try: exe_object = TestExecution.objects.get(pk=int(test_exe_object_id)) # for completeness the database section of my settings.py: … -
Python - Django project - DateTimeField format
i want to change the format of the Date in my Django project. now it looks like this: "June 3, 2018, 2:19 p.m.". and i want something like: "23,Oct 2018 - 18H23m". The model that i have its setting this time: date = models.DateTimeField(auto_now_add=True) How can i format the date to the way i want?Is there any other parameters that allow me to do this? i just started working with django 2 days ago, so sorry if it is a stupid question. i tried to search around but didnt find any answer. So if this topic its repeated pls tell me. Thanks in advanced! -
Why is my store.html not recognized?
These are my views def index(request): return render(request,'template.html') def store(request): return render(request,'store.html') Urls from django.contrib import admin from django.urls import path from django.conf.urls import url from store import views urlpatterns = [ url(r'^', views.index ,name='index' ), url(r'^store', views.store ,name='store' ), path('admin/', admin.site.urls), ] I have changed line in HTML Boilerplate file <p>Welcome to mystery books and store template is changed!</p> I have problem when I go runserver It does not see any difference between http://127.0.0.1:8000/store and http://127.0.0.1:8000/index Why is my other html not recognized? -
Django: how do I use object from a previous form to filter object?
def Date_Form(request): if request.method == 'POST': form = DateForm(request.POST) if form.is_valid(): date = form.cleaned_data['date'] date1 = DateOptions.objects.get(date=date) flight_date = Flight.objects.filter(date_options=date1) form1 = KeyWordForm(request.POST) return render(request, 'app/index.html',{'flight_date': flight_date, 'date': date, 'form1': form1}) else: form = DateForm() return render(request, 'app/options.html', {'form':form}) def Search_Destination(request): if request.method =='POST': form1 = KeyWordForm(request.POST) if form1.is_valid(): destination = form1.cleaned_data['destination'].capitalize() result= Flight.objects.filter(destination__icontains=destination, date_options=????) return render(request, 'app/search.html', {'result':result, 'destination':destination}) else: form1 = KeyWordForm() return render(request, 'app/searchfield.html', {'form1':form1}) This part is where I struggle: result= Flight.objects.filter(destination__icontains=destination, date_options=????) I want to be able to use the same date_option as date1. I know I can't say date_options=date1. The system won't recognize it.