Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying image django rest framework
I am trying to get image url from database by sending id in the request. views.py class RenderImage(APIView): def post(self, request): print(request.data) serializer = ImageSerializer(data = request.data) print(serializer.is_valid()) print(request.data['id']) if(serializer.is_valid()): print("1") tags = serializer.data['id'] output = {} images = Image.objects.get(pk = request.data['id']) print("2") # output['image'] = serializer.data for image in images: output.append(image.url) text = {'status': 1, 'data':output} else: text = {'status':-1, 'data':serializer.errors} return Response(text) models.py class Image(models.Model): image = models.ImageField(upload_to = 'images/') def __unicode__(self): return os.path.basename(self.image.name) serializers.py class ImageSerializer(serializers.ModelSerializer):#test class Meta: model = Image in the views the serializer is invalid so the view doesn't proceed any idea whats wrong?? -
How to use incontains for filtering by using foreignkey in django?
I have models SiswaID = models.AutoField(primary_key=True) WaliKelasID = models.CharField(max_length=11, blank=True, null=True) SiswaKelas = models.ForeignKey(biayapendidikan, null=True, blank=True) and i want to filtering i it in template by SiswaKelas(ForeignKey) keyword2=request.GET['tingkat'] siswa['listsiswa'] = DataPribadiSiswa.objects.filter(Q(SiswaKelas__icontains = keyword2)) return render(request, 'index.html', siswa) when i run it, i get this error Related Field got invalid lookup: icontains -
Django - No Module named 'django'
I recently installed Django and below is the installation path "C:\Program Files (x86)\Python Software Foundation\Python\Lib\site-packages\" I added the path to the PATH environment variable and I tried "django-admin" command in the cmd prompt. I am getting the below error 'django-admin' is not recognized as an internal or external command, operable program or batch file. Whereas if I go into the django's bin folder and issue the same "django-admin" command, I am getting the below error Traceback (most recent call last): File "C:\Program Files (x86)\Python Software Foundation\Python\Lib\site-packag es\django\bin\django-admin.py", line 2, in from django.core import management ImportError: No module named 'django' All i want is for Django to create a website for me inside the project folder that I have created. Any help on how to fix this will help me started with Django. Thanks -Satheesh -
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
I know this question has been asked before, but I haven't found an answer that solves my situation. I'm looking at the Django tutorial, and I've set up the first URLs exactly as the tutorial has it, word for word, but when I go to http://http://localhost:8000/polls/, it gives me this error: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^polls/ ^% [name='index'] ^admin/ The current URL, polls/, didn't match any of these. I'm using Django 1.10.5 and Python 2.7. Here is the code I have in relevant url and view files: In mysite/polls/views.py: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello, world. You're at the polls index.") In mysite/polls/urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^%', views.index, name='index'), ] In mysite/mysite/urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] What's going on? Why am I getting 404s? -
Create a Template folder in Django
I have created a new project NewProject in Django. I thought I could create the folder (with db.sqlite3 and manage.py installed by default) with the simple command mkdir Templates, but it didn't work as I'd expected. I know where to install the folder, but I don't know how to install that folder in the right way. Could anyone be able to explain to me what I have to do to fix this little issue? Thanks in advance! -
CSRF token fails on form submission when CSRF_COOKIE_DOMAIN is set
I am setting CSRF_COOKIE_DOMAIN=.example. After setting this form submission fails with csrf token error. Here are the details: https://gist.github.com/anonymous/3fde73be4d3541223cf93b8e703169c1 If I don't set csrf_cookie_domain csrf fails in ajax request. I am passing csrf token on each ajax requests. -
FB.api not return email field but email is required for register flow
I found when users login with facebook through my website. Some users not return an email field from API. but my website register flow is required an email field to end the flow. Need to use email to login when user haven't login by facebook. When users who don't return a email response to my API web will raise errors and I'll lose that one. Any idea how to fix API or store users data? -
Reverse for 'account_emailconfirmation_changelist' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
When I accessed localhost: 8000/admin it shown like this: Reverse convex for ' account_emailconfirmation_changelist ' with arguments ' () ' and keyword arguments ' {} ' not found. 0 pattern (s) tried: []. I don't understand why, when this project before running this in my computer but when I switch to another computer then the error! *** I'm using python 2.7, django 1.9.9, angular2, please help me ! -
Django: csrf_exempt doesn't work
Django: 1.9.7 / Python 3.5.1 views.py from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse class OrderPayCheckView(View): @csrf_exempt def post(self, request, *args, **kwargs): return JsonResponse( data={ "valid": False, } ) When I send POST request to this url via POSTMAN, it shows, 403 Forbidden - CSRF authentication Fail kinda thing (I really want to show all errors, but the language is Korean) I tested it in my test server which has its own url. Why does it happen? -
Angular request to Django REST API is taking too long
I've a request to my REST Api that only takes 0:00:00.000129 to process in the back end. class GetRequest(APIView): def get(self, request, format='json'): time = timezone.now() serializer = ObjSerializer(Obj.objects.all(), many=True) print (timezone.now()-time) return Response(serializer.data, status=status.HTTP_200_OK) But Angular takes 3.2 minutes to finish the following request: MainService.getAllObj = function() { return $http.get(frontendUrl + "obj/?format=json"); }; I'm calling the service function in a controller: $scope.loading = true; MainService.getAllObj().success(function (objs) { $scope.objs = objs; $scope.loading = false; }); How can I reduce the angular processing time? I'm using Apache mod WSGI Server and MySQL on a Linux machine. -
How to setup and run Celery on widnwos?
Hello and thank your for your time i have a big Django project and i'm developing it in PyCharm on Windows. Right now i need to use smart queries, so i want to add Celery on it. The main problem, that celery dropped support for Windows since v4.0. So my questions is: 1) How can i use rabbit/celery on window? 2) I have some old answer, that suggest to use old version, that has support for windows, but maybe it has some way with virtual box or other staff to lanch it on windows? -
Django allauth bug: deployment from localhost to herokuapp
I'm using allauth in my Django app for basic sign-in, sign-up, password reset functionality, etc. There are no social media apps attached. Everything is working fine on localhost. When I deploy to herokuapp, I change my site in the admin page to my herokuapp domain, keeping the site id the same in my code. However, users that sign up keep getting magically deleted, and users that I used in testing and deleted keep magically returning. When I check what the site domain is in the admin page, it says "localhost" again. I've tried switching it a couple times now, but it keeps doing this. There is no error message, but I thought I'd post this problem in the off-chance that someone has encountered it. -
bootstrap-select doesn't work for Django template
I am building a Django project and try to use bootstrap-select plugin, I followed the tutorial to import needed libraries but nothing display in the browser, it is empty. It shows the regular select options when I comment out the CSS library as below: <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/css/bootstrap-select.min.css"> <!-- Latest compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/js/bootstrap-select.min.js"></script> <!-- (Optional) Latest compiled and minified JavaScript translation files --> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/js/i18n/defaults-*.min.js"></script> <select class="selectpicker"> <option>Mustard</option> <option>Ketchup</option> <option>Relish</option> </select> Does anyone know what's going on, why didn't the libraries load properly? Or does anyone know any select option alternatives for Django? Thanks -
Does Wagtail template variable "self" exist in (Django) pages that don't subclass Page?
Wagtail newbie here templating a response that is derived from a Django-based models.Model class and am noticing that it does have the {{ page }} template variable available but not the {{ self }} one. Just looking for confirmation that the this is because {{ self }} template variable is only available to classes that extend Page. Not finding anything in the docs about it. Thanks in advance, John -
H E L P New to Python! Trying to get Terminal to run my program from ATOM
/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'ex1.py': [Errno 2] No such file or directory calvisitor-10-105-169-187:~ CIS$ I get this ^ when trying to type in python ex1.py. / ex1.py is an ATOM program. Just for context; -----I'm using the 'Learn Python the Hard Way' website. The ATOM program still has an IDLE logo (even though I changed the default application). 'cd' produces no results. -
How do I make a form field read only or otherwise non editable in a django generic FormView?
I have a form that pre-populates the user field on page load with the currently logged in user. I would like to grey this field out so that the user can't change it to a user who isn't logged in. I would like for the user to be able to change the rest of the fields. I've tried using the init function on the model form and the view to no avail. Any pointers would be appreciated. forms.py: class PtoRequestForm(forms.ModelForm): class Meta: # Model to be used in the form. model = PtoHistory # Define which model fields to include in the form. fields = [ 'user', 'start', 'end', 'leave_type', ] # Attach input widgets to fields for a friendlier user interface. widgets = { 'start': DateTimeWidget(attrs={'id':'start'}, usel10n = True, bootstrap_version=3), 'end': DateTimeWidget(attrs={'id':'end'}, usel10n = True, bootstrap_version=3), } views.py: class IndexView(FormView): template_name = 'accounts/index.html' form_class = PtoRequestForm success_url = '/accounts' # Pre-populates the form with the specified values on page load. def get_initial(self): return {'user': self.request.user} # Function runs when form is submitted. Do whatever needed to the form before it's saved to the db. def form_valid(self, form): form.save() return super(IndexView, self).form_valid(form) # Function runs on page load. Gather any … -
Django csrf fails after logout login new user
Even if I understand the problem, I'm not sure how to solve this. I have a django powered api that has an endpoint that lets the user change the email. If the logged user A enters a already existing email, it checks if the logged user A entered a password that corresponds to the already existing user B object (i.e he owns another, older account). If that is the case, I have to logout the actual user A and login again the already existing B account. ... if User.objects.filter(email=email).exists(): # If the email already belongs to another account user = authenticate(username=email, password=password) if user is not None: # The user is the owner of the existing account, he has the password # Get already existing client object client_existing_user_obj = Client.objects.get(user=user) # get clients actual cart actual_cart = client.cart # update existing clients cart with newly created cart client_existing_user_obj.cart = actual_cart # logout user with the old email, login already existing user logout(request) login(request, user) ... The endpoint works correctly, it returns 200. However, the next post & put requests answer 403 - "detail": "CSRF Failed: CSRF token missing or incorrect." How can I solve this? Any advice will help. -
Any alternatives for OneToMany or ManyToOne in Django
I have a NOTIFICATION and an USER app in Django. The code goes something like : class Notification(models.Model): user = models.ForeignKey(User , related_name = "notification" .... .... and class User(models.Model): notifications = models.OneToManyField(Notification , related_name = "user" .... .... Now I know that models.OneToManyField doesn't exist in Django. I get the fact that I can simply access the user from the notification instance of the model. But I suppose that would somehow slow my system because in production I would keep all the instances of Notification Model. For example : I'm expecting around 500+ notifications per user once the system is in production for a significant amount of time. I suppose, it would just be easier to access all the notifications of one user directly rather than sifting through the whole Notification Table to find notifications of a specific user. I've read this and the documentation to an extent and I'm not able to find a solution to my problem. Also I'm not sure about the processing constraints of a processor to obtain all the Notifications from the whole Notification Table. I'm just assuming that it'll be somewhat slower. -
What is the use of email in Django Superuser?
Django asks to enter an email of while creating a superuser, What is the primary use of this & what would be a potential risk of a random email say like test@test.com or admin@admin.com ? -
Why can't I make my own test database for my django project?
I am currently deciding what testing packages to use with my django project, specifically how to populate data before I run tests. I have looked into: Fixtures: Many people seem to be against this since modifying JSON can be difficult and hard to maintain. Factory boy: My project has a lot of hierarchy to it, so I feel like creating an object from a model that is really low in the hierarchy is really slow. The idea I have in my mind is to just make a database that I will always run tests against. Since I know what data is in it, shouldn't it work similarly to fixtures without the hassle of JSON? Since I haven't seen this idea through my research, I assume this is a bad idea. Why is it a bad idea though? -
Django wont load media files from filefield to template
I want to display and audio stored in filefield but the links comes up dead even though when i upload files to through admin they are showing up in the media directory but are giving dead links in when page loads i even tried to change it from audio to an image with appropriate data still nothing #template {% for audios in Audios %} <audio controls> <source src="{{ audios.Audio_File.url }}" type="audio/mpeg"> </audio> {% endfor %} #settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' #urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) dja Also here is the entire settings file just incase import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'kv=%#$g8bjbu+b6)#(z@5kp2*-40rz6e6&3h$6dpt$&55+jep@' ALLOWED_HOSTS = [] STATIC_URL = '/static/' INSTALLED_APPS = [ 'speak.apps.SpeakConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'speakEnglish.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'speakEnglish.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = … -
Double loop with django GABARITS
so I have this matrix sent to a view [[6.197, 6.156, 6.165, 6.164, 4.741], [6.191, 6.106, 6.175, 6.132, 4.741], [6.158, 6.137, 6.137, 6.133, 4.741]] and a list containing dates ["11-12-2016","12-12-2016","13-12-2016"] and I want to format them with GABARIT to look like this [["11-12-2016",6.197, 6.156, 6.165, 6.164, 4.741] ["12-12-2016",6.191, 6.106, 6.175, 6.132, 4.741] ....] Iam using this code : {% for date in dates %} {% with forloop.counter0 as i %} ,["{{date}}"{% for item in selling.i %} ,{{item}} {% endfor %}] {% endwith %} {% endfor %} and it doesn't work , but when I replace i with 0,1.. the second loop works fine on one list -
How to get id from Queryset Django
I need get id from Queryset Сode: def button(self, request, queryset): return '<a class="button" href="{}">Print</a>'.format(reverse('act', args=str(queryset.values_list('id', flat=True).order_by('id')))) button.short_description = 'Actions' button.allow_tags = True But I get an error: Reverse for 'act' with arguments '('<', 'Q', 'u', 'e', 'r', 'y', 'S', 'e', 't', ' ', '[', '2', ']', '>')' and keyword arguments '{}' not found. 1 pattern(s) tried: ['act/(?P<obj>[\\w-]+)$'] Could you help me get only id from Queryset? -
Django Chartit is not displayng yAxis data
I am using Django 1.10.3 and python 3.4.2 For some reason chartit is not displaying graph line on my chart plot. However I can see 'data' when I do view-source in my browser. Please point me where I was wrong. my graph (without graph) here is what view-source displays <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script type="text/javascript" src="http://code.highcharts.com/highcharts.js"></script> </head> <div id='cont'><script type="text/javascript"> var _chartit_hco_array = [{"yAxis": [{"title": {"text": "Temp"}}], "series": [{"stacking": false, "data": ["20.83", "20.83", "21.61", "22.11", "23.00", "23.17", "23.94", "24.67", "24.94", "24.94", "25.00", "25.00"], "type": "line", "name": "temperature"}], "xAxis": [{"categories": ["2016-12-16T11:40:13+00:00", "2016-12-16T11:40:13+00:00", "2016-12-16T12:00:32+00:00", "2016-12-16T12:20:51+00:00", "2016-12-16T13:20:56+00:00", "2016-12-16T13:40:22+00:00", "2016-12-16T14:00:41+00:00", "2016-12-16T14:21:00+00:00", "2016-12-16T14:40:26+00:00", "2016-12-16T14:47:29+00:00", "2016-12-16T14:51:02+00:00", "2016-12-16T14:54:34+00:00"], "title": {"text": "Date"}}], "chart": {"renderTo": "cont"}, "title": {"text": "Temp Data of Kedsum"}}]; </script> <script src="/static/chartit/js/chartloader.js" type="text/javascript"> </script></div> my views.py from chartit import DataPool, Chart from django.shortcuts import render from monitor.models import LogicLocation, SensorPrologue, SensorThgr122N, SensorKedsum #def graphs(request): # return render(request, 'graphs/graphs.html', {'content': ['Graphs Output!!!']}) def graphs(request): #Step 1: Create a DataPool with the data we want to retrieve. sensordata = DataPool( series= [{'options': { 'source': SensorKedsum.objects.all()}, 'terms': [ 'date', 'temperature']} ]) #Step 2: Create the Chart object cht = Chart( datasource = sensordata, series_options = [{'options':{ 'type': 'line', 'stacking': False}, 'terms':{ 'date': [ 'temperature'] }}], chart_options = {'title': { … -
Django - registration login.html as index
My app is hosted on shezankazi.pythonanywhere.com When I open this link I get to index.html. However I would like to open login.html directly as occurs when I choose "Anmelden" at the index page. Herefore I require assistance This is my views.py def index(request): return render(request, 'crm/index.html') This is my app/urls.py from django.conf.urls import url from django.conf.urls import include from django.contrib import admin from crm import views as crm_views from person import views as person_views urlpatterns = [ url(r'^$', crm_views.index, name='index'), url(r'^crm/', include('crm.urls')), ... ] And this is my crm/urls.py from django.conf.urls import url from crm import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^dashboard/', views.dashboard, name='dashboard'), ] And this is the end of my settings.py: # If True, users can register REGISTRATION_OPEN = False # One-week activation window; you may, of course, use a different value. ACCOUNT_ACTIVATION_DAYS = 7 # If True, the user will be automatically logged in. REGISTRATION_AUTO_LOGIN = False # The page you want users to arrive at after they successful log in LOGIN_REDIRECT_URL = '/crm/dashboard/' # The page users are directed to if they are not logged in, # and are trying to access pages requiring authentication LOGIN_URL = '/accounts/login/' # The page users are directed …