Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to change CKEditor highligth theme on django?
I am not able to add styles in codes in posts. The style I put in works only when I'm going to edit in the Django admin site, but when I go to the post, the codes are in the default style. My code currently is: admin/base.html <script> var config = { extraPlugins: 'codesnippet', codeSnippet_theme: 'monokai_sublime', height: 356 }; CKEDITOR.replace ('body', config); </ script> blog/post_detail.html <link href="{% static 'ckeditor/ckeditor/plugins/codesnippet/lib/highlight/styles/default.css' %}" rel="stylesheet"> <script src="{% static 'ckeditor/ckeditor/plugins/codesnippet/lib/highlight/highlight.pack.js' %}"></script> <script>hljs.initHighlightingOnLoad();</script> I also tried adding the first code to the posting file, but it did not work images: https://imgur.com/a/uyX3ytC -
Django Angular File Upload - Upload works in Postman but does not with angular 7
I have Django Backend that accepts File with other data as a request. When I use File Upload API from Postman to submit File and other form data. Postman Request It works fine and Prints <QueryDict: {u'csv': [<InMemoryUploadedFile: log_2018_10_09- 11_57_16_Summary_subject23_hrm.csv (text/csv)>], u'device_name': [u'Zephyr']}> and file successfully get stored. But when I am trying to do it with Angular it logs empty object. Below is my Angular Code. // HTML <input hidden type="file" id="csv" name="csv" accept=".csv" (change)="onFileChange($event)" #fileInput> // On Change Method onFileChange(evt: any) { if (evt.target.files && evt.target.files[0]) { const file = evt.target.files[0]; const reader = new FileReader(); reader.onload = () => { this.form.get('csv').setValue(file); }; reader.readAsText(evt.target.files[0]); this.uploadData.append('csv', this.form.get('csv').value); } } // On Submit Method onSubmit() { this.uploadData.append('device_name', this.form.get('device_name').value); this.backendService.insertCSV(this.uploadData).subscribe( response => { console.log(response); }, error => { console.log('error', error); } ); } // Call to Backend HttpUploadOptions = new HttpHeaders({ 'content-type': 'multipart/form-data', }); insertCSV(fileData): Observable<any> { return this.http.post('http://127.0.0.1:8000/upload/', { data: fileData, headers: this.HttpUploadOptions}); } Gives an Error on Console in Browser And Prints on Django {u'headers': {u'normalizedNames': {}, u'lazyUpdate': None}, u'data': {}} Please Help Me! -
Get value from one model to another with a custom migration?
I have a foreign key on a model referencing another model like so: class ModelA(CachingMixin, models.Model): fkCol = models.ForeignKey(ModelB, null=True, blank=True) With the above, I am able to express a one to one relationship. However there is now the need to support a one to many relationship for this, and I have recently created another model ModelAB. class ModelAB(models.Model): fkCol_A = models.ForeignKey(ModelB, related_name="modelB_modelA") fkCol_B = models.ForeignKey(ModelA, related_name="modelA_modelB") Is there a way to copy across (ideally when migrating) all values from ModelA > fkCol into the ModelAB > fkCol_A and populate ModelAB > fkCol_B values with the id of each record from ModelA? For example ModelA record with id=1 has a fkCol=10 needs to become ModelAB has fkCol_A = 10 and fkCol_B = 1 Is this possible? -
Django 'str' object has no attribute 'save'
I have a problem using Django in views.py....... the error in line post = text_headlines.save(commit=False) Exception Value: 'str' object has no attribute 'save' below is my code in forms.py, models.py and views.py thank you sorry I am new in Django still need time to learn forms.py from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ('URL',) models.py from django.db import models # Create your models here. from django.conf import settings from django.utils import timezone class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) URL = models.URLField(max_length=200) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title views.py from django.shortcuts import render, redirect from .forms import PostForm from django.utils import timezone from django.shortcuts import render, get_object_or_404 from .models import Post from urllib.request import Request, urlopen as uReq from bs4 import BeautifulSoup as soup #Post.objects.get(pk=pk) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'post_detail.html', {'post': post}) def make_soup(website) : req = Request(website,headers = {'User-Agent' : 'Mozilla/5.0'}) uClient = uReq(req) page_html = uClient.read() uClient.close() page_soup = soup(page_html, 'html.parser') return page_soup def post_new(request) : if request.method == "POST": form = PostForm(request.POST) print(form) if form.is_valid(): url = form.cleaned_data['URL'] website = make_soup(url) headlines … -
NoReverseMatch at /accounts/profile/
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. [![ profile.html 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'), ] div class="modal fade" id="kiddyupdate" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header text-center"> <h4 class="modal-title w-100 font-weight-bold">Update child <strong>{{kid.name}}</strong></h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="{% url 'update_profile_kid' %}" method="post"> {% csrf_token %} <i class="fas fa-user fa-2x" aria-hidden="true"></i> <div class="form-group row"> <div class="col-sm-6 "> <input formControlName="name" name="name" type="text" value="{{kid.name}}" class="form-control form-control-lg" placeholder="Childs Name"> </div> </div> <i class="fas fa-mars fa-2x"></i><i class="fas fa-venus fa-2x"></i> <div class="input-group"> <select placeholder="Select a gender..." class="form-control chosen-select" style="width:350px;" tabindex="2" name="gender" type="text" value="{{kid.gender}}"> <option value="Select … -
Is it compulsory to end a url defined in urls.py. with '/'?
I have just started learning Django and want to know the reason behind a particular behavior the Django's polls application is showing. When I remove that '/' from the end of 'detail' URL path, I can access the details page of all questions except for the primary key(pk) 1. In case of pk 1, I am getting a 404 Error. It would be great if I will get an explanation. Thanks! Cheers! Here are the code files: polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] polls/views.py ....... ....... def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/details.html', {'question': question}) ....... ....... polls/templates/details.html <h1> {{ question.question_text }} </h1> <ul> {% for choice in question.choice_set.all %} <li> {{ choice.choice_text }} </li> {% endfor %} </ul> -
Is there a way to use iterator() in SlugRelatedfield queryset argument
Caching is happening in SlugrelatedField queryset argument , Is there a way to use iterator() in the queryset argument to avoid caching -
django forms create multiple of the same input with different names
I'm currently trying to create a form that takes multiple hidden inputs to collect data via javascript class NewCasePhotoForm(forms.Form): case_photo_1 = forms.CharField(required=False) case_photo_2 = forms.CharField(required=False) case_photo_3 = forms.CharField(required=False) case_photo_4 = forms.CharField(required=False) case_photo_5 = forms.CharField(required=False) case_photo_6 = forms.CharField(required=False) case_photo_7 = forms.CharField(required=False) case_photo_8 = forms.CharField(required=False) case_photo_9 = forms.CharField(required=False) case_photo_10 = forms.CharField(required=False) case_photo_11 = forms.CharField(required=False) case_photo_12 = forms.CharField(required=False) case_photo_13 = forms.CharField(required=False) case_photo_14 = forms.CharField(required=False) case_photo_15 = forms.CharField(required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for i, field in enumerate(self.fields): self.fields[field].widget=forms.HiddenInput( attrs={ 'id': 'fileInput{}'.format(i+1) } ) Is there a better way to do this that is DRY? -
Django deploy - no images and css
So I have just deployed my website to my outer server. I coppied all files from my repo. I created virtualenv, database on server, created users, made migrations, migrated and ofc . Unlikely it seems that my images and css/js files are not found. Is it absolutely nessecarry necessary to install NginX (as it was told in tutorial) to get it done? On my localhost everything works fine...