Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Database : SQLite vs MySQL in production
I'm new to Python/Django, and i using the default database (SQLite) for now, but someone told us that i must use MySQL in production. Using SQLite would be a problem ? -
How can I make a sum of numbers in a cycle in django?
I have a record with severall numbers. The column "Variação de saldo" is the simulation of the extract of some person. What I want the column "Saldo" to show is something like the real time balance. For example, in this case, I want "saldo" to show the sum of the numbers in "variação de saldo". Starting with the first record (in this case, 10); then, adding the next records (10-10=0 the second row will be 0; 0+5=5, the third row will be 5, and so on). How can I make this? enter image description here -
Host Django Rest API on AWS ec2 using Apache
I have built a very basic API using the Django Rest Framework following this tutorial: https://scotch.io/tutorials/build-a-rest-api-with-django-a-test-driven-approach-part-1 I have confirmed that this works on my local machine by following the instructions of the tutorial. Now I need to host this API on the internet. The easiest way to do this seems to be with AWS using Apache2 on an ec2, which I have attempted to do, but I can't seem to figure out how to make this work. I understand that I need to configure Apache2 for my application, which I have done following this tutorial: http://www.nickpolet.com/blog/deploying-django-on-aws/koAayBejnjdNwYfc6 modifying values as needed. My Apache2 configuration file is as follows: WSGIScriptAlias / /home/ubuntu/API/djangorest/djangorest/wsgi.py WSGIPythonPath /home/ubuntu/API/djangorest <Directory /home/ubuntu/API/djangorest/djangorest> <Files wsgi.py> Order deny,allow Require all granted </Files> </Directory> Alias /media/ /home/ubuntu/API/djangorest/media/ Alias /static/ /home/ubuntu/API/djangorest/static/ <Directory /home/ubuntu/API/djangorest/static> Require all granted </Directory> <Directory /home/ubuntu/API/djangorest/media> Require all granted </Directory> My project is housed in the home directory of the ec2 instance like so: ~/API/djangorest/... From here, shouldn't it be a simple matter of configuring Apache? I've waded through documentation for hours to no avail. This is basically the first project I've ever done that isn't a console application, so It's likely that I'm missing something obvious. In short, … -
Django queryset filter hourly data
I need to fetch all the users who came yesterday at a particular hour. Say, if I am running the query at 1:15pm, then users who came yesterday between 1pm and 2pm, should be returned. How can I achieve this? -
Installing only social account from allauth
I am trying to have social sign in on my site using allauth. However, I do not want all the other features that come along with it. For example, I don't want the accounts feature (login, sign up, etc.) I only want: allauth.socialaccount I tried installing only this app and I did get all the models that go with it Social accounts, Social application tokens, Social applications and sites Here's what I installed: INSTALLED_APPS = [ .... .... 'django.contrib.sites', 'allauth', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.twitter', ] SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'METHOD': 'oauth2', 'SCOPE': ['email'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'LOCALE_FUNC': lambda request: 'en_US', 'VERSION': 'v2.4' }, 'google': { 'SCOPE': ['email'], 'AUTH_PARAMS': {'access_type': 'online'} }, 'twitter':{} } SITE_ID = 3 I have my own User model (inheriting from django.contrib.auth User model. I also have my own sign up page. All I want to do right now is try to get a link in the sign up page that allows the user to sign up with his social accounts (Facebook, Google, Twitter). How do I add these links to my custom sign up page? Please remember I only installed socialaccount and not accounts. I do not want allauth's sign up, login, change email, etc. … -
Deploy Django app on clients production environment
Hi i am new to python development. I have developed the web application using django and i am trying to deploy my application on client environment. I don't want to deploy the application with source code . I have pyc file but it's easily decode. -
How to know the compatible DRF version to Django version?
I just wanted to install and use Django v1.8 and then i installed the latest DRF version on top of it. When i created an initial migration of a model, it was generated an error : Maybe the Django version and the DRF version wasn't compatible which was i did't really know. Any idea how to find the compatible DRF for Django 1.8 ? -
nginx + gunicorn 400 error
I have setup my server to use nginx plus gunicorn for hosting a project. When I send POST request of small sizes everything is OK. But when I send POST requests of size about 5MB I get 400 error from server. I had set client_max_body_size in my nginx configuration to 100M. Can anyone help with this error? Following is how I send request to server : r = requests.post(url, json=data, timeout=180, cookies=cookies, headers=headers) 400 Error depends on data size. With large data size I get this error! -
Security - Is it Safe to Call a Django Function (Python) from an AJAX Request?
Basically, I'm wondering if this code is going to cause any security issues if I put it into production. csrf tokens are implemented and all requests are served over a strict HSTS HTTPS domain. I want to do it like this so I can display a 'loading' screen while the function runs. Otherwise, the app seems to 'hang.' The endpoint for the AJAX request is secure AFAIK, but I'd like some advice on how to ensure I'm not inadvertently doing something insecure. Sending a POST request to the run_shredder function initiates the shredder process (in this case it iterates through all the user's Reddit posts and comments, selectively deleting them.) Here is the Front end JS: $.ajaxSetup({ beforeSend: function (xhr, settings) { xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}') } }); $(document).ready(function () { $('#output').DataTable({ 'autoWidth': true, 'responsive': true, 'processing': true, /* Adds the slick gear animation */ 'language': { processing: '<i class="fa fa-gear fa-spin fa-3x fa-fw"></i><span class="sr-only bg-primary"></span> ' }, 'ajax': { 'url': "{% url 'run_shredder' %}", 'dataSrc': '', 'type': 'POST', 'data': { 'account': '{{ account|safe }}', 'keep': '{{ time|safe }}', 'karma_limit': {{ karma_limit|safe }} } }, 'columns': [ {'data': 'cid'}, {'data': 'body'}, {'data': 'status'} ] }); }); Here is the Python … -
Django What is the super of mixin inherit from object
I'm reading a django app code: https://github.com/rogargon/myrecommendations/blob/master/myrestaurants/views.py#L26 He writes some code like: class LoginRequiredMixin(object): @method_decorator(login_required()) def dispatch(self, *args, **kwargs): return super(LoginRequiredMixin, self).dispatch(*args, **kwargs) class CheckIsOwnerMixin(object): def get_object(self, *args, **kwargs): obj = super(CheckIsOwnerMixin, self).get_object(*args, **kwargs) if not obj.user == self.request.user: raise PermissionDenied return obj class LoginRequiredCheckIsOwnerUpdateView(LoginRequiredMixin, CheckIsOwnerMixin, UpdateView): template_name = 'myrestaurants/form.html' Could you tell me what is the super here means? Maybe it just is a problem of python. Thanks! -
How to add dynamically field in crispy form
I don't how how to add dynamically field in crispy, actually i have not much knowledge in crispy form. Could anybody help me?i need this type of field. after click on add button, same field comes down. -
Production setup for celery
How can i setup Celery in Production Server using aws or digitalocean and broker as redis or rabbitmq. Please elaborate more on how we can resilience over the connection refused error while the broker is down. -
Passing Variable (View --> Template --> View)
Problem: I want to generate a random number, and ask the user to calculate the addition of these two. Then, I want to evaluate the number and see if the solution is correct. My issue: I can do everything except the evaluation bit, as the values of the random numbers change! HTML file: <p> What is {{ a }} + {{ b }} ? </p> <form action="{% url 'form_handle' %}" method="POST">{% csrf_token %} {{form.as_p}} <button type="submit">Submit</button> </form> FORM file: class MyForm(forms.Form): num1 = forms.CharField(max_length=20) VIEW file: def form_handle(request): if request.method == 'POST': form = MyForm(request.POST) # if post method then form will be validated if form.is_valid(): cd = form.cleaned_data num1 = cd.get('num1') #num2 = cd.get('num2') #result = cd.get('result') if float(num1) == float(a + b): # give HttpResponse only or render page you need to load on success return HttpResponse("Good job!") else: # if sum not equal... then redirect to custom url/page return HttpResponseRedirect('rr/') # mention redirect url in argument else: a = random.randrange(5,10); b = random.randrange(10,20); form = MyForm() # blank form object just to pass context if not post method return render(request, "rr.html", {'form': form, 'a': a, 'b':b}) The error I get is "local variable 'a' referenced before assignment". … -
Django - Url Dispatching - Page Not Found
I am very puzzled as to why the URL dispatcher is try to look for an empty path although a url was specified for it? Does it imply that it is unable to find the specified url and therefore trying to find the default. This happens when I try to POST and HttpResponseRedirect searches for an empty path instead of following the specified path. Assume that the other. Using Django version: 2.0 Thanks in advance! main/urls.py (ROOT_URLCONF) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('app/', include('shorterner.urls')) ] shorterner/urls.py from django.urls import path from . import views urlpatterns = [ path('request/', views.RequestView.as_view(), name="request"), path('list/', views.IndexView.as_view(), name="list") ] shorterner/views.py from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from django.conf import settings from django.urls import reverse from django.views import View, generic from .models import Urls import requests import json from .forms import SubmitUrlForm class RequestView(View): form_class = SubmitUrlForm initial = { 'url': ''} template_name = "shorterner/request.html" context_object_name = 'url' def form_valid(self, form): return super().form_valid(form) def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): input_url = form.cleaned_data['url'] short_url = google_url_shorten(input_url) print(input_url) print(short_url) … -
Ideal page is not shown
Ideal page is not shown. I wrote in views.py def top(request): content = POST.objects.order_by('-created_at')[:5] return render(request, 'top.html',{'content':content}) def detail(request,pk): content = POST.objects.order_by('-created_at')[:5] return render(request, 'detail.html',{'content':content}) in top.html <div> {% for item in content %} <h2>{{ item.title }}</h2> <p><a href="{% url 'detail' content.pk %}">SHOW DETAIL</a></p> {% endfor %} </div> in detail.html <div> <h2>{{ content.title }}</h2> <p>{{ content.text }}</p> </div> in urls.py urlpatterns = [ path('top/', views.top, name='top'), path('detail/<int:pk>/',views.detail , name='detail'), ] When I access top method, top.html is shown.And when I click SHOW DETAIL url link, detail.html is shown.But in this detail.html,always content is same.I wanna make a system when I click this link, detail's content is changed each content.pk.But now my system is not my ideal one.Why does my system always return same content in detail.html?How should I fix this? -
About Django pk in urlpattern
I am new to Django, and I am reading one app on github: https://github.com/rogargon/myrecommendations/blob/web2-html/myrestaurants/urls.py#L18 There is one urlpattern like url(r'^restaurants/(?P<pk>\d+)/$', RestaurantDetail.as_view(), name='restaurant_detail') It revoke RestaurantDetail view, here: https://github.com/rogargon/myrecommendations/blob/master/myrestaurants/views.py#L36 class RestaurantDetail(DetailView): model = Restaurant template_name = 'myrestaurants/restaurant_detail.html' def get_context_data(self, **kwargs): context = super(RestaurantDetail, self).get_context_data(**kwargs) context['RATING_CHOICES'] = RestaurantReview.RATING_CHOICES return context Here I know pk is set to one number indicating the id of restaurant, but in the html model, https://github.com/rogargon/myrecommendations/blob/master/myrestaurants/templates/myrestaurants/restaurant_detail.html, I didn't see any where using pk, but the page shows only the one restaurant. Could you how does pk work in this process? {% extends "myrestaurants/base.html" %} {% block title %}MyRestaurants - {{ restaurant.name }}{% endblock %} {% block content %} <span vocab="http://schema.org/" typeof="Restaurant"> <h1> <span property="name">{{ restaurant.name }}</span> {% if user == restaurant.user %} (<a href="{% url 'myrestaurants:restaurant_edit' restaurant.id %}">edit</a>) {% endif %} </h1> <h2>Address:</h2> <p> {{ restaurant.street }}, {{ restaurant.number }} <br/> {{ restaurant.zipcode }} {{ restaurant.city }} <br/> {{ restaurant.stateOrProvince }} ({{ restaurant.country }}) </p> <h2> Dishes {% if user.is_authenticated %} (<a href="{% url 'myrestaurants:dish_create' restaurant.id %}">add</a>) {% endif %} </h2> <ul> {% for dish in restaurant.dishes.all %} <li><a href="{% url 'myrestaurants:dish_detail' restaurant.id dish.id %}"> {{ dish.name }}</a></li> {% empty %}<li>Sorry, no dishes for this restaurant yet.</li> {% … -
NoReverseMatch at /app/^detail/3/$
I got an error,NoReverseMatch at /app/^detail/3/$ Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['app/\^detail\/(?P[0-9]+)\/\$$'] . I wrote codes in urls.py urlpatterns = [ path('top/', views.top, name='top'), path(r'^detail/<int:pk>/$',views.detail , name='detail'), ] in views.py def top(request): content = POST.objects.order_by('-created_at')[:5] return render(request, 'top.html',{'content':content}) def detail(request,pk): content = POST.objects.order_by('-created_at')[:5] return render(request, 'detail.html',{'content':content}) in top.html <div> {% for item in content %} <h2>{{ item.title }}</h2> <p><a href="{% url 'detail' pk %}">SHOW DETAIL</a></p> {% endfor %} </div> When I clicked url of SHOW DETAIL,this error happens.When I saw what's url I accessed ,it was http://localhost:8000/app/%5Edetail/3/$.I really cannot understand why %5Edetail is contained in url.How should I fix this?I did not write codes such a word was contained in url.What is wrong in my codes? -
Using multiple conditions in Django's Case When expressions
As per the Django documentation, its possible to use multiple conditions with the When clause. When(registered_on__gt=date(2014, 1, 1),registered_on__lt=date(2015, 1, 1),then='account_type') However, I am unable to use the same when using the Case clause. Case(When(registered_on__gt=date(2014, 1, 1),registered_on__lt=date(2015, 1, 1), then='account_type'), default='default') I end up getting the following error: TypeError: __init__() got multiple values for keyword argument 'then' Is there some way I can achieve this? Am I missing something here? -
Re-configuring allauth to fit custom specifications
I have a set of expectations I'm trying to achieve. I want a sign up, login, and forget password page. I also want to have social sign in using Twitter, Facebook, or Google. Another thing I want is to send a confirmation email to the user validating their account. I know I can do this with Django allauth, but allauth comes with extra features that I don't need. For example, I don't need the password reset and change email pages. I want to remove these pages and their corresponding functionality, but I'm afraid I might break the code if I do this. I was thinking about two solutions. One solution would be to go through the allauth templates and change some of the code to fit my specifications, but I feel like it would be very tedious because a lot of things might break if I remove some funcionality. The second solution I was thinking of doing was building on top of auth and using a custom User model and building custom login, sign up, and reset pages. Adding the required functionality and everything. I could also build the models to provide social login by copying allauth's templates. I am … -
Django how ImageField and BinaryField works for image
So i wanted to ask how does these 2 fields works. As my friend told me that his ios will sent byte format image to me, does it matter if i use imageField instead of BinaryField ? I did try adding a Binaryfield into my User models but when testing it out on django admin and also django rest framework api, it doenst work In django admin : the binaryfield did not appear in it In django rest framework : got an error that says editable is false for binary field. Setting the binaryfield editable=True also doesnt work. The documentation about Binaryfield in django is also not much. Can anyone please explain to me how does these 2 field work ? does sending byte format to the imagefield work ? -
Save downloaded image in django ImageField
I want to download an image and save as django ImageField. Where is my mistake? from django.core.files import File from urllib.requests import urlretrieve from .models import Photo r = urlretrieve("http://test.com/img/test.png", "./test.png") f = open("/tmp/test.png", "rb") django_file = File(f) img = Photo() img.name = "Test" img.logo.save("test.png", django_file, save=True) -
django: naming files, dirs, classes, etc
django 2.0 python 3.6.3 Hi, I have stubbed my toe on django. I have seen that models can be split out into individual files a la: |-- models | |-- __init__.py | `-- Profile.py I have also tried to do the same thing with views and forms. I ran into the case where I was importing a model and a view where the underlying file had the same name: from models import Profile from views import Profile but the code got confused over which "Profile" I was talking about. I decided to rename the files |-- models | |-- __init__.py | `-- m_profile.py |-- views | |-- __init__.py | `-- v_profile.py then do from models.m_profile import Profile from views.v_profile import Profile but now the migrations are messed up -- I get the error ModuleNotFoundError: No module named 'models'. Is there a better way to handle these things? -
CommandError: Can't find xgettext. django
I am making an app for my website with django and i need to ad persian language to my project. But when I tried to run following command django-admin.py makemessages and i get this error CommandError: Can't find xgettext. Make sure you have GNU gettext tools 0.15 or newer installed. i have installed python-gettext with pip and installed GetText for Windows and gettext.tools with nuget i saw some guys with problems similar to mine like this but they're solutions didn't help me what should i do? (i am using windows 7 64 bit and i am really noob in django ) -
Django: Display website name without using Sites framework
I want to render my website name in Jinja templates. Django's own docs on Sites state: Use it if your single Django installation powers more than one site and you need to differentiate between those sites in some way. I know I can still use it, but it seems like an overkill. I just want to pull a variable with my website's name (!= domain) in ANY template. I don't want to pass it in views either because that doesn't seem DRY enough. TIA -
I want to use the if statement based on the existence of a web page
So basically i have a complicated scenario. I am current using Django to build a website and i have current made two apps. Both apps have almost identical fields. The field I would want to focus on though is the Information field(which they both have and which i have auto generated with the help of the Wikipedia model) So the case here is that I want to create an if and else statement in the html in such a way that if the page i am hyperlinking to exists it would go to the link dealing with DetailView but if it doesnt exist I would redirected to the Create View I should also note that the two apps have their names linked with the help of the foreign key but when i try to open information links using the same name , they gave me different pks I dont feel like i explained my problem well enough but I hope someone can understand what i mean This is the Detail View Html {%extends "home.html"%} {%block head_title%} {{block.super}}{%endblock head_title%} {% block content%} <!-- verify authentication --> {% if request.user.is_authenticated%} <h3><a href="{%url 'InfoPedia:UpdateView' object.id %}">{{object.title}}</a></h3><br/> {% endif %} <ul type="disc"> <div class="container"> …