Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
writing an example django form like class
I am working with flask and need django form like class so that in flask view i can simply instantiate a class and check its validity.Something like this. class MyForm(Form): username = StringField(null=True) class StringField(object): def __init__(self, value=None, null=False): self.value = value.strip() if value is not None else value self.nullable = nullable def clean(self): if self.null: if self.value in ('', None): return self.value else: if self.value in ('', None): raise Exception( "Value can not be null or blank" ) try: self.value = str(self.value) except: raise Exception( "Value is neithe string nor can be coerced into one" ) in my views i want do this mf = MyForm(data_dict) if mf.is_valid():pass Problem is: how to get all fields like username, email etc in constructor of our main Form class (one which gets inherited), so that i can apply some validation to its attributes as these fields can be variable in number -
Django: The joined path is located outside of the base path component
i'm using Django 10 and i dont know why after i collect my static files successfuly, when i try to run server in deployment mode(debug=False) it occurs me something like this: When i look for a static file by doing: python manage.py findstatic /static/mysite/js/javascript.js django.core.exceptions.SuspiciousFileOperation: The joined path (/static/mysite/js/javascript.js) is located outside of the base path component (/home/xxxx/.venvs/mysite/local/lib/python2.7/site-packages/django/contrib/admin/static) I run this using a virtual env 'mysite'. In settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") (i tried also just only 'static') MEDIA_ROOT = BASE_DIR + '/mysite/media' MEDIA_URL = '/media/' my urls.py: urlpatterns = [ url(r'', include('mysite.urls')), ] urlpatterns += staticfiles_urlpatterns() This is new for me, i also did already a django website and it never occurs such error. Why is not considering my STATIC_ROOT path? For the other hand the collectstatic works fine. And if i runserver with a debug a true it works like a charm. -
Using graphene-django, how can I define a circular relationship between two nodes?
Using the following contrived example: from django.db import models from django_filters import FilterSet, OrderingFilter from graphene import ObjectType, Schema, relay from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField class Recipe(models.Model): name = models.CharField(max_length=50) ingredients = models.ManyToManyField('Ingredient', related_name='recipes') class Ingredient(models.Model): name = models.CharField(max_length=50) class RecipeFilter(FilterSet): order_by = OrderingFilter(fields=[('name', 'name')]) class Meta: fields = {'name': ['icontains']} model = Recipe class IngredientFilter(FilterSet): order_by = OrderingFilter(fields=[('name', 'name')]) class Meta: fields = {'name': ['icontains']} model = Ingredient class RecipeNode(DjangoObjectType): ingredients = DjangoFilterConnectionField(IngredientNode, filterset_class=IngredientFilter) class Meta: interfaces = [relay.Node] model = Recipe only_fields = ['name'] class IngredientNode(DjangoObjectType): recipes = DjangoFilterConnectionField(RecipeNode, filterset_class=RecipeFilter) class Meta: interfaces = [relay.Node] model = Ingredient only_fields = ['name'] class Queries(ObjectType): all_recipes = DjangoFilterConnectionField(RecipeNode, filterset_class=RecipeFilter) all_ingredients = DjangoFilterConnectionField(IngredientNode, filterset_class=IngredientFilter) schema = Schema(query=Queries) How can I define the circular relationship between RecipeNode and IngredientNode such that I can run the following GraphQL query: { allRecipes(name_Icontains: "gg") { edges { node { name ingredients(name_Icontains: "gg") { edges { node { name } } } } } } allIngredients(name_Icontains: "gg") { edges { node { name recipes(name_Icontains: "gg") { edges { node { name } } } } } } } As it stands, I cannot reference IngredientNode from RecipeNode since it is not yet defined. … -
Django + pyodbc + MS LocalDB ghost instance
I'm trying to set up a Python project with a LocalDB instance. Because of business restrictions, I'm tied to a MS SQL Server 2014 backend to use with Django 1.8 and I'm trying to connect to it with pyodbc drivers. I want to use a LocalDB instance instead of SQL server for development, but I'm running into some problems. I got the connection working with the following settings. Django settings: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'my_db', 'HOST': '(localdb)\\hands-on', 'Trusted_Connection': 'yes', 'PORT': '', 'OPTIONS': {'driver': 'SQL Server Native Client 11.0', 'Integrated Security': 'true', }, 'TEST': { 'NAME': 'test_my_db', }, } } I created this instance with my SqlLocalDB.exe: Name: hands-on Version: 12.0.2000.8 Shared name: Owner: COMPANY\MY_ACCOUNT Auto-create: No State: Stopped Last start time: 27-12-2016 16:53:55 Instance pipe name: I created my_db in the instance with SSMS and the connection is made. Presto! However, there is a bit of an issue. When I start the Django application, it automatically starts the LocalDB instance (I can see a sqlservr.exe running in Task Manager under my user account). But when I run SqlLocalDB.exe info hands-on, the output is State: Stopped When I open SSMS and connect to (LocalDB)\hands-on the connection is … -
Django/Haystack: 404 error when doing rebuild_index using elasticsearch
I am using elastic search for my Django project. I am unable to indexing for my instances. when i do manage.py rebuild_index, it returns GET /haystack/_mapping [status:404 request:0.012s] Because of this, it shows none when i run SearchQuerySet().all() in shell. I would appreciate helping me solve this. -
Is it possible to change the passed query parameter "next" for social login
When linking accounts to fb messenger, fb calls the passed URI for login with a query parameter redirect_uri and a CALLBACK_URL. A redirect, to redirect_uri, with an authorization_code if login succeeds must be performed. If I want to perform the login using social login an issue appears related to what is explained here . The OAUTH handshake is done respecting the next parameter. Where it's advisable to create a next parameter reflecting redirect_uri such that the redirection takes place and doesn't disrupt all this great package. If I wait to reach get_login_redirect_url the parameter is already dropped when logging in. If it's logged it will be available for the redirect. -
OperationalError at /admin/blog/theme/add/ no such table
I know, that's a old question, but other themes dont help me. After new "git pull" i add a new model (Categories) and bind her with model Post. Now i have a that's objects on page create theme or post: OperationalError at /admin/blog/theme/add/ no such table python manage.py makemigrations blog python manage.py migrate That's first what i enter, but that's not helped. In second try i writed in model Post that string: category = models.ForeignKey('Theme', default='') But error is not disappeared. What am i need to do? There is a code both models: class Post(models.Model): author = models.ForeignKey('auth.User') category = models.ForeignKey('Theme', default='') title = models.CharField(max_length=200,verbose_name='Заголовок') text = models.TextField(verbose_name='Текст') created_date = models.DateTimeField(verbose_name='Время создания',default=timezone.now) published_date = models.DateTimeField(verbose_name='Время публикации',blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def approved_commentimages(self): return self.comments.filter(approved_comment=True) def __str__(self): return self.title class Theme(models.Model): title = models.CharField(verbose_name='Заголовок', max_length=40) def __str__(self): return self.title I think problem with old objects class Post. They dont have a field 'category' and that's is root of error. But default='' dont help. -
Populating db data for django's built-in testing tools
I'm using Django(1.8) + DRF + uwsgi + nginx and trying to unit-test API that I've made. To run tests I need to populate db (create users, for example) and use this data in all tests. So I've tried two ways: Create directly in TestCase.setUp: class ApiTests(TestCase): def setUp(self): Account.objects.create_user(username='username', password='password') Or use fixtures: class ApiTests(TestCase): fixtures = ['dump.json'] Next I run my project through supervisor: system("service supervisord startall") After everything is ready I try to access my API in test to login, using: login_data = {"username": "username", "password": "password"} rslt = client.post(HOST_NAME + '/login/', data=login_data) ... but I can't authorize, because users somehow don't exist in the db! As I've found in the docs to Django tests, TestCase doesn't write data into db, but store it in a transaction, that is rolled back after testing. And as I can see I can get this data only on test-side (using User.objects.all() that is showing that users are created), but not on my nginx-server-side (User.objects.all() on this side shows 0 items). ATM I can see few options: Somehow force TestCase to commit data into db. Populate data in other methods (but which?). Use different testing libs. Could you please help? -
Running django management command on docker cloud
I have a few django commands that are required to run periodically. Crontab for one of them: */10 * * * * cd /usr/src/app && python manage.py expire_orders | logger My whole stack is run under docker cloud. When I log in, go to my cron terminal and type: python manage.py expire_orders then the management task is run. It's not run automatically from cron. My command also generates some output like "starting: expire_orders cmd" which I can see in the console while running it manually, but can't see anywhere (logger puts it to /var/logs/syslog I guess) if I rely on cron. Any help? -
Django queryset working differently in SQLite than PostgreSQL
The following code works as expected with SQLite: if burial_date >= 1500 and burial_date <= 2100: burial_query = Q(burial_date__year=burial_date) else: if burial_date == 0: burial_query = Q() else: burial_query = Q(pk__in=[]) if last_name != '' or first_name != '' or burial_date != 0: burial_set = BurialRecord.objects.filter( burial_query, last_name__istartswith=last_name, first_name__istartswith=first_name ).order_by( 'last_name', 'first_name', 'burial_date' ) else: burial_set = BurialRecord.objects.none() However, with PostgreSQL, it returns an empty queryset whenever first_name is not an empty string. I originally tried Q objects for all three filters and got the same result. Any help is much appreciated. -
Incremented CharField
is there any possibility to define a Field which gets incremented, but starts with a letter? So the values should be like: S123, S124, S125. I' d like to use the id field for it, but some reason i' d like to have it as a CharField. As a workaround i could use: id = models.CharField(max_length = 32, primary_key = True) and redefine the save method, so i always precalculate its value, but this won' t be that robust than a "real" solution, and also my solution would too slow with the calculation. Is there a proper solution for my problem? Django: 1.9.2 Python: 3.4.2 . -
Getting 'undefined' when trying to get value from Parsed xhr.responseText
I have this javascript function where it makes a GET request to my Django server and get a JSON response but when i try to get the values from the json after parsing xhr.responseText with JSON.parse(), I get 'undefined'. What and Where am I doing it wrong? function getSignedRequest(file){ const xhr = new XMLHttpRequest(); xhr.open('GET', `/sign-s3?file-name=${file.name}&file-type=${file.type}`); xhr.onreadystatechange = () => { if(xhr.readyState === 4){ if(xhr.status === 200){ const response = JSON.parse(xhr.responseText); //var apple = JSON.parse(xhr.responseText); console.log(xhr.responseText); alert(response.url); //gives undefined console.log(response); //uploadFile(file, response.data, response.url); } else{ alert('Could not get signed URL.'); } } }; xhr.send(); } This the JSON data i get after parsing it. It is a valid json. {"url": "https://myurlfromserver", "data": {"url": "https://myurlfromserver", "fields": {"myremainimg data"}}} -
Django REST: map 'update' to 'list' using CustomRouter
Problem explanation: There is a Django project using REST API. The router is defined as: router = routers.DefaultRouter() The Accounts router: router.register('accounts', AccountViewSet) accounts_router = NestedSimpleRouter(router, r'accounts') There are other routers under accounts_router which use standard paradigm (as described on Django Reference), e.g.: URL pattern: ^accounts/$ Name: 'account-list' URL pattern: ^accounts/{pk}/$ Name: 'account-detail' Problem: Now there is object which has only 1 instance - singleton_foo. Showing its details view as /accounts/foo_acc/singleton_foo/1 would be a bad idea, since user may expect #2, #3, etc. Goal: I want to use custom router to map '/accounts/foo_acc/singleton_foo/1' to '/accounts/foo_acc/singleton_foo'. Basically, I want to show and update singleton_foo details (update) in the list view (list) I have tried using something like: class SingletonNestedRouter(NestedSimpleRouter): routes = [ Route( url=r'^{prefix}/$', mapping={'get': 'list'}, name='{basename}-list', initkwargs={'suffix': 'List'} ), Route( url=r'^{prefix}/{pk}/$', mapping={'put': 'retrieve'}, name='{basename}-retrieve', initkwargs={'suffix': 'Retrieve'} ), ] And the attach the router to accounts: accounts_router.register('singleton_foo', SingletonFooViewSet, 'singletonfoo') ConfigNestedRouter(domains_router, r'speedtest_config', lookup='singleton_foo') Any suggestions? -
Is there a better way to store who likes, dislikes a profile in a relational database?
I'm creating a small django application in which, A users can see the number of likes and dislikes on his profile as well as who(other user) have liked or disliked his profile. My Current Solution Is : Table(ProfileView): user_from | user_to | response(0,1) In this table I'm storing who likes|dislikes the profile in 'user_from' and To whom he likes|dislike in 'user_to' and In response user_from either likes or dislikes user_to (0 means Like and 1 means dislike) But this solution isn't scalable and making queries like listing all the user(s) who have liked or disliked a particular profile will be quite inefficient. So, Is there any better option than this in a relational database and I using 'Postgresql'. -
How combined my templatetags and base filter |linebreaksbr
I have a problem with right sidebar in that site: http://antonigin.pythonanywhere.com/ I need to create linebreaks in text. I can add that in post, that's not a problem. But sidebar using my tag. @register.simple_tag def notetitle(value): note = Note.objects.get(pk=value) return note.title @register.simple_tag def notetext(value): note = Note.objects.get(pk=value) return note.text I create that template: {% load note_def %} {% block note %} <h1>{% notetitle 2 %}</h1> <p>{% notetext 2 %}</p> {% endblock %} I need a filter |linebreaksbr. And i dont know, how to insert this. Of course, i can send value with my note in every view and insert {% content block %} in every templates, but if i will want change sidebar, that's take a lot of time. -
django logout me after render_to_response()
this is my views.py def createpost(request, id=None): form = PostForm(request.POST or None, request.FILES or None) if form.is_valid() and request.method == 'POST': instance = form.save(commit=False) instance.user = request.user instance.save() messages.success(request, "successfully create!") return HttpResponseRedirect('/post') else: context ={ 'form': form } return render_to_response('createPost.html', context) and createPost.html code that i want show the post page with errors {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} {% if request.user.is_authenticated %} <form method="POST" name="PostForm" action="/post/createpost/" enctype="multipart/form-data"> {% csrf_token %} {{form|as_bootstrap_inline}} <input type="hidden" name="user_id" value="{{ user.id }}" /> <button type="submit" class="btn btn-primary">Save AD</button> {% else %} <div>Please Register First!</div> {% endif %} </form> {% endblock content %} but when happen error redirect and logout me. how can i post the authenticated user to my post page -
using django-rest-framework how query works for list fields?
I'm using get_queryset with Django-REST-Framework to build APIs for my app. I would like to know if there's a way to get this filter working http://api/data?district=Nasik,Pune to get all data with district "Pune" OR district "Nasik". I've tried with http://api/data?district=Nasik&district=Pune but as expected it does an AND between the filters and retrieve only the Pune district (i suppose because it's the last filter). Here is my code : from rest_framework_mongoengine.viewsets import ModelViewSet as MongoModelViewSet from app.serializers import * from mongoengine.queryset.visitor import Q class ToolViewSet(MongoModelViewSet): serializer_class = ToolSerializer def get_queryset(self, *args, **kwargs): queryset_list =Tool.objects.all() fruit=self.request.query_params.get("fruit") district=self.request.query_params.get("district") taluka=self.request.query_params.get("taluka") if fruit and district: queryset_list = queryset_list.filter( Q(fruit__icontains=fruit) &Q(district__icontains=district) ) return queryset_list if fruit and taluka: queryset_list = queryset_list.filter( Q(fruit__icontains=fruit) &Q(taluka__icontains=taluka) ) return queryset_list if district and taluka: queryset_list = queryset_list.filter( Q(district__icontains=district) &Q(taluka__icontains=taluka) ) return queryset_list elif fruit: queryset_list = queryset_list.filter( Q(fruit__icontains=fruit) ) return queryset_list elif district: queryset_list = queryset_list.filter( Q(district__icontains=district) ) return queryset_list elif taluka: queryset_list = queryset_list.filter( Q(taluka__icontains=taluka) ) return queryset_list so, this code working for two different fields, for example: htt/api/?data?fruit=Banana&district=Pune htt/api/?data?fruit=Banana&taluka=Haveli htt/api/?data?taluka=Haveli&district=Pune all are working but, http://api/data?district=Nasik,Pune this is not working, here I use this code for "OR" if district or district: queryset_list = queryset_list.filter( Q(district__icontains=fruit) &Q(district__icontains=district) ) return queryset_list … -
Check for online users in django(django 1.10 python 3.5)
I am developing an app where employees would log in and search for already uploaded data, I want to create a page for admin users where they can see which employees are online/offline/onBreak How can i achieve this ? -
Django/Haystack: SearchQueryset returns None with elasticsearch
I am using haystack with elasticsearch for my Django project. I have 1000 instances for my model and I do python manage.py rebuild_index. But when I do SearchQuerySet().all().count() in my shell it returns 0. I don't have any Ngram or EdgeNgram field in my search_indexes.py. Can some help me in solve this issue!! TraceBack when i do rebuild_index: Indexing 1000 instances GET /haystack/_mapping [status:404 request:0.002s] TraceBack when i do SearchQuerySet().all(): <SearchQuerySet: query=<haystack.backends.elasticsearch_backend.ElasticsearchSearchQuery object at 0x041E91D0>, using=None> TraceBack when i do SearchQuerySet().all().count(): File "c:\python34\lib\site-packages\haystack\backends\elasticsearch_backend.py", line 524, in search _source=True) File "c:\python34\lib\site-packages\elasticsearch\client\utils.py", line 69, in _wrapped return func(*args, params=params, **kwargs) File "c:\python34\lib\site-packages\elasticsearch\client\__init__.py", line 531, in search doc_type, '_search'), params=params, body=body) File "c:\python34\lib\site-packages\elasticsearch\transport.py", line 307, in perform_request status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout) File "c:\python34\lib\site-packages\elasticsearch\connection\http_urllib3.py", line 93, in perform_request self._raise_error(response.status, raw_data) File "c:\python34\lib\site-packages\elasticsearch\connection\base.py", line 105, in _raise_error raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info) elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception') 0 -
can we get the browser history using sessions and cookies in django
Is there any inbuilt function to track the browser history or any other way, it will b very helpful to me and thank you in advance -
Django behind Squid
please, I have problem with DJANGO behind reverse proxy SQUID... Squid is set so that after recieve request it redirect me to another local port. This redirect works. From DJANGO I recieve ERROR 404 with this: Request Method: GET Request URL: http://a.server.cz:5500/http://a.server.cz:5500/ {u'path': u'http://a.server.cz:5500/'} In terminal I see: [26/Dec/2016 21:41:00] "GET http://a.server.cz:5500/ HTTP/1.1" 404 1696 I think, that problem is, that squid add squid server address to absolute path of request ... Network scheme: :--------------------------: : : : INTERNET : : : :--------------------------: : : : request - a.server.cz:5500 : a.server.cz : :----------------------------: : : : squid: 5500 -> 5501 : : : : : : DJANGO: listen 5501 : : : :----------------------------: Please, can you help me? Thank you! -
Django: "Forbidden (403) CSRF verification failed. Request aborted." in Docker Production
I am getting this error whenever I am trying to login into Django Admin or Whenever I try to signup in my Django application. I am using Production in Docker and serving site with http. Whatever I know, this problem is arises because of serving it over http instead of https. Here is my production settings.py: SECURE_HSTS_SECONDS = 518400 SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool('DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS', default=True) SECURE_CONTENT_TYPE_NOSNIFF = env.bool('DJANGO_SECURE_CONTENT_TYPE_NOSNIFF', default=True) # SECURE_BROWSER_XSS_FILTER = True SESSION_COOKIE_SECURE = False SESSION_COOKIE_HTTPONLY = True SECURE_SSL_REDIRECT = env.bool('DJANGO_SECURE_SSL_REDIRECT', default=False) CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = True X_FRAME_OPTIONS = 'DENY' I know I have to make some changes into this setting to make it work, but I don't know which one. -
Django Rest Framework filtering foreign keys
I have been reading about filtering foreign keys in a ListAPIView, but I cannot seem to get it to work like I see in examples. class SomeViewSet(generics.ListAPIView): serializer_class = ProjectSerializer authentication_classes = (BasicAuthentication,) permission_classes = (IsAuthenticated,) def get_queryset(self): queryset = Project.objects.all() platform = self.request.query_params.get('platform', None) if platform is not None: queryset = queryset.filter(test__platform=platform) return queryset My serializer looks like this: class TestSerializer(serializers.ModelSerializer): class Meta: model = Test exclude = ['created'] class ProjectSerializer(serializers.ModelSerializer): test_set = TestSerializer(many=True) class Meta: model = Project fields = ['name', 'test_set'] And in the models I just have a ForeignKey to the Project class from the Test class project = models.ForeignKey('Project') But when filtering the API view with a query parameter, it still includes test objects with a different platform. I have also tested with test__platform__icontains etcetera if that makes any difference I was looking for it to return something along the lines of [ { "name": "<Project name>", "test_set": [ { ... }, ... } ] -
Django models: Set default relative to another field
Im buling an app using Django 1.10 as backend. Is it possible to set a model field's default relative to another model from the same instance? I specifically need to set second_visit's default to be 3 weeks after first_visit class SomeModel(models.Model): first_visit = models.DateField() second_visit = models.DateField(default= second_visit_default) def second_visit_default(self): # Set second_visit to 3 weeks after first_visit -
Dynamically pass app_label and model_name to the url in Python Django
I'm curious, why aren't more people talking about code consolidation by dynamically passing app_label and model_name as arguments to the URL. In building generic CRUD actions for 'non-staff' users I've been searching for the most 'DRY' method. I started out trying to extend the Django Admin for 'non-staff' users. Later I came across Django-Generic-Scaffold, which is awesome, but scaffolds models up front rather than dynamically on-demand. After digging through the Django Admin source code I discovered this technique and have it working well but I wonder why is this technique isn't discussed more? urls.py url(r'^(?P<app_label>[\w\-]+)/(?P<model_name>[\w\-]+)/$', DynamicListView.as_view(), name='list'), views.py class DynamicListView(LoginRequiredMixin, ListView): template_name = 'dynamic_list.html' @property def model(self): return apps.get_model(app_label=str(self.kwargs['app_label']), model_name=str(self.kwargs['model_name'])) @property def app_label(self): return str(self.kwargs['app_label']) def get_queryset(self): queryset = super(DynamicListView, self).get_queryset() if self.app_label == 'auth': return Http404 else: return queryset.filter(**self.request.GET.dict()) def dispatch(self, request, *args, **kwargs): if request.user.is_superuser: return super(DynamicListView, self).dispatch(request, *args, **kwargs) else: # Set permissions here for non-staff users For example, let's say we have an app called 'Library' and two models Book and Author: class Author(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author) def __str__(self): return self.title With this technique we could use a single set of URLs to list, …