Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tensorflow error while deploying Django app to Heroku
I am trying to deploy my application developed in Django to Heroku and getting the following errors: > File > "/app/.heroku/python/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", > line 58, in <module> > from tensorflow.python.pywrap_tensorflow_internal import * File "/app/.heroku/python/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "/app/.heroku/python/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "/app/.heroku/python/lib/python3.6/imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "/app/.heroku/python/lib/python3.6/imp.py", line 343, in load_dynamic return _load(spec) ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "chatbot_website/manage.py", line 22, in execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/init.py", line 341, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/app/.heroku/python/lib/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "/app/chatbot_website/chatbot_interface/chatbotmanager.py", line 15, in from chatbot import chatbot File "/app/chatbot/chatbot.py", line 26, in … -
django : create table form when selecting multiple rows
I need to create a pretty straight forward form with Django but seems to be unable to find the proper tool for it, maybe because of the lack of vocabulary on what I want : I have a table of n rows, each row represents a database object. I want to put a checkbox in front left of each row to be able to select multiple rows and apply an action placed in a multiplechoice widget at the top. I thought about "serialize" a deleteview with formset but anyway I don't know how to add extra actions (apart from delete). Any valuable information on direction to take would be welcome, thanks. -
django updating model issues
I have a babysitter app I am working on. I can add and update the parent to the parent model with no problem. I can create and delete a kid but when I try to update a kid I get the following error. What am I doing wrong? I have been looking through examples and similar queries on this site but I still cant get it to work. urls.py from django.conf.urls import url from .views import register, profile, logout, login, update_profile, update_profile_kid, create_profile_kid, delete_profile_kid urlpatterns = [ url(r'^register/$', register, name='register'), url(r'^profile/$', profile, name='profile'), url(r'^profile/update/$', update_profile, name='update_profile'), url(r'^profile/kids/update/(?P<id>\d+)$', update_profile_kid, name='update_profile_kid'), url(r'^profile/kids/delete/(?P<id>\d+)$', delete_profile_kid, name='delete_profile_kid'), url(r'^profile/kids/create/$', create_profile_kid, name='create_profile_kid'), url(r'^logout/$', logout, name='logout'), url(r'^login', login, name='login'), ] profile.html {% extends "base.html" %} {% load static %} {% load gravatar %} {% block content %} <section class="container-fluid"> <div class="page-header text-center"> <h1>Client Dashboard</h1> </div> <div class="container-fluid"> <div class="row"> <div class="col-md-12 col-lg-4 text-center"> <p class="lead">Welcome <b>{{user.first_name}}</b></p> <img class="rounded-circle profile-image my-2 img-fluid" src="{{ MEDIA_URL }}{{user.profile.image}}" alt="{{user.username}}"> <br> <div class="text-center"> <a href="" class="btn btn-default btn-rounded mb-4" data-toggle="modal" data-target="#modalRegisterForm">Edit Profile</a> <ul class="list-group"> <li class="list-group-item d-flex justify-content-between align-items-center"> <span><i class="fas fa-user-alt fa-lg"></i> Name:</span> {{ user.first_name }} {{user.last_name}} </li> <li class="list-group-item d-flex justify-content-between align-items-center"> <span><i class="fas fa-map-marker-alt fa-lg"></i> Address</span> {{ user.profile.address1 }}, {{ … -
Django FormView to redirect to a URL generated from the form input
I've been trying to write a view in Django for this purpose but nothing has worked yet, so I'm not sure what the right approach is. Basically i want to have one page /request with the fields string1 and string2 and a button 'submit' And after submitting it redirects to another page results/{string1}/{string2} And i can use the two strings as variables on that page. Im running out of ideas what to try and i would be really happy if someone could help me out! -
Using Django admin interface with enumchoicefield
I'm attempting to use the Django (2.1.3) admin interface with the enumchoicefield package. All goes well with creating and executing the migration and starting Django, but when I try to add an instance to the model containing the EnumChoiceField I get: Exception Type: TypeError Exception Value: render() got an unexpected keyword argument 'renderer' Exception Location: /home/django/Env/rosella/lib/python3.5/site-packages/django/forms/boundfield.py in as_widget, line 93 Python Executable: /usr/local/bin/uwsgi Python Version: 3.5.2 Model code: from enumchoicefield import ChoiceEnum, EnumChoiceField ... class SystemStatus(ChoiceEnum): UNKNOWN = 'Unknown' OK = 'Ok' DOWN = 'Down' class Monitor(models.Model): ... status = EnumChoiceField(SystemStatus, default=SystemStatus.UNKNOWN) Question: Does enumchoicefield support the admin interface? Note: I tried doing enums using django_enumfield, but also ran into problems with the admin interface. -
Prevent html5 "required" attribute on Django required form fields
I've got a Django form with required fields, but I don't want them to render with the html required attribute because I want to control this from Javascript. How can I make the form render without the required attribute? -
Django - how to import fake data
I am looking to populate my Django database with fake data for testing. What is the best method to do this? -
How do you craete a django rest framework ListCreateAPIView?
I'm trying to implement functionality to upload a batch of records into a database using drf. This is my class in my api view. class BatchRecordModelViewSet(ListCreateAPIView): """ This is an API view to insert a batch of item counts. """ serializer_class = serializers.BatchRecordSerializer queryset = models.Record.objects.all() def create(self, request, *args, **kwargs): data = request.data some_data = request.user.profile.profile_id for rec in data: rec.update(some_data=some_data) serializer = self.get_serializer(data=data, many=True) if serializer.is_valid(): serializer.save() headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) else: return Response(status=status.HTTP_400_BAD_REQUEST) This is my serializer that I am importing: class BatchRecordSerializer(serializers.ModelSerializer): item = RecordSerializer(many=True) class Meta: model = models.Record fields = ('field1', 'field2', 'field3', etc...) -
Post and save Django variable, doesn´t work
Hi, could someone please check how should I write correctly the views.py part? if I code: from django.shortcuts import render, redirect def shifts_table(request): print(request.POST['value']) return render(request, 'shifts_table.html', {}) ...at least the page runs, but if I code like below it doesn't, any idea why? Thank you. from django.shortcuts import render, redirect from django.contrib import messages def shifts_table(request): if request.method == 'POST': number = request.POST['value'] if number.is_valid(): number.save() return redirect('shifts_table.html') else: messages.success(request, ('Seems Like There Was An Error...')) return render(request, 'home.html', {}) else: return render(request, 'shifts_table.html', {}) home.html: <form action="{% url 'shifts_table' %}" method='POST'> {% csrf_token %} <label for='number'>Number:</label> <input type="number" name="value" placeholder="2020" required><br/> <button type="submit">submit</button> </form> urls.py: urlpatterns = [ path('', views.home, name='home'), path('shifts_table', views.shifts_table, name='shifts_table'), ] -
SSL not being recognized when accessing website without www
I'm deploying the website http://www.therentalmoose.com on a VPS (digital ocean) using the stack Django 1.11 Apache mySQL I've followed certbot tutorials from digital ocean (https://www.digitalocean.com/community/tutorials/how-to-secure-apache-with-let-s-encrypt-on-ubuntu-16-04), however, I'm with the following problems. on GOOGLE CHROME, whenever I access my website WITHOUT .www (http://therentalmoose.com) it shows a unsecure display as if SSL is not configured. However, it was configured multiple times. When I reach http://www.therentalmoose.com is works normally with SSL. Also, If I use MOZILLA, it works both normally (with or without www.) I have no clue of what's going on. My apache .conf file <IfModule mod_ssl.c> <VirtualHost *:443> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, … -
TimeoutError - Traceback (most recent call last), Django-app - sending e-mails. Python
I am trying to use 'mailgun' and gmail mail to send emails from my Django application, but each time I receive an error. In my application I have the following code: settings.py EMAIL_HOST = 'smtp.mailgun.org' EMAIL_PORT = 587 EMAIL_HOST_USER = 'aaa@mg.xxx.com' EMAIL_HOST_PASSWORD = '3cda51baa5e1f38c2256f31d7fe3ddc5-3b1f59cf-26fa3063' EMAIL_USE_TLS = True then I run the command from the command line: manage.py shell [1] from django.core.mail import send_mail [2] send_mail('subject', 'body of the message', 'aaa@mg.xxx.com', [' recipient@aaa.com']) Do I use gmail, or with 'mailguna' always get the same error Error: TimeoutError Traceback (most recent call last) <ipython-input-27-4c559962ca7f> in <module>() ----> 1 send_mail('subject', 'body of the message', '###@mg.###.com', ['###@###.com']) ~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\mail\__init__.py in send_mail(subject, message, from_email, recipient_list, fail_silently, auth_user, auth_password, connection, html_message) 58 mail.attach_alternative(html_message, 'text/html') 59 ---> 60 return mail.send() 61 62 ~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\mail\message.py in send(self, fail_silently) 289 # send to. 290 return 0 --> 291 return self.get_connection(fail_silently).send_messages([self]) 292 293 def attach(self, filename=None, content=None, mimetype=None): ~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\mail\backends\smtp.py in send_messages(self, email_messages) 101 return 102 with self._lock: --> 103 new_conn_created = self.open() 104 if not self.connection or new_conn_created is None: 105 # We failed silently on open(). ~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\mail\backends\smtp.py in open(self) 61 }) 62 try: ---> 63 self.connection = self.connection_class(self.host, self.port, **connection_params) 64 65 # TLS/SSL are mutually exclusive, so only attempt TLS … -
Disable Result Count in Django ListView
I have a custom ListView whose query is rather expensive. When sub-queried for use in a COUNT(*), the Postgres query planner does even worse in terms of performance. The count is about 20x slower than retrieving the results (46ms vs 922ms). My question is is there a way to disable the count query for a subclass of ListView? In the Django admin, there is an option show_full_result_count which allows one to disable the extra COUNT(*) query for pagination. So is there a similar mechanism? -
Android websocket client SSL error when connecting to server running multiple SSL enabled web applications
I am working on the Android client implementation that connects via websocket to a server. I've just enabled HTTPS on the server instance and now I am receiving this issue: W/System.err: com.neovisionaries.ws.client.HostnameUnverifiedException: The certificate of the peer (CN=otherdomain.com) does not match the expected hostname (domain.com) at com.neovisionaries.ws.client.SocketConnector.verifyHostname(SocketConnector.java:171) at com.neovisionaries.ws.client.SocketConnector.doConnect(SocketConnector.java:126) at com.neovisionaries.ws.client.SocketConnector.connect(SocketConnector.java:83) at com.neovisionaries.ws.client.WebSocket.connect(WebSocket.java:2152) at com.neovisionaries.ws.client.ConnectThread.runMain(ConnectThread.java:32) at com.neovisionaries.ws.client.WebSocketThread.run(WebSocketThread.java:45) It seems that the websocket client is finding mismatched server host names. Some other related info: otherdomain.com is a different one of our URLs. It is pointed to separate instance of the same web application running on the same server as domain.com which is the app I am currently working on. My code is logging the URL that it is connecting to and I can see that it is correctly referencing domain.com: connecting to: wss://domain.com?session_key=TheCorrectSessionKey As noted otherdomain.com is another instance of the same web application. That instance already previously had HTTPS enabled and everything is working properly with that instance. The same client code I am using now is able to connect successfully to this instance. The same web application has a front end page that also connects to the websocket via wss://. This is working properly in both Chrome and Firefox … -
Django cms - custom page (type)
i try to generate a django cms application with different page types. Currently i do that like that: CMS_TEMPLATES = ( ('content.html', 'Base'), ('category.html', 'Category'), ) So i can create different pages for different product categories. But i would like to build a custom "renderer" or something like that, where i can do some db calls to retrieve some products. (Depending on some custom page attributes) Currently i set the custom page attributes by PageExtension from django cms. Can you give me a hint to that? -
Creating blog on Django - urls won't cooperate
System information: Using Sublime Text 3.1.1 and Mac 10.14 Mojave and Django Version 2.1.3 I am creating a blog in django for python. It has a homepage and then a 'posts' page that when you click on it lists the titles of the posts that have been created. When I click on a title of a post, it should bring me to a page that has the title and then the text of the post underneath it. However, this is where my project stops working. I get the error on my web browser: TypeError at /posts/1/ post() got an unexpected keyword argument 'post_id' Request Method: GET I am trying to use a number for the url that correstponds to the blog post. So one blog post would be at http://localhost:8000/posts/1/, the next at http://localhost:8000/posts/2/, etc. Let me show you how I am trying to do this. In my urls.py I create the following path in the 'urlpatterns' list: path('posts/<int:post_id>/',views.post,name='post') From what I understand, this should store an integer value as 'post_id'. My view, in 'views.py', for a post looks like: from django.shortcuts import render from .models import BlogPost as Post def post(request): """Show the text of a single blog post""" … -
Django If in the article, show all the article titles in the category of this article
Hello i need a little help. I create django cms. I cant filter category in my post page. I want, If I'm in the post page, I would like to see other post titles in this category. Let me explain; i have three post. post title is like this; 1-bmw3series 2-bmw5series 3-teslaroadster 1st and 2nd post in "bmw" category 3nd post in the "tesla" category I want to show post categories in the left area. but I want to show post title of that post categorie. For example, if I'm in bmw5series page, I want only see left category area to bmw3series and bmw5series post titles. When I use the following code {% for category in category %} {% for article in category.get_article %} <li><a title="{{ article.title }}" href="{% url 'article:detail' slug=article.slug %}">{{ article.title }}</a></li> {% endfor %} {% endfor %} All post titles are listed... so if im inside bmw5series post just I need to see articles in bmw category.... How do I filter them? views.py from django.shortcuts import render, get_object_or_404 from .models import Article, Category def index(request): articles = Article.objects.all() category = Category.objects.all() context = { "articles": articles, "category": category, } return render(request, 'index.html', context) def detail(request,slug): article … -
django-admin: command not found in HostGator shared hosting to start django project
I am tring to setup Django in HostGator shared hosting server. python 2.6.6 django 1.3.1 I run this command in SSH shell. django-admin startproject sitename -jailshell: django-admin: command not found How can i fix this. -
Why is ContentFile necessary in file upload
I have a script that reads a csv file and then creates a temporary file using default_storage.save(name, ContentFile(data.read())) to be processed later. I have read the docs about ContentFile and some other post but I still do not understand why its necessary. I understand that it inherits from a file object and operates on string content instead of the file. What is the purpose of contentfile and why do I need it in this case? -
How to set a field to null in a django update statement
I have the following statement: TrackTitle.objects.filter(pk=tracktitle_id).update(master_id=None) I get the following error from this: FieldDoesNotExist at /mturk/remove TrackTitle has no field named 'master_id' However, if I change it to the field name itself (which is a foreign key): TrackTitle.objects.filter(pk=tracktitle_id).update(master=None) I get the following error: invalid literal for int() with base 10: 'None' How would I set master_id to null in an update statement? -
Moving Django Database from Digital Ocean to AWS
I want to move my Django application from Digital Ocean server to AWS. How do I move the database from old server to the new server? -
Using PassLib to Verify Hash from Flask User Passwords
I'm currently trying to migrate my Flask Users over to a Django Backend. However, when I'm using passlib to verify the hash, I can't figure out why it won't verify. Our flask app settings SECURITY_PASSWORD_HASH = "pbkdf2_sha512" SECURITY_PASSWORD_SALT = "stackoverflow" # this is an example An example of a hash I pulled from a database flask_hash = "$pbkdf2sha512$12000$ZQyhNEbIOSfk/J/T2vs/Bw$j.yxtixV.DqAcpsY9XTnJZZb3lCkR2fMWmV329Uc7Y/vz5Z0yMshEkYlUsE2Y9xm8TICwYkG55RgAplzZzLl7g" So I created a custom pbkdf2_sha512 with the the rounds and salt rounds = 12000 salt = "stackoverflow".encode() # assume I swapped this out with the right salt custom_pbkdf2 = pbkdf2_sha512.using(rounds=rounds, salt=salt) verify_result = custom_pbkdf2.verify(hash=flask_hash, secret=password) print (verify_result) # false But if I create a new hash ... it does work test_hash = custom_pbkdf2.hash('testing-if-this-works') test_hash_confirm = custom_pbkdf2.verify('testing-if-this-works', hash=test_hash) Is there something I'm missing? Thank you so much for any help here ... I know the password to this -- it's a dummy account I used for testing. -
django model choices is not populating the database
I have the following code: class ReportType(models.Model): REPORT_TYPE_CHOICES = ( ('E', 'Earnings'), ('MA', 'Monthly announcement'), ('WA', 'Weekly announcement'), ('SA', 'Sales announcement'), ) report_type = models.CharField( max_length=50, choices=REPORT_TYPE_CHOICES, default="Earnings" ) def __str__(self): return self.report_type This is just one of the model classes which includes a choices attribute for one of the fields. However, when doing "makemigrations" and then "migrate" the management tool creates the database table but does not populate the database table attribute with the data in the choices which it should do. The result is that when I'm using this model in a modelfrom I get an empty drop-down list when clicking on the dropdown box in the form. This problems occurs on almost everyone of the model classes which includes the choices field, but one of the model classes is actually working, but it has the same code except from different content in the actual choices. Does someone know why the django management tool is not populating the data in the choices attribute into the database table ? I cant see any problems with the code. -
Django Relationship to link two models
i am learning django and I am working on an project to make a pizza ordering portal. I decided to make models for Toppings and Pizza seperately, so that more toppings can be added later and for pizza to of them can be selected, but I cannot seem to figure out the relation schema that should be used to link these two. I stumbled upon Foreign key method but that is not I want Here is the part of code for models: class Topping(models.Model): name = models.CharField(max_length = 30) def __str__(self): return self.name class Pizza(models.Model): name = models.CharField(max_length=40) first_toppping = models.Topping() second_topping = models.Topping() # in inches size = models.IntegerField(max_length=3) price = models.FloatField() Please, suggest a method to link these two. -
Is that possible to disallow public access AWS Files, but serve only a specific Origin?
Recently I use AWS S3 bucket to serve static files for my Django project. Here is my settings: AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') # AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') # AWS_STORAGE_BUCKET_NAME = 'bucket-name' AWS_STATIC_LOCATION = 'static' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' After creating the bucket, I can see these options are by default True But when I try to access my static files from my website www.my-site.com or locally 127.0.0.0.1:8000, it shows 403 permission denied. What do I miss? Request URL: https://bucket-name.s3.us-east-2.amazonaws.com/static/file-name.js Request method: GET Remote address: 52.0.0.0:443 Status code: 403 After some searches, I tried to define a CORS like: <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> -
How do I remove a model but keep the database table on Django
I want to remove the class declaration of the model but want to keep the records and the table on the database. How can I do that?