Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django running on an ECS task does not work
I have some problems running Django on an ECS task. I want to have a Django webapp running on an ECS task and accessible to the world. Here are the symptoms: When I run an ECS task using Django python manage.py runserver 0.0.0.0:8000 as entry point for my container, I have a connection refused response. When I run the task using Gunicorn using gunicorn --bind 0.0.0.0:8000 my-project.wsgi I have no data response. I don't see logs on CloudWatch and I can't find any server's logs when I ssh to the ECS instance. Here are some of my settings related to that kind of issue: I have set my ECS instance security groups inbound to All TCP | TCP | 0 - 65535 | 0.0.0.0/0 to be sure it's not a firewall problem. And I can assert that because I can run a ruby on rails server on the same ECS instance perfectly. In my container task definition I set a port mapping to 80:8000 and an other to 8000:8000. In my settings.py, I have set ALLOWED_HOSTS = ["*"] and DEBUG = False. Locally my server run perfectly on the same docker image when doing a docker run -it -p 8000:8000 … -
I'm getting error "local variable 'form1' referenced before assignment"
I'm getting an error "local variable 'form1' referenced before assignment" This is my views.py and I'm unable to figure this out. I'm a noob in django. Any type of help is appreciated. def getview(request): formObject = form_input() formObject.orign = None formObject.destinations = None formObject.timeWindow = None if request.method == 'POST': formData = ro_input_form(request.POST) if formData.is_valid(): formObject.orign = request.POST.get('orign') formObject.destinations = request.POST.get('destinations') formObject.timeWindow = request.POST.get('timeWindow') formObject.save() return HttpResponse(status=200) else: form1 = ro_input_form() ## this should be forminput return render(request, 'inputform.html', {'form1': form1}) -
Run MySQL queries for Chatterbot
I've built a chatterbot application and did integration with django. My DB being MySQL, changed settings.py, added MySQL details and performed 'python36 manage.py makemigrations'. Now I want my chatbot to query tables from the mysql and reply to user. Can you please suggest me some learning path or can you please let me know how do I achieve it? . PS: My Chatbot is able to pick response from the text file and reply to user. Now I'm trying to make it interact with Database directly. Regards, Hari -
Upload files from django-admin panel to a specific server address and host?
I have a VPS , and on this VPS I installed WAMP SERVER , I have installed Django and run django-admin panel for this vps . When i upload filed using django-admin panel it goes to directory like this : http://someip:8000/media/pic.jpg But I want to upload files from django-admin panel to WWW Directory of WAMP SERVER in the same VPS . So I want to access files like this : http://someip/pictures/pic.jpg Any suggestion will be helpfull . Thank you All . -
subpages in django not rendering
so I have my site setup so the admin can create and edit pages and subpages everything is working where the super user can create pages in form something.com/page but when new page of form something.com/page/subpage/ is created through admin site 404 error is rendered. Should I create a new app called subpages and try and make subpages through that or is there a way to do it originally in my pages app. #views.py def index(request, pagename): pagename = '/'+ pagename pg = get_object_or_404(Page, permalink= pagename) pg = Page.objects.get(permalink=pagename) context = { 'title': pg.title, 'content':pg.bodytext, 'last_updated':pg.update_date, 'page_list': Page.objects.all(), } # assert False return render(request,'pages/page.html',context) #pages.urls.py urlpatterns= [ #path('',views.index,name='index'),path path('',views.index,{'pagename':''},name='home'), path('contact',views.contact,name='contact'), path('<str:pagename>', views.index, name='index'), path('trips/<str:pagename>',views.subPage, name = 'subpages' ), ] #urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), ] error message Exception Type: DoesNotExist at /trips/trip1 Exception Value: Page matching query does not exist. -
How to push all error messages generated in Django form into an array?
So, i am trying to get a list of validation errors raised in Django form into an array. What is the best method to do this? -
SMS/Text backend in Django
I want to create a backend for sending SMS/Text like the EmailBackEnd I can accomplish the task of sending SMS just fine but the trouble is testing. I can test how many email's are sent during the tests using django.core.mail.outbox I want to do something similar for SMS say sms.smsoutbox so how would I go about writing something like this for Django. I understand that email outbox resides in the localmemory for the duration of a single test so what I may be asking is that how do you put something in localmemory for the duration of a test. Thanks already. -
"No module named Django" Problem on MacOS Mojave
I'm using Python3.7.1 and Django 2.0 has been installed successfully through pip3 command on Terminal on MacOS Mojave. Pip list indicates that there is actually an installed Django on my computer. However, when I run the code import django, an error is raised: ModuleNotFoundError: No module named django. I've tried reinstall django through pip but everything stays the same. Other packages like matplotlib, xlrd and etc. installed by pip3 are all imported successfully. This is really confusing me. -
Django: didn't return a HttpResponse object error
I am trying to make a Post form, but HttPResponse occurs.In my code, there is a redirect method, and I think it is considered as a httpresponse, isn't it? I am just a engineer, so if someone could find an easy mistake, I would appreciate from django.shortcuts import render,redirect from .forms import DayCreateForm def index(request): return render(request,'diary/day_list.html') def add(request): form = DayCreateForm(request.POST or None) if request.method == 'POST'and form.is_valid(): form.save() return redirect('diary:index') context ={ 'form':form } return render(request,'diary/day_form.html',context) -
Dose Django or wsgi app init every time with a new connection in deployment env?
I mean, if I store a global int in a Django project's memory and modify/view it, this is OK with manage.py runserver. However, will this still work in deployment environment? I am not sure how production web server(apache or uwsgi) will use my code. Will this app initialed many times in different processes? -
Python doesn't accept my input, what I'm I doing wrong?
I'm creating code for the mastermind game and I think that everything should be perfect, but when I try to write the info needed by the first input (in this case, the colors like "R", it doesn't matter what I do that will jump directly to print ("You have to introduce four colours, no more, no less! ") Can anyone help me please??? Here's the code: colours=["R", "G", "B", "Y", "W", "R", "P"] attempts=0 game=True codemaker=random.sample(colours,4) print (codemaker) while game: white_points=0 black_points=0 guessed_colour="" player_guess=input().upper() attempts+=1 if len(player_guess) != len(codemaker): print ("You have to introduce four colours, no more, no less! ") continue -
Web based database to view product information, best technology to use
I want to build an online database of all of our product sku's, descriptions, prices, costs etc. I want the sales people to be able to login and check our costs. I need to be able to upload the data from CSV or excel files. I like to use Python, what would the best technology stack/framework to use to accomplish it? I was thinking django, or flask? -
Filter number of polygon inside polygon in Geoqueryset Django
I have 2 Models "Building" and "Flood", both are in srid 32651 My purpose are want to calculate how many building get hits by flood, I use : affected = Building.objects.filter(geom__within=Flood.geom) but somehow I get "object with type SpatialProxy for a spatial lookup parameter" , Is there something wrong with this? -
How do I add the file used to import data with django-import export?
I am using django-import-export to allow my app's users to import their own data to the database. I have created the appropriate resource with the fields that are needed. It works as it should. What I am trying to do next is add the used file alongside the users imported data, so I can show the users their imported files and their info. I am not saving the files to my server, just processing them. Firstly, I have created a new model called FileImported to hold the info for the file used for the import: class FileImported(models.Model): filename = models.CharField() name = models.CharField() size = models.DecimalField() extension = models.CharField() date = models.DateField(auto_now_add=True) time = models.TimeField(auto_now_add=True) timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) def __str__(self): return self.filename Then I had to pass the file info: result = imported_bet_resource.import_data(dataset, dry_run=True, raise_errors=False, file_name=import_file_name, user=self.request.user, file_size=import_file_size, file_extension=import_file_extension) After that, I create a new FileImported model object before importing: class ImportedResource(resources.ModelResource): ......... def before_import(self, dataset, using_transactions, dry_run, **kwargs): file_name = kwargs.get('file_name', 'unknown') name = os.path.splitext(file_name)[0] file_size = kwargs.get('file_size', 'unknown') file_extension = kwargs.get('file_extension', 'unknown') user = kwargs.get('user', 'unknown') file_name_model_object = FileImported .objects.get_or_create(filename=file_name, name=name, size=file_size, extension=file_extension, user=user) I have added the following fields to my model: … -
Django, ModuleNotFoundError: No module named 'django_pg'
Can someone provide more details on setting up and utilizing django_pg. I would like to use the array functionality. By following the setup of two simple steps from here: https://django-pgfields.readthedocs.io/en/latest/usage.html Results in this error: (environment) jeff@jeff-computer:~/environment/projectA$ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/jeff/environment/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/jeff/environment/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/jeff/environment/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/jeff/environment/lib/python3.7/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/jeff/environment/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/jeff/miniconda3/lib/python3.7/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 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_pg' -
Django Postgres search with TrigramSimilarity
If I use 'title' in my post_search function it works perfectly. Post.objects.annotate( similarity=TrigramSimilarity('title', query) ).filter(similarity__gt=0.1).order_by('-similarity') Although if I try to search in 'body' instead of 'title', I'm getting 0 results. Post.objects.annotate( similarity=TrigramSimilarity('body', query) ).filter(similarity__gt=0.1).order_by('-similarity') It is supposed to work perfectly as if I look into TrigramSimilarity documentation the keyword choices are: author, author_id, body, comments, created, id, publish, slug, status, tagged_items, tags, title, updated. Has anybody experienced anything like this? -
Django NoReverseMatch- cannot figure out why it is raising this
Why is Django returning a NoReverseMatch? I am trying to have my app redirect the user when it detects that the user trying to edit a post is not the post's author. However, Django returns a NoReverseMatch when i try to do this. URLs: path('new/', views.NewPost, name='NewPost'), path('post/<int:pk>/edit/', views.editPost, name='editPost'), path('post/<int:pk>/delete/', views.deletePost, name='deletePost'), path('post/<int:pk>/comment/', views.commentPost, name='commentPost'), path('post/<int:pk>/<str:slug>/', views.viewPost, name='viewPost'), View: def editPost(request, pk): if request.method == 'GET': post = get_object_or_404(Post, pk = pk) if post.author == request.user: form = PostForm(instance = post) return render(request, 'editPost.html', {'form': form, 'post': post}) else: return redirect('viewPost',pk = pk, postURL : post.postURL) -
Trouble Getting User Input in Django
I'm newbie and trying to do something pretty basic after reading the Django Doc Project Documentation, but can't seem to figure it out. I'm getting a user's name with a POST and trying to GET it and display it on the same page. I'm getting an error: hello() missing 1 required positional argument: 'greeting_id' I'm using Django 2 and wondering if it could be something with the routing? I'm not exactly sure as I'm very new to MVC and Django. Any help in the right direction would be greatly appreciated. Here's my code so far: Views.py from django.shortcuts import render from django.http import HttpResponse from .models import Greeting # create hello view def hello(request, greeting_id): if request.method == 'POST': if request.POST['firstname']: greeting = models.Greeting() greeting.firstname = request.POST['firstname'] greeting.save() obj = models.Greeting.objects.get(pk=greeting_id) context = { 'object': obj } return render(request, 'greetings/home.html', context) return render(request, 'greetings/home.html') Models.py from django.db import models # Create your models here. class Greeting(models.Model): firstname = models.CharField(max_length=100) # returns post object in admin interface def __str__(self): return self.firstname urls.py from django.contrib import admin from django.urls import path from greetings import views #import greetings views into the url file urlpatterns = [ path('admin/', admin.site.urls), path('hello/', views.hello, name='hello'), ] home.html … -
Django. How can I prevent another user from editing and deleting my listings?
Please help me implement these features so that another user cannot delete or edit my ads. @login_required def listing_delete(request, listing_id): listing = Listing.objects.get(id=listing_id) listing.delete() return redirect('index') @login_required def listing_edit(request, listing_id): form = ListingForm(instance = Listing.objects.get(id = listing_id)) if request.method == "POST": form = ListingForm(request.POST, request.FILES, instance = Listing.objects.get(id = listing_id)) if form.is_valid(): listing = form.save() return redirect('listing', listing_id) return render(request, 'listings/listing_edit.html', {'form': form}) -
How do I add a string to a Django template?
I want to take this piece of code... <section data-name="color1" data-type="color" data-order="2" style="color:{{ block.color1|default:"inherit" }}"> Which by default outputs this tag in the html... <section data-name="color1" data-type="color" data-order="2" style="color: rgb(0, 0, 0);"> Because of a color conflict on one of my child elements, the color of the block.color1 variable isn't being applied. I'd like to add an "!important" to the inline CSS's output to counter this issue. In other words, I want an output of <section data-name="color1" data-type="color" data-order="2" style="color: rgb(0, 0, 0) !important;"> in the HTML. What can I add to Django to ensure I receive an output with !important in the CSS? -
Expected str instance, BoundField found (Django)
Django version: 2.0 python: 3.7 jquery : 3.3.1 bootstrap: 3.3.7 I am implementing ajax to my django forms. For that I was following this tutorial. However I am getting a strange error when I click new book button or update button. "Expected str instance, BoundField found" Instead of opening a modal, only a small line is displayed. urls.py urlpatterns = [ path('book_list/', views.book_list, name='book_list'), path('book/create/', views.create_book, name='book_create'), path('<int:pk>/book/update/', views.book_update, name='book_update'), path('<int:pk>/book/delete/', views.book_delete, name='book_delete'), ] form.py class EducationForm(forms.ModelForm): class Meta: model = Education fields = ['degree','school','edu_start_date','edu_end_date'] Views def save_book_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True books = Education.objects.all() data['html_book_list'] = render_to_string('profile_settings.html', request, { 'books': books }) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def create_book(request): if request.method == 'POST': form = EducationForm(request.POST) else: form = EducationForm() return save_book_form(request, form, 'partial_book_create.html') def book_list(request): books = Education.objects.all() return render(request, 'book_list.html', {'books': books}) Templates partial_book_form.html {% load widget_tweaks %} {% for field in form %} <div class="form-group{% if field.errors %} has-error{% endif %}"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {% render_field field class="form-control" %} {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} … -
ManyToMany slow in Django
I have two simple models: class A(models.Model): name_a = models.CharField( _("name_a"), max_length=255) b = models.ManyToManyField( 'B', related_name='b', blank=True ) class B(models.Model): name_b = models.CharField( _("name_b"), max_length=255) I created 1000 records for A: for i in range(1000): A.objects.create() and 3 objects for B: for i in range(3): B.objects.create() and connect each Object of b with each object of a through the m2m relation: for a in A.objects.all().iterator(): a.b.add(B.objects.all()[0]) a.b.add(B.objects.all()[1]) a.b.add(B.objects.all()[2]) Now for each a object, I want to get all b objects: import time start = time.time() objects = A.objects.all() for n in objects.iterator(): list(n.b.all()) print(time.time() - start) Output: 2.642864465713501 So it takes over 2 seconds for this query for just 1000 a objects. The performance is horrible. I have over 1000000 a objects in production. I tried to increase the performance by using prefetch_related: import time start = time.time() objects = A.objects.all().prefetch_related('b') for n in objects.iterator(): list(n.b.all()) print(time.time() - start) Output: 2.684298038482666 But that helps nothing. Why is it so slow and how can I improve the performance? -
badly formed hexadecimal UUID error string for a UUID primary key
I'm trying to get my table to load, but am getting this error, most likely because my primary key is a uuid. Here is my url paths. path('results/', views.results, name='results'), path('results/<uuid:pk>/', views.genre_book, name='books_genre_table'), Here is my views.py If there is one observation, we load the price table. If not, then we load a table with service descriptions. The user can then pick the service they are most interested and click through to the price table for that service. This is not working. The first view "results" works, but the second view book_genre does not. def results(request): query_string = '' found_entries = None if ('s' in request.GET) and request.GET['s'].strip(): query_string = request.GET['s'] entry_query = get_query(query_string,['service__desc_us', 'com_desc']) _objs = Price.objects.filter(entry_query).values('service__join').distinct() num_obj = Price.objects.filter(entry_query).values('service__join').distinct().count() if num_obj == 1: Price_objs = Price.objects.filter(entry_query).order_by("price_offer") table = PriceTable(Price_objs) RequestConfig(request).configure(table) if num_obj > 1: model = Service entry_query = get_query(query_string,['desc_us', 'price__com_desc']) serv_obj = Service.objects.filter(entry_query).distinct() table = ServiceTable(serv_obj) RequestConfig(request).configure(table) return render(request, 'results.html', {'table': table}) def genre_book(request, pk): serv_obj = Service.objects.get(pk=pk) price_obj = Price.objects.filter(service=serv_obj).values("join") table = PriceTable(price_obj) RequestConfig(request).configure(table) return render(request, 'results.html', {'table': table}) Here is my tables.py file class PriceTable(tables.Table): class Meta: model = Price template_name = 'django_tables2/bootstrap4.html' ... class ServiceTable(tables.Table): desc_us = tables.LinkColumn('books_genre_table', args=[A('pk')]) class Meta: model = Service … -
Editing a Django login view
I'm trying to add 2fa to my Django project, and for that i'm using this library. I'm studying their example, in order to undestand. I'm taking a look at the login part, but there is something i don't understand: the example does not have a login view. It just calls the module's login view, see below: <li><a href="{% url 'two_factor:login' %}">{% trans "Login" %}</a></li> The login view is here. This is what i don't undestand: how can i edit the view? What if, for example, i would like to add another field to the login? How can i edit the view, since i'm not using my login view but the library's login view? -
Hue Install From Tarball Failure
After running PREFIX=/home/hue make install Towards the end of my hue install via tarball, I get the following error. I'm not sure what is happening. I have the prerequisites installed as well. Using this guide === Installing app at zookeeper Updating registry with zookeeper v.4.3.0 Running 'make -C /home/hue/hue/apps/zookeeper egg-info ext-eggs' with {'ROOT': '/home/hue/hue'} make[2]: Entering directory `/home/hue/hue/apps/zookeeper' make[2]: Nothing to be done for `egg-info'. make[2]: Nothing to be done for `ext-eggs'. make[2]: Leaving directory `/home/hue/hue/apps/zookeeper' === Saved registry at /home/hue/hue/app.reg === Saved /home/hue/hue/build/env/lib/python2.7/site-packages/hue.pth Running '/home/hue/hue/build/env/bin/hue makemigrations --noinput' with None Traceback (most recent call last): File "/home/hue/hue/build/env/bin/hue", line 11, in <module> load_entry_point('desktop', 'console_scripts', 'hue')() File "/home/hue/hue/desktop/core/src/desktop/manage_entry.py", line 216, in entry execute_from_command_line(sys.argv) File "/home/hue/hue/build/env/lib/python2.7/site-packages/Django-1.11-py2.7.egg/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/hue/hue/build/env/lib/python2.7/site-packages/Django-1.11-py2.7.egg/django/core/management/__init__.py", line 307, in execute settings.INSTALLED_APPS File "/home/hue/hue/build/env/lib/python2.7/site-packages/Django-1.11-py2.7.egg/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/hue/hue/build/env/lib/python2.7/site-packages/Django-1.11-py2.7.egg/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/hue/hue/build/env/lib/python2.7/site-packages/Django-1.11-py2.7.egg/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/hue/hue/desktop/core/src/desktop/settings.py", line 271, in <module> conf.initialize(_desktop_conf_modules, _config_dir) File "/home/hue/hue/desktop/core/src/desktop/lib/conf.py", line 598, in initialize conf_data = load_confs(_configs_from_dir(config_dir)) File "/home/hue/hue/desktop/core/src/desktop/lib/conf.py", line 530, in load_confs for in_conf in conf_source: File "/home/hue/hue/desktop/core/src/desktop/lib/conf.py", line 511, in _configs_from_dir conf = ConfigObj(os.path.join(conf_dir, filename)) File "/home/hue/hue/build/env/lib/python2.7/site-packages/configobj-5.0.6-py2.7.egg/configobj.py", line 1229, in __init__ …