Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying Django Application on Alibaba ECS
I am trying to deploy a simple todo application on Alibaba ECS. Its a Django application and I am trying to deploy it with the help of gunicorn and nginx. However, after setting up the required files, when I try to access http://149.129.136.180/ , I get the message - "The site can't be reached. 149.129.136.180 took too long to respond." Here are the required details: OS: Ubuntu 16.04.4 LTS (GNU/Linux 4.4.0-117-generic x86_64) root@iZa2asghjgdfsdjfsgukZ:~# cat /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/todo ExecStart=/root/.virtualenvs/todo_venv/bin/gunicorn --workers 3 --bind unix:/root/todo/todo.sock todo.wsgi:application [Install] WantedBy=multi-user.target root@iZa2asghjgdfsdjfsgukZ:~# sudo nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful root@iZa2asghjgdfsdjfsgukZ:~# cat /etc/nginx/sites-available/todo server { listen 80; server_name 149.129.136.180; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; proxy_pass http://unix:/root/todo/todo.sock; } } root@iZa2asghjgdfsdjfsgukZ:~# sudo systemctl status nginx ● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Drop-In: /etc/systemd/system/nginx.service.d └─override.conf Active: active (running) since Tue 2018-09-18 17:11:07 CST; 10min ago Process: 996 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=0/SUCCESS) Process: 1012 ExecStartPost=/bin/sleep 0.1 (code=exited, status=0/SUCCESS) Process: 1005 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; … -
AbstractUser is not working Django ! (Substituting a custom User model)
App name is "backend" Models.py from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractUser class User(AbstractUser): fb_userid = models.CharField(max_length=256) Settings.py AUTH_USER_MODEL = 'backend.User' INSTALLED_APPS = [ 'backend.apps.BackendConfig', 'rest_framework', 'rest_framework.authtoken', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'oauth2_provider', 'bffcode', ] Error: I'm trying to Substitute User model in my project but i'm not able to create migrations -
Django 2.0 in production not selecting text by mouse
I am not able to select part of the text of my Django 2.0 project in production in Chrome and Firefox (to copy it and paste) . So am able to do this in Microsoft Edge or in development mode via runserver. -
Django: one UID per request howto
I want to make sure the user has opened only one tab when he's connected. The idea is to generate one new unique id attached to the session for each request, and make sure when I get a new request, that this is the right "expected" id. If not, then disconnect the user with the message "you've been disconnected, maybe it's because you have more than one tab opened. If so, please close all other mywebsite.com tabs and re-login". How would you do? -
Django Timezones - Database returned an invalid datetime value
I have the following query that returns the amount spent over time. Right now it shows every 'transfer'. summary_over_time = qs.values('created_on').annotate(total=Sum('amount')).order_by('created_on') where created_on has the format 2018-09-12 16:49:13.000000 I would like to group the results by month. I have tried the following: timezone = pytz.timezone('Etc/GMT+0') summary_over_time = qs.annotate(month=TruncMonth('created_on', tzinfo=timezone)).values('month').annotate(total=Sum('amount')).order_by('created_on') but I get: ValueError: Database returned an invalid datetime value. Are time zone definitions for your database installed? I have tried specifying the timezone in the my.ini file in the [mysqld] default-time-zone = '+00:00' and then rebooting the service. Running SELECT @@GLOBAL.time_zone; returns '+00:00' but I'm still getting the same error. Any ideas? -
How to install Django framework?
Well, i am new to Django and planning to learn it into core. I have query with on how to create a website and tie it in with a database, as well as how to use dynamic code in your HTML pages? And after a lot of research on how to install it I have found this ~ Learn Django Building Projects Doing it well here !! -
Need Guidance for django wagtail
currently i'm trying to Integrating Wagtail with existing django project. I'm new in wagtail, and still learning about wagtail class BlogPage(Page): body = RichTextField(blank=True) categories = ParentalManyToManyField('blog.BlogCategory', blank=True) location = models.ForeignKey('blog.Location', on_delete=models.PROTECT) and then i register the category and the location model as snippets. how's the best practice for build page contains of BlogPage with certain category / location ? and how to call that page from django's menu or maybe where can i find documentation for integrating wagtail to existing django project Thank you -
Data is not inserting into django table
Models.py File class register(models.Model): name = models.CharField(max_length=200) mobile = models.CharField(max_length=20) email = models.CharField(max_length=50) actype = models.CharField(max_length=50) amount = models.CharField(max_length=10) def __str__(self): return self.name Views.py file def form_submit(request): name = request.POST["name"] mobile = request.POST["mobile"] email = request.POST["email"] actype = request.POST["actype"] amount = request.POST["amount"] registeration = registeration(name = name, mobile = mobile, email = email, actype = actype, amount = amount) registeration.save() return render(request, 'about.html') -
Django: product variants for ecommerce
I'm trying to build an ecommerce and to configure product variants and attributes. In my product variant models, I'd like to access all of the selected attributes from the related product and add a value for each product. For example, if I create a new product and chosose two attributes for the variants: color and size, I'd like to be able to create dynamically a field for each of them when creating a variant for this product. Here's what I have in my models.py file: class Product(models.Model) : name = models.CharField(max_length=120) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='products') allow_variants = models.BooleanField(default=True) product_attributes = models.ManyToManyField("attribute") def __str__(self) : return self.name class Meta : ordering = ("name",) class Attribute(models.Model) : name = models.CharField(max_length=120) def __str__(self) : return self.name def get_all_attr_variants(self) : variants = AttributeVariant.objects.filter(attribute__name=self.name) return variants class AttributeVariant(models.Model) : name = models.CharField(max_length=120) attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) def __str__(self) : return self.name class Meta : ordering = ('name',) class ProductVariant(models.Model) : Please help me if you have any idea of how I could do it. Thanks! -
independent keys per user in django
I'm new to django and I'm writing a small website for internal use. The basic functionality is to get permission and access the user google account (photos, drive, etc). In my views.py I need to share some variables between the different functions (for example, the access key to the google account). I implemented this by using a global variable (a class with data fields only). This solutoin works nicley exept one big problem: if two users use the website at the same time, both access the same google account! How can I make sure each user will have his own private data? (by user I mean someone that access the site on his personal computer) Thanks, Shimi -
Gunicorn worker restarts when exception is thrown
In our django app run through gunicorn a worker restarts whenever there is a exception thrown in a call which is not handled. This also causes other processes to fail like socket server. However if I run as dev which is without gunicorn, any exception thrown is just printed out to console and application keeps on working smoothly. How can I have the same behavior as in dev i.e. worker doesn't restart on an exception. -
Python for loop where both if statements need to execute
Basically, I have a for loop which compares two list values and if they match do something and if they don't do something else. The problem is, for example, when I enter two values that are in both lists the code works and also when entered two values that are not in both lists it works. What I want is when I enter one value that is in both lists and one value that is not in both lists it would execute both commands. for y in range(len(value)): if [item for item in List1 if item in List2]: // do something if [item for item in List1 if item not in List2]: //do something else I know this is probably wrong way to implement this, because to my knowledge if one of if statements is true it ignores the second if statement, however I don't know any other way. -
Cannot use bootstrap-datetimepicker
I want to include datetime picker in my template but having done this tutorial http://www.lisenme.com/date-time-picker-input-field-using-bootstrap/ my css and js files still cannot be found by django. in template: <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link href="css/bootstrap-datetimepicker.min.css" rel="stylesheet"> <script src="js/bootstrap-datetimepicker.min.js"></script> and the error: Not Found: /js/bootstrap-datetimepicker.min.js Not Found: /css/bootstrap-datetimepicker.min.css I downloaded the whole bootstrap-datetime picker, in my project tree created directories css and js and included files that the links refer to. Maybe here is the problem as I am not sure where to include the css and js files. I have tried two options so far: my_app/templates/my_app/css or my_app/templates/css. None of them was found by django -
How to add Django after installing Python 3.6 in whm via ssh?
I have a VPS and it does not provide a one-click Python Installation as some other VPS services do. After many failed attempts I finally installed Python 3.6.3 via my WHM ssh. Can someone guide me on how to set up Django next and proceed to development? -
Django and Google Cloud Storage - how to cache images
I am developing a Django 2.1 app and trying to serve media files through Google Cloud Storage (GCS). I created a bucket with public read access and installed django-storages package. I managed to make the integration work, but I don't know how to make the browser cache the images downloaded from GCS. Right now, the images are downloaded even for those pages that I already visited. These are my settings in settings.py: # GCS INTEGRATION # ------------------------ DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = '<BUCKET>' GS_DEFAULT_ACL = 'publicRead' GS_CACHE_CONTROL = 'max-age=86400' # MEDIA # ------------------------- MEDIA_URL = 'https://storage.cloud.google.com/<BUCKET>/' MEDIA_ROOT = 'https://storage.cloud.google.com/<BUCKET>/' I also set up an environmental variable that points to a GCS service account json file GOOGLE_APPLICATION_CREDENTIALS='<PATH-TO-JSON>' In a template that shows a list of images, I put the following code (inside a loop): <div class="uk-width-1-4 uk-card-media-left uk-cover-container"> <img data-src="{{object.resource.url}}" alt="" uk-cover uk-img> </div> When rendered by the server, this piece of code is translated as follows: <div class="uk-width-1-4 uk-card-media-left uk-cover-container"> <img data-src="https://storage.cloud.google.com/<BUCKET>/<PATH-TO-FILE>" alt="" uk-cover="" uk-img="" class="uk-cover" src="https://storage.cloud.google.com/<BUCKET>/<PATH-TO-FILE>" style="width: 169px; height: 126px;"> </div> I tried to fiddle with some header tags with the following mixin. class CacheControlMixin(object): cache_timeout = 60*60 def get_cache_timeout(self): return self.cache_timeout def dispatch(self, *args, **kwargs): response = super(CacheControlMixin, … -
Django - error 500 occurs when checking if value is None
I'm using Django to develop my server and came across a problem which I'm not sure why is happening. I have the following model: class Group(models.Model): group_name = models.CharField(max_length=45, unique=True) attached_rule = models.CharField(max_length=45, null=True) @classmethod def create(cls, group_name, attached_rule=None): group = cls(group_name=group_name, attached_rule=attached_rule) return group def __str__(self): return self.group_name I also have the following function in my views.py: def get_rule_by_group(request): if request.method == 'GET': group_name = request.GET.get("groupName") print(group_name) group = Group.objects.filter(group_name=group_name) if group.attached_rule is None: #<== Fails here print("attached rule is null") return HttpResponse("Successful") Now, when a group first created the value of attached_rule is null and will changed later on. The problem happens after I create the group, and then try to print the attached rule to console - I check if the rule is null. However, the server fails at this point and I get this error: "GET /policies/getRuleByGroup/?groupName=TestGroup HTTP/1.1" 500 58646 What can be causing this error? Thanks in advance. -
Periodic auto update "html-div" and database in django
I'm trying to develop a website using Django. I have a model, which has to be updated periodically and readback and update it in html. I have implemented this by calling a function in my "views.py", which will update the database, later it will read the database and update in the html. So, whenever i reload my page, it executes a function which gets all the necessary data, update the database, read it and update in "html". I just added the line < meta http-equiv="refresh" content="10"/> to reload my page periodically in a interval of 10 seconds. This is working proper, but it looks odd(when it is reloading). I know this shouldn't be the way it to be implemented. Much appreciated, If anyone can suggest a better way to update the database periodically and reload a part of the html. -
Page not found at polls/1/details in Django-2.1
I'm trying to get the Choice details but the page isnt rendering here is link to project- https://github.com/tsuryaa/my_project -
Facebook Messenger bot webhook verification fails when django app is deployed to AWS elastic beanstalk
I have developed on chatbot application for FB messenger using django. I've deployed on AWS EB which I believe was successful. I followed this tutorial. I am now trying to set up my webhook using the url that was created by EB. When I try to verify my callback url on facebook, it fails? Some additional information: 1) Everything works as expected locally when I use ngrok to tunnel into my local host 2) The deployment to AWS was successful as I am able access the django admin page and other pages in the application through a browser using the AWS created url. 3) Facebook sends a get request to verify that my endpoint is working. If I perform this get request manually (through a browser) to the AWS created url, it works. This makes me believe that there is some form of authentication or whitelisting that I need to configure between AWS and facebook. But I am not sure if this is correct or how to achieve this. Any help or suggestions would be appreciated! Thanks -
How to save sessions for particular session in djnago
I am using request.session to save data. sessionid = request.session.session_key This id is getting generated and deleted while login and logout.So i want when user would add some items to cart it would be saved in that particular session so if user would not logout then when he comes back would see his added items and if he loggs out all added cart item would be deleted -
django how to load view for each user separatly?
I have a login page that users can login, but all users can view the same data or each other data! I would like to separate each users data like facebook, for example, that each user loads his/her own data. can any one give a clue how to implement it! thanks in advance! -
Django pass argument to class-based view
I have a page with one charfield where the user writes some text. I need to redirect the user to another page with that text as agument: This is the code from the first view: if form.is_valid(): link = form.cleaned_data['play'] print(link) return redirect('play_that_view', link = link) This is the second view: class Play_that_View(View): template_name = 'Play/play_that.html' def get(self,request,*args,**kwargs): link = self.kwargs['play'] print(link) print('get') def post(self,request,*args,**kwargs): link = self.kwargs['play'] print(link) And this is in urls.py: url(r'^play_that_shit/', views.Play_that_View.as_view(), name = 'play_that_view'), The error i get is: Reverse for 'play_that_view' with keyword arguments '{'link': 'rere'}' not found. 1 pattern(s) tried: ['play_that/'] I just need to catch the text in the back so i can process it. What am i doing wrong? -
Cannot gzip Django static files served on AWS S3
I've ran a lighthouse audit on my Django-React webapp and it suggests "Enable text compression." The thing is, I've already enabled gzip setting in my django-storages conf file. When I check my aws s3 console, the file size is 177.4KB on the other hand the network portion of chrome devtools says that my main.js is 662kb still. I've checked the returned response headers and it is as below. It does not return 'Content-Encoding: gzip' while checking the metadata of main.js on my aws s3 console does have this. \response headers: Accept-Ranges: bytes Cache-Control: max-age=2629746 Content-Length: 677745 Content-Type: text/javascript \conf.py AWS_IS_GZIPPED = True GZIP_CONTENT_TYPES = ( 'text/css', 'application/javascript', 'application/x-javascript', 'text/javascript', 'application/vnd.ms-fontobject', 'application/font-sfnt', 'application/font-woff', 'image/svg+xml', ) -
Django file upload with Ajax-fueled progress bar
I am relatively new to Django and even newer to JavaScript, so excuse my greenhorn question. The situation is like this: 1) I have a website for file uploading, coded out in Django, with some of the logic like the one below: def page_query(request): ... if request.method == 'POST': ... file_entry = file_form(request.POST, request.FILES) if file_entry.is_valid(): if request.FILES.get('filename', False) != False: f = request.FILES['filename'] fname = time_id + '_' + case_id + '_.ext' file_check = data_admin.upload_file(f, fname, upload_path) upload_file_path = os.path.join(upload_path, fname) data_admin.upload_file() is a custom function defined in another module of my project with function boiling down to: with open(upload_path + fname, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) 2) I wanted to add some sort of upload progress indication to my website, and in a lot of sources I have seen people recommending jQuery's Ajax solution, which boils down to the code below: $(document).ready(function() { $('#form_id').on('submit', function(event) { // event.preventDefault(); var post_data = new FormData($("#form_id")[0]); $.ajax({ xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function(evt) { var percent = Math.round(evt.loaded/evt.total * 100) console.log(percent) $('#complaint_query_button').attr('disabled', true) $('#complaint_query_button').get(0).innerText = "Upload status: " + percent + '%' }, false); xhr.upload.addEventListener("load", function(evt) { $('#complaint_query_button').css('background-color', 'green').delay(2000) $('#complaint_query_button').get(0).innerText = "COMPLETE, refreshing..." // … -
difference between request.session and requests.Sessions
I use request.session to save session id but i came across a tutorial where they have used requests.Sessions to save data they need. What is the difference between these two?