Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tests to valid that an Django Object has other Objects with it as a foreign key
I'm writing a website that lets people create their own interactive quizzes. I have three Objects: Quiz, Question and Answer. Question has a Quiz field (which uses Quiz as a foreign key), Answer has a Question field (which uses Question as a foreign key). I'd like to make sure that a Quiz has at least one question and that a Question has at least two Answers. I've had trouble because in order to even add a Question to a Quiz, I must first save the quiz. -
Django ajax 403 because of httponly cookie
I have a strange issue with CSRF in Django. Here are the relevant portions: In my javascript file I have: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $(function () { $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); }) $.post('/api/jpush', $.param({'recipients': recipients, 'message': message, 'url': url, 'url_title': url_title, 'priority': priority, 'csrftoken': getCookie('csrftoken')}), ... then I have in my view: def push(request): return render(request, 'api/push.html') def jpush(request): tmplData = {'result': False} if not request.POST: return HttpResponseBadRequest(request) elif request.POST.viewkeys() & {'recipients', 'message', 'priority'}: tmplData = { 'results': send(request.POST) } return JsonResponse(tmplData) .... and in my template: <form id="push" class="form-horizontal" action="" method="post">{% csrf_token %} However when I post using ajax I get a 403 and firebug shows me that β¦ -
Can not update DateTime field in database
I'd like to update lastposted field in the views : print 'going to update lastposted', topic_id, timezone.now() Topic.objects.filter(pk=topic_id).update(lastposted=timezone.now()) topic = Topic.objects.get(pk=topic_id) topic.lastposted = timezone.now() topic.save() print 'now topic.lastposted is:' , topic.lastposted Which prints out this in the terminal: going to update lastposted 283 2017-02-09 15:38:44.817672+00:00 now topic.lastposted is: 2017-02-09 15:38:44.819416+00:00 However the field is not updated in the database. The value is still 2017-02-07 16:57:38 The model is: class Topic(models.Model): nid = models.IntegerField(default=0) title = models.CharField(max_length=300, blank=False) description = models.TextField(max_length=10000, blank=False) forum = models.ForeignKey(Forum) created = models.DateTimeField(auto_now_add=True) creator = models.ForeignKey(User, blank=True, null=True) updated = models.DateTimeField(auto_now=True) lastposted = models.DateTimeField(blank=True) And the table description: mysql> SHOW CREATE TABLE myforum_topic \G; *************************** 1. row *************************** Table: myforum_topic Create Table: CREATE TABLE `myforum_topic` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nid` int(11) NOT NULL, `title` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `description` longtext COLLATE utf8_unicode_ci NOT NULL, `forum_id` int(11) NOT NULL, `created` datetime NOT NULL, `creator_id` int(11) DEFAULT NULL, `updated` datetime NOT NULL, `lastposted` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=270419 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci The odd thing is that the update sometimes works, but not most of the times. This problem bugs me for days. Really appreciate your hints to fix it. -
How to disable authentication altogether for Django admin
I have a Django server (Using PostGis) and I want to disable everything related to authentication: When entering the admin no authentication will be required In the admin hide the Users/Groups After searching online I tried the combination of this & this It does get me the result I hoped for, until I try to add an object via the admin. Then I get an IntegrityError: insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: Key (user_id)=(1) is not present in table "auth_user". I tried solving it using solutions like this and it didn't help. I don't mind having a solution in a whole new approach as long as the end goal is acquired. Thanks ahead, -
APIView stopping another view from working
I have the following urlpatterns and APIViews for getting JSON data. They all work and return data as they should except for the last one 'pollutant_daily_means'. When I remove the view for 'site_daily_means' then the 'pollutant_daily_means' returns the data that it should. If I remove just the 'site_daily_means' above it then it still doesn't work, so it must be something to do with the site_daily_means view interfering somehow. url(r'^api/daily-means/$', views.daily_means.as_view(), name='daily_means'), url(r'^api/daily-means/(?P<url>\w+)/$', views.site_daily_means.as_view()), url(r'^api/daily-means/(?P<poll>\w+d+)/', views.pollutant_daily_means.as_view()), class daily_means(APIView): def get(self, request): means = DailyMean.objects.all() serializer = DailySerializer(means, many=True) return Response(serializer.data) class site_daily_means(APIView): def get(self, request, url): means = DailyMean.objects.filter(url=url) serializer = DailySerializer(means, many=True) return Response(serializer.data) class pollutant_daily_means(APIView): def get(self, request, poll): means = DailyMean.objects.filter(poll=poll) serializer = DailySerializer(means, many=True) return Response(serializer.data) Can anybody see any clear reasons for this from the above urls and views? -
Django - First time viewers sometimes are shown a login_required page
While showing my website to people, I have noticed that sometimes, when viewing the website for the first time, the wrong page is displayed. views.py from django.contrib.auth.decorators import login_required def index(request): if request.user.is_authenticated(): return HttpResponseRedirect('/home/') else: return render(request, 'free/landing_page.html') @login_required def home(request): ... def login_user(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None and user.is_active: login(request, user) return HttpResponseRedirect("/home/") else: errors = "True" return render(request, 'registration/login.html', {'errors': errors}) else: return render(request, 'registration/login.html') and urls.py url(r'^$', views.index, name="index"), url(r'^home/$', views.home, name="home"), The idea is to have the home page displayed, if a user already has an account and is authenticated. And if the user is not authenticated then the landing page should be displayed. So here we go, What I have noticed, is a first time viewer of the website sees the home page rather than the landing page, and to make it even worse, the home page is populated with information from another user's account. From here, if you click on any link you are redirected back to the landing page where you can properly create an account or login. It is strange because the few times this has β¦ -
Django Model: Add meta data to model class
Is it possible to add meta data to a Django model? I want to attach meta data to the model class. The meta data is static and should not be stored in the database. The above example crashes, but illustrates what I want to do. Example: class SomeModel(models.Model): easy_name = "Some model" more_meta_data = {"can be a dict?": True} # Actual database fields under this line Access the meta data: print(SomeModel.easy_name) -->Some model -
Images in Browser are broken
Images in Browser are broken. Now,by using Google's Inspect Element, I found my images src are like In my app, images are in image(child app)/images/ directory. So,I deleted images from src and changed into src="/image/images/xxx.jpeg",but images are still broken. I tried to write full path of images in search box of Google(it is like file://Users/Desktop/AppName/image/images/xxx.jpeg),but a browser error happen.But,I wrote full path of images in search box of there and I designate images in my computers(it is like file://yname/Desktop/xxx.jpeg),images were shown in browser. So,I really cannot understand how to fix it. In views.py,I wrote def upload_save(request): photo_id = request.POST.get("p_id", "") if (photo_id): photo_obj = Post.objects.get(id=photo_id) else: photo_obj = Post() files = request.FILES.getlist("files[]") photo_obj.image = files[0] photo_obj.save() photos = Post.objects.all() context = { 'photos': photos, } return render(request, 'registration/accounts/photo.html', context) In photo.html, {% extends "registration/accounts/base.html" %} {% block content %} <div class="container"> {% for photo in photos %} <h2 class="page-header">{{ photos.title }}</h2> <div class="row"> <div class="col-xs-4"> <img class="img-responsive" src="/image/images/{{ photo.image }}"> </div> </div> <a class="btn btn-primary" href="{% url 'accounts:upload' photo.id %}">UPLOAD</a> {% endfor %} </div> {% endblock %} What should I do? -
Isn't there collectstatic equivalent for django collect media command?
How to collect media files from different django project applications into one folder to be easier to deploy in production to be served by Nginx/Apach ? -
how can i makemigrations djano models in custom path?
I want create practice web game using python(django) + javascript my project name is lucifer the path is βββ Makefile βββ README.md βββ lucifer β βββ db.sqlite3 β βββ game β β βββ __init__.py β β βββ character β β β βββ __init__.py β β β βββ models β β β βββ __init__.py β β β βββ character.py β β βββ skill β β βββ __init__.py β β βββ models β β βββ __init__.py β β βββ skill.py β βββ lucifer β β βββ __init__.py β β βββ settings β β βββ templates β β βββ urls.py β β βββ views β β βββ wsgi.py β βββ manage.py β βββ posts β β βββ __init__.py β β βββ forms.py β β βββ models β β βββ templates β β βββ views β βββ users β βββ __init__.py β βββ admin β βββ models β βββ templates β βββ views the app is posts, users, game and models of game are in game app, INSTALLED_APP INSTALLED_APPS = [ # ... # 'rest_framework', 'django_summernote', 'lucifer', 'users', 'posts', 'game', ] when I manage.py makemigrations users posts game character, skill model does not migrations.. how can i makemigrations my game's models? thank you -
Form action isn't triggering at all
Basically I am currently trying to work around the fact that you have to do a HttpResponseRedirect after form submission to avoid repeat submissions on page refresh. So I want my submit button for my form to trigger another view, not submit the current view. Here is my html: (I've taken the form out because there's lots of code to render the table horizontally) <form id= "time-form" method = 'POST' action='' class="dynamic-form" enctype="multipart/form-data">{% csrf_token %} <div id="formset-container" class = "formset-container"> <table> <--form is in here--> </table> <ul>{{ newtime_formset.errors }}</ul> </div> </br> <div> <input type = "submit" id = "save" action="{% url 'tande:create_time' %}" value = "Save Timesheet"> </div> So I want the submit button to execute the create_time view. We are currently in a view called timesheet. But it's not entering the create_time view at all it just stays in the current view. def create_time(request): #below isn't printing print "create_time view" #save the form in here return HttpResponseRedirect('timesheet') And the url for both view: from django.conf.urls import url from . import views urlpatterns = [ url(r'^(?P<timesheet_id>[0-9]+)/person/timesheet/$', views.timesheet, name='timesheet' ), url(r'^create_time/$', views.create_time, name='create_time' ), ] So I want to save the timesheet in create_time and then go back to timesheet to β¦ -
Django diferrent value of DateTimeField at created/updated
I would like to store time of created and modified. But when I use below model: date_created = models.DateTimeField(auto_now_add=True) date_update_local = models.DateTimeField(auto_now=True) auto_now_add does't work properly. If I created object at first time, everything is ok, I have properly value of date_created, but if I modify exist object then date_update is set to 0000-00-00 00:00:00.000000. So I modified my code as below: Models.py class Product(models.Model): reference = models.CharField(max_length=8, unique=True, primary_key=True) date_created = models.DateTimeField(default=timezone.now) date_update_local = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): try: p = Product.objects.get(reference=self.reference) self.date_created = p.date_created except self.DoesNotExist: pass return super(Product, self).save(*args, **kwargs) Views.py p = Product(reference = 'no. ref') p.save() I am checking does object exist, if True, I am get last date_created value and set it as new value. But I think it is wrong solution. -
How to call url uniquely which has same number of parameter from django template
I have an issue in django template while calling url on my anchor tag. Here is my anchor on my template <a href="{% url 'info_page' detail.slug %}"> I have bellow url pattern, urlpatterns = [ url(r'^cars/', include([ url(r'^$', category_page, name=cars), url(r'^(?P<slug>[\w-]+)/$', category_page, name=cars), ]) ), url(r'^cars/', include([ url(r'^$', info_page_view, name='info_page'), url(r'^(?P<slug>[\w-]+)/$', info_page_view, name='info_page'), ]) ) ] Basically I would like to redirect this anchor url to my 'info_page_view' defination defined in views, but its actually landing it into 'category_page' defination. I might be missing some url parameter while calling from template but not getting the exact solution for that. As I'm calling urls by their name given, How do I differentiate these urls and call them uniquely from template to landup in expected view. Please suggest. -
Django the powerpoint generated using python-pptx library has error message
I use python-pptx v0.6.2 to generate powerpoint. I read a exist powerpoint into BytesIO, then do some modification and save it. I can download the file successfully, and I'm sure the content can be write into the file. But when I open the powerpoint, it will popup a error message "Powerpoint found a problem with content in foo.pptx. Powerpoint can attempt to repair the presatation.", then I have to click "repair" button, the powerpoint will display as "repaired" mode. My Python version is 3.5.2 and Django version is 1.10. Below is my code: with open('foo.pptx', 'rb') as f: source_stream = BytesIO(f.read()) prs = Presentation(source_stream) first_slide = prs.slides[0] title = first_slide.shapes.title subtitle = first_slide.placeholders[1] title.text = 'Title' subtitle.text = "Subtitle" response = HttpResponse(content_type='application/vnd.ms-powerpoint) response['Content-Disposition'] = 'attachment; filename="sample.pptx"' prs.save(source_stream) ppt = source_stream.getvalue() source_stream.close() response.write(ppt) return response Any help is appreciate, thanks in advance! -
Python-Snapchat API
I need to integrate an upload plugin from my web portal to user SnapChat account. My backnd server is written in Python, and using a package it was working last year. Now all my upload request are keep failing without no reason. I have been searching for a working solution for more than a week, but didnt find any luck. So can you please guide me to make this working or a latest REST API documentation is more helpful. -
how to update image file in django with angularjs and rest api
I want to update file in django. I am using rest API with angularjs. I am using angularjs for post request to django rest api.I am getting blank multivalue dictionary in python side. So any one can help me how pass file in django rest api Code: (function() { var UpdateCompanyInformationApp = angular.module('UpdateCompanyInformationApp', []); UpdateCompanyInformationApp.config(function($httpProvider) { $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; $httpProvider.defaults.paramSerializer = '$httpParamSerializerJQLike'; //$httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript'; //$httpProvider.defaults.headers.post['Content-Type'] = 'multipart/form-data; charset=utf-8'; //$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; }); UpdateCompanyInformationApp.directive('fileModel', ['$parse', function ($parse) { return { restrict: 'A', link: function(scope, element, attrs) { var model = $parse(attrs.fileModel); var modelSetter = model.assign; element.bind('change', function(){ scope.$apply(function(){ modelSetter(scope, element[0].files[0]); }); }); } }; }]); $scope.update = function(file) { console.log((file)); //Take the first selected file //alert($("#about").val()); //alert($("#company_logo").val()); data_obj = { about : $("#about").val(), file : file, company_id : $scope.company_id } //,{transformRequest: angular.identity,headers: {'Content-Type': 'multipart/form-data'}} console.log(data_obj); $http.post("/api/update-company-information/",data_obj).success(function(data) { console.log(data); $scope.data = data; }); }; }); }); })(); <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script> <div class="row" ng-controller="UpdateCompanyController" ng-init="company_id={{ request.user.id }}"> <form class="form-horizontal" method="post" name="UpdateInformation" id="UpdateInformation" ng-submit="update(myFile)" enctype="multipart/form-data"> <div class="col-md-3"> <img src="{{ company.company_logo.url }}" id="company_logo"> <input type='file' name='company_logo' id='company_logo' ng-model='company.company_logo' file-model='myFile'/> </div> <div class="col-md-9"> <section class="content"> <div class="box"> <div class="box-header with-border"> <h3 class="box-title">About Company</h3> </div> <div class="box-body" id="desc"> </div> </div> <input type='submit' value='Update' β¦ -
Django REST Framework JSON API: Could not resolve URL for hyperlinked relationship when using ResourceRelatedField
I am sorry if I'm asking obvious question here. I am new to world of JSON APIs. I would appreciate any help. I am writing an HTTP API that uses django + django REST framework + django REST framework JSON API. When I tried to do PATCH request I received this error: "Incorrect type. Expected URL string, received OrderedDict" when updating relationship. Looking through issues I understood I need to use ResourceRelatedField. I'm trying to follow documentation here Related fields. Below is how my code looks like. urls.py from django.conf import settings from django.conf.urls import include, url from rest_framework import routers from events import views as e_views router = routers.DefaultRouter() router.register(r'events', e_views.EventViewSet) router.register(r'event-types', e_views.EventTypeViewSet) urlpatterns = [ url(r'^', include('events.urls')), url(r'^', include(router.urls)), ] events/urls.py from django.conf.urls import url from .views import EventRelationshipView urlpatterns = [ url( regex=r'^events/(?P<event_pk>[^/.]+)/relationships/(?P<related_field>[^/.]+)$', view=EventRelationshipView.as_view(), name='event-relationships' ) ] models.py from datetime import timedelta from django.db import models from django.contrib.gis.db import models as gis_models class EventType(models.Model): title = models.CharField(max_length=16) def __str__(self): return str(self.title) class Event(models.Model): timestamp = models.DateTimeField() delay = models.DurationField(default=timedelta(0)) event_type = models.ForeignKey(EventType) name = models.CharField(max_length=16) location = models.CharField(max_length=200, blank=True) coordinates = gis_models.PointField(null=True, blank=True) depth = models.CharField(max_length=64, blank=True) size = models.IntegerField(null=True, blank=True) comments = models.TextField(blank=True) is_virtual = models.BooleanField(default=False) β¦ -
implementing user authentication to django app which uses mongodb in backend
I am creating django app, I am using - django 1.10 mongodb in backend. To connect with mongodb I am using mongoengine 0.11 and pymongo 3.4 I have built all the pages which I needed. Now I need to implement Authentication to application, also app will display pages user specific [ functionality need to implement yet]. Can you please suggest best way to do it. I searched alot but didn't find any specific solution. Does using multiple database will solve the problem.[ mysql for authentication and mongodb for all the other data ]. -
Django query to group records with created field
models.py class Post(models.Model): caption = models.CharField(max_lenght=200) description = models.TextField() created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) I am looking for django single query which will give me result like: data = { "YYYY-MM-DD": [{<post data one>}, {<post data two>}], "YYYY-MM-DD": [{<post data one>}, {<post data two>}], "YYYY-MM-DD": [{<post data one>}, {<post data two>}], } "YYYY-MM-DD" will map to date value of created field of Post Table -
integrating django and sentry inside docker
I have running Django project in docker. I want to add sentry. Logging is working from localhost but from web I have connection refused. My Django config looks ok because when I checked some other sentry server, log appears correctly. I wrote simple script to test my logging using python, I've tried to replace localhost by sentry but still connection refused error: script.py from raven import Client client = Client('http://ad75eaa4541f4a0889cb495e75190796:b1598cc34edd45d79e4c88758c44946d@localhost:9000/3') try: 1 / 0 except ZeroDivisionError: client.captureException() docker-compose.yml version: '2' services: postgres: ... nginx: image: nginx:1.10 ports: - "8000:80" depends_on: - web redis: image: redis:latest celery: image: celery:3 environment: - CELERY_BROKER_URL=redis://redis depends_on: - redis web: build: context: . dockerfile: Dockerfile-web image: my-web command: /usr/bin/supervisord -nc /etc/supervisor/supervisord.conf volumes: - ./supervisor.conf:/etc/supervisor/conf.d/webservers.supervisor.conf - .:/vagrant ports: - "2222:22" depends_on: - postgres - redis - celery sentry: image: sentry:8.3 volumes: - "./sentry.conf.py:/home/sentry/.sentry/sentry.conf.py" links: - redis - postgres ports: - 9000:9000 stdin_open: true tty: true environment: SENTRY_SECRET_KEY: ad75eaa4541f4a0889cb495e75190796:b1598cc34edd45d79e4c88758c44946d SENTRY_POSTGRES_HOST: postgres SENTRY_DB_USER: sentry SENTRY_DB_PASSWORD: sentrypostgres SENTRY_REDIS_HOST: redis depends_on: - postgres - redis - web command: "sentry start --upgrade" sentry_celery_beat: image: sentry:8.3 links: - redis - postgres environment: SENTRY_SECRET_KEY: ad75eaa4541f4a0889cb495e75190796:b1598cc34edd45d79e4c88758c44946d SENTRY_POSTGRES_HOST: postgres SENTRY_DB_USER: sentry SENTRY_DB_PASSWORD: sentrypostgres SENTRY_REDIS_HOST: redis depends_on: - sentry - postgres - redis - web command: β¦ -
Static html pages in Django
I'm working in a project(My first one) and decided to design the pages first. By now I'm already done with 85% of the designing. For designing I've used HTML, CSS, JS. I've thought of Using Django in the back end. This is the first time ever I'm using Django. I was not aware of the Django templates. when I got to know about it from that moment I'm in a dilemma. Though the template library seemed very good to me but I don't know what to do now. How to deal with it. Please give some advice.. Whether I should use the static files or modify them. I've a deadline to submit with in three days from today. -
Not able to create super user in Django, Virtualenv
I'm trying to create superuser in django but keep getting this error message. Superuser creation skipped due to not running in a TTY. You can run `manage.py createsuperuser` in your project to create one manually. I tried eclipse custom command first and than I saw some people able to create super user using window command line with virtualenv, so I installed and activated it. However till now I wasn't able to create superuser. What I've been typing in the cmd is C:\Users\name>python Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> python manage.py createsuperuser File "<stdin>", line 1 python manage.py createsuperuser ^ SyntaxError: invalid syntax I tried this too. C:\Users\name>python manage.py createsuperuser python: can't open file 'manage.py': [Errno 2] No such file or directory -
Push notifications with service workers in django
I'm trying to implement push notifications in my django web app. I'm new to service workers and I can't find any working examples of how to implement this in django. Has anyone managed to implement this in django? Any help is welcome -
Django - Saving User Input
I'm new to Django, so please forgive me if my question isn't clear. I created a page that has a form for requested information (a field for each requested information) and a dropdown menu for the user to select an option. My question is this, how can I save this information? Perhaps in a table. I'm going to need this data to be used elsewhere in my website, but I don't know how to save it. Again, sorry if my question is vague. Please let me know if you need more information and I appreciate any help. -
Django Filter query set
On my "training" website i show product (that working) now i want to add some button with filter sort by name price etc. This is my views def product_list(request, category_slug=None): category = None categories = Category.objects.filter(man=True) products = Product.objects.filter(section='man', available=True) flt = Product.objects.filter(section='man', available=True).order_by('-name') products = products.filter(category=category) return render(request, 'shop/product/list.html', {'category': category, 'categories': categories, 'products': products, 'flt': flt}) so how can i make when i click button my product sort by name , price etc ?