Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: How to know reason for not authenticated
I am trying to test username and raw password on Django Shell using authenticate function username = "test@test.com" raw_password = "password" user = authenticate(username=email, password=raw_password) I know this user name and password does not exist. When i run this code the user is returned as None. Is there a way i get some failed status or failed reason. I want to send the failed reason to my application, like email not valid or password not valid or user is not active or for whatever reason its not authenticating. -
How to upload data-URI images to S3 in Django?
I am new in Django. I am trying to create a simple web app which will take a snapshot from webcam using webcamJs javascript library. This JS library returns Data-URI of the captured snapshot that I want to upload on Amazon-S3. And I want to store the S3 link of the image in the database. I was trying to accomplish this using django-s3direct library. But It is used to upload files from the system. Can we use this library to upload data-URI images? Is there any other Django package which will be useful to accomplish this task? Any help would be appreciated. Thanks. -
Media files disappear after i push to heroku
I've created a new Django project that users can update images, and the images are being stored in /images dir, here is my setting part about it : MEDIA_ROOT = os.path.join(BASE_DIR,'images/') MEDIA_URL = '/Images/' and here is the DB setting part I am using with Heroku DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) SQL_ALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] here is the website https://fostania-web-app.herokuapp.com/, u can see it the image slider that fails every time I push. Any suggestions about this !? -
Django Post 403 forbidden CSRF
I have a simple Django webhook that keeps returning a 403 forbidden despite I have marked it with csrf_exempt. Here is the relevant code: urls.py ... url(r'^mail/$', MailView.as_view(), name="mail"), ... view.py class MailView(View): @csrf_exempt def dispatch(self, *args, **kwargs): return super(MailTrackingView, self).dispatch(*args, **kwargs) def post(self, request, *args, **kwargs): return HttpResponse(status=204) When sending data to this endpoint, Django gives a Forbidden (CSRF cookie not set.): /mail/ What else do I have to set so the CSRF validation is not performed? -
How do I add to a many-many field using Django rest framework instead of creating those entries
These are my two model class modelJob(models.Model): employer = models.ForeignKey(modelEmployer,on_delete=models.CASCADE,null=True,default=None,blank=True) skills = models.ManyToManyField(modelSkill,blank=True) title = models.CharField(max_length=200, unique=False,blank=False,null=True) and this is the model that I would like to create when received as json object from my post request class modelSkill(models.Model): skill_description = models.CharField(max_length=20, unique=True) #All the skills should be unique Now This is my serializer class Serializer_CreateJob(WritableNestedModelSerializer): skills = Serializer_SkillName_TX(many=True) class Meta: model = modelJob fields = [ 'title', 'skills', ] This is what i am sending { "title" : "Cleaning the lamp of my room", "skills": [ {"skill_description": "SkillA"}, {"skill_description": "SkillB"} ], } Now this seems to think that I would like to create the skills that I passed but instead these skills already exist and I would like to assign these skills to the created object. Any suggestions on how I can do that ? This is my view class CreateJob_CreateAPIView(CreateAPIView): serializer_class = Serializer_CreateJob permission_classes = (permissions.AllowAny,) # permissions.IsAuthenticated def post(self, request, format=None): emp = self.request.user serializer = self.serializer_class(data=request.data) if serializer.is_valid(): modjob = serializer.save() #Return the created instance modjob.employer = emp modjob.save() return Response(Serializer_Job_TX(modjob).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) My is_valid() is failing here and says that the skills have already been created. I do not want the skills to … -
Django subdomains for idiots
I am trying to set up subdomains using the DJANGO SUBDOMAINS package on my site. Turns out I'm more of an idiot than I thought. I have followed the documentation on the site, as well the following stack questions: django subdomains - SUBDOMAIN_URLCONFS Django Subdomains using django-subdomains package My knowledge is still not deep enough to follow. If any patient soul out there could please explain it to me step by step as you would to, say, a german shepard, it would be greatly appreciated. My site is in development at the moment, so I guess that means my domain is 127.0.0.1:8000. It is a membership site so I would like the capability of a user going to his console via username.sitename.com Thanks in advance. -
Django REST - URL of ForeignKey related model in metadata(OPTIONS)
I'm looking for how to get the url of ForeignKey related model in metadata(OPTIONS). Models: Class Country(models.Model): pass Class City(models.Model): country = ForeignKey(Country) I wish the "choices_url" below can be showed on the OPTIONS: City's API (OPTIONS) "actions": { "POST": { "country": { "type": "related", "required": true, "read_only": false, "label": "Country", "choices_url": "http://example.com/api/country/" Thanks. -
django-filter get queryset
I am using django-filter v1.1.0 , django 1.11. I want a dynamic filter for a model. I have created filters.py which contains the respective config for model filters. This site tells that: It will generate a Django Form with the search fields as well as return the filtered QuerySet. It here refers to SomeModelFilter function. I tried applying len and objects functions to it's object, but it returns AttributeError: 'SomeModelFilter' object has no attribute 'len' AttributeError: 'SomeModelFilter' object has no attribute 'objects' I want to get the filtered content. It doesn't seem to be a QuerySet to me. filters.py from project_app.models import * import django_filters class SomeModelFilter(django_filters.FilterSet): class Meta: model = SomeModel fields = ['field_a', 'field_b', 'field_c', 'field_d'] views.py somemodel_list = SomeModel.objects.all() somemodel_filter = SomeModelFilter(request.GET, queryset=somemodel_list) -
django and javascript API
I would like to use this javascript API in a django based web page. Is it possible to use this code below in a django web framework? https://github.com/Esri/html5-geolocation-tool-js I plan to create a web page where users can sign up and log in to the django webpage and subsequently upload their photos and post their live user location from their mobile phone into their own web account. I need to use this API as it has an accuracy of up to 10 meters outdoors which is ideal for my application. I only really need the latitude and longitude data from the GPS to be saved in django. I have only around 6 months of python and django experience and none for javascript. Any advice on how to integrate this API into django? I am open to paying someone to do it too, should someone be interested. I would however like to try. Thank you for any answers, tips, ideas, links or tutorials that might help. -
DRF get 2 row with bigger count than other ones
i have some row in table i want to get only 2 record that have bigger count value that others . for now according the my picture count 50 and 80 shoud be return. i should have a list of product_ids (only 2 record) that have count more that others.. so i should try values_list i know this is wrong how can i fix it? prod_ids = ProductViewCount.objects.all().aggregate(Max('count')).values_list('product', flat=True) this is my full code : class ViewTopLiked(APIView): def get(self, request): prod_ids = ProductViewCount.objects.all().aggregate(Max('count')).values_list('product', flat=True) obj = Product.objects.filter(product_id__in=prod_ids).order_by('-created_date') serializer = ProductSerializer(instance=obj, many=True, context={'request': request}) return Response(serializer.data) -
Is it possible to do fuzzy filter search? (filter on a field for a set of values)
I came from this issue https://github.com/carltongibson/django-filter/issues/919, here is what happened: I want to do some fuzzy search on a list via django-filter (certain list search and single fuzzy search is ok). First, the product model: from django.db import models class Product(models.Model): ... name = models.CharField(max_length=16) type = models.CharField(max_length=16) ... and two products stored in database: { "name": "tomato", "type": "vegetable" } { "name": "orange", "type": "fruit" } and serializer: from rest_framework import serializers from .models import Product class ProductSerializer(serializers.ModelSerializer): name = serializers.CharField() type = serializers.CharFIeld() class Meta: model = Product fields = '__all__' then ListFilter: import django_filters from django_filters.fields import Lookup from .models import Product class ListFilter(django_filters.Filter): def filter(self, qs, value): value_list = value.split(u',') return super(ListFilter, self).filter(qs, Lookup(value_list, 'in')) then view (I put the ListFilter at utils.django_filters): from rest_framework import generics from django_filters import rest_framework as filters from utils.django_filters import ListFilter from .models import Product from .serializers import ProductSerializer class ProductFilter(filters.FilterSet): type = ListFilter(name='type') class Meta: model = Product fields = { 'type': ['exact', 'contains'], } class ProductList(generics.ListCreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = ProductFilter finally url: from django.urls import path from . import views path('product-list', views.ProductList.as_view(), name='product-list') Below is the test cases and results: … -
Python - I try generate query that retrieve all fields from my relational model and successfully caught the query
que = RuleCondition.objects.select_related('rule_id', 'operator_id', 'value_id', 'variable_id', 'rule_specification_id') print(que.query.str()) Generated query are SELECT de1_rulecondition.id, de1_rulecondition.rule_id_id, de1_rulecondition.rule_condi_id, de1_rulecondition.rule_condi_seqno, de1_rulecondition.variable_id_id, de1_rulecondition.operator_id_id, de1_rulecondition.value_id_id, de1_rulecondition.rule_specification_id_id, de1_rulecondition.function, de1_rulecondition.logical_operator, de1_rulecondition.leftPara, de1_rulecondition.rightPara, de1_rulecondition.created_by, de1_rulecondition.created_date, de1_rulecondition.updated_by, de1_rulecondition.updated_date, de1_rule.rule_id, de1_rule.rule_threshold_id_id, de1_rule.rule_name, de1_rule.rule_type, de1_rule.description, de1_rule.rule_category, de1_rule.created_by, de1_rule.created_date, de1_rule.updated_by, de1_rule.updated_date, de1_variables.variable_id, de1_variables.variable_description, de1_variables.data_type, de1_variables.standared_format, de1_variables.created_by, de1_variables.created_date, de1_variables.updated_by, de1_variables.updated_date, de1_operators.operator_id, de1_operators.operator, de1_operators.no_of_val, de1_operators.created_by, de1_operators.created_date, de1_operators.updated_by, de1_operators.updated_date, de1_rulevalue.value_id, de1_rulevalue.rule_id, de1_rulevalue.rule_condi_id, de1_rulevalue.rule_condi_seqno, de1_rulevalue.default_value, de1_rulevalue.created_by, de1_rulevalue.created_date, de1_rulevalue.updated_by, de1_rulevalue.updated_date, de1_rulespecifiedvalues.id, de1_rulespecifiedvalues.rule_id, de1_rulespecifiedvalues.rule_condi_id, de1_rulespecifiedvalues.rule_condi_seqno, de1_rulespecifiedvalues.value_id, de1_rulespecifiedvalues.specified_value, de1_rulespecifiedvalues.created_by, de1_rulespecifiedvalues.created_date, de1_rulespecifiedvalues.updated_by, de1_rulespecifiedvalues.updated_date FROM de1_rulecondition INNER JOIN de1_rule ON (de1_rulecondition.rule_id_id = de1_rule.rule_id) INNER JOIN de1_variables ON (de1_rulecondition.variable_id_id = de1_variables.variable_id) INNER JOIN de1_operators ON (de1_rulecondition.operator_id_id = de1_operators.operator_id) INNER JOIN de1_rulevalue ON (de1_rulecondition.value_id_id = de1_rulevalue.value_id) INNER JOIN de1_rulespecifiedvalues ON (de1_rulecondition.rule_specification_id_id = de1_rulespecifiedvalues.id) How can be remove these redundant columns such as created_by etc...? -
Database created in psql is not detected in PgAdmin 4
I created a postgresql database named portfoliodb with user postgres using psql for my Django project. But when I use a PgAdmin the database doesn't show up there. Even when try to connect my database with django it says database not found. But surprisingly when I create database with same name using PgAdmin everthing works fine and database gets connected to Django and all migrations are successful. Why is it so? Have I not properly installed Postgresql? -
How to count tags with tag name of a user in Django ORM
I have a Post Model like below and I am using django-taggit class Post(models.Model): user = models.ForeignKey(User) post = models.TextField() tags = TaggableManager() >>>p1 = Post(user='user1', post='Some description', tags="python, java, js") >>>p1.save() >>>p2 = Post(user='user2', post='Some description', tags="c, java, js") >>>p2.save() >>>p3 = Post(user='user1', post='Some description', tags="c, js, python") >>>p3.save() Now I want to get the tags and tag count of each user is tagged like below { 'user1': {'python':2, 'java':1, 'js':2, 'c':1}, 'user2': {'c':1,'java':1,'js':1} } I tried with annotate, aggregation but not able write the exact query. -
When adding/editing a show in Admin, objects from other shows are being displayed instead of a blank dropdown
I have basically replicated the functionality of IMDB using Django, but I found myself in a bit of pinch. I know the problem is taking place in my Admin page, and it's starting to get really hard to track episodes, and seasons for various shows. (I have attached screenshots explaining the problem visually, down below) Right now I have two shows in my database that keeps track of a lot of things like the # of seasons, # of shows, episode title, ratings, etc. Let's say I have populated my database of the first five episodes from the show called "Suits". Now if I want to add episodes from a different show, let's say "Prison Break", in the dropdown, instead of there being no objects "---" it's showing me objects from "Suits". So even though I am on a specific show "Prison Break", my season and episode dropdowns are showing me the data I entered for my show "suits". At this rate it will be impossible to make a database of lets say 5 shows. Any ideas of what is happening? Is there a way I can exclude or prevent objects from other shows to display on a specific show? … -
How to speed up django development - Code reload
I have been moving from php to python for my web-development. Have selected django as my prefeered framework. One thing that bugs is the time it takes for my changes of the python code to reload during development. ~10 sec. Roughly. Probably some of my seconds are due to my selected setup of docker-for-mac with mounted volume. But even if it was down to 5sec it would be annoying. I have moved away from the built-in django development server, over to apache2.4 with mod_wgsi, this improves the speed of the application a lot, but no the python code reloading. I know it's like comparing apples and oranges, but coming from php my code changes are available immediately. Does anyone have any tips to speed this up? -
Django app push rejected on Heroku when upgrading to python 3.6.5
When pushing my Django app to Heroku, I am receiving this warning remote: -----> Python app detected remote: ! The latest version of Python 3 is python-3.6.5 (you are using python-3.6.4, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.5). remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes But I am getting an error when trying to update the python version. In my local environment, it is already python 3.6.5, so I just update my runtime.txt file switching python-3.6.4 to python-3.6.5. However, this is raising an error when pushing the app. Strange enough, the error is not always the same. One example: remote: Building source: remote: remote: -----> Python app detected remote: -----> Found python-3.6.4, removing remote: -----> Installing python-3.6.5 remote: -----> Installing pip remote: -----> Installing dependencies with Pipenv 11.8.2… remote: Installing dependencies from Pipfile… remote: An error occurred while installing pysocks==1.6.5! Will try again. remote: An error occurred while installing pytz==2017.2! Will try again. remote: An error occurred while installing pyyaml==3.12! Will try again. remote: An error occurred while installing requests==2.12.4! Will try again. remote: An error occurred while installing rq-dashboard==0.3.8! Will try again. remote: An error occurred while installing selenium==3.0.2! Will try again. remote: An error … -
Get only instance related Items in Django Admin
I am new to python and Django so I hope I can get some help here. I have an "app" where I have some models like "Raum", "Platz" and "Buchung". in English (Room, Postion and booking). In the web app a user can book a Position in a Room. Here are my 3 Models. Room: class Raum(models.Model): raumID = models.CharField(max_length=1, primary_key=True) name = models.CharField(max_length=250, default='') Position: class Platz(models.Model): platzID = models.CharField(max_length=3, primary_key=True) raum = models.ForeignKey(Raum, on_delete=models.CASCADE, default='') Booking: class Buchung(models.Model): cearted_on = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(Mitarbeiter, on_delete=models.CASCADE, default='') raum = models.ForeignKey(Raum, on_delete=models.CASCADE, default='') platz = models.ForeignKey(Platz, on_delete=models.CASCADE, default='') I want to be able to choose a Room and a Position when trying to book a Room. But it should only show the positions for the room I choose. And thats my Problem, I don't really know how to do that. I looked into the Django documentation and found "to_field" but I don't think thats right and also it doesn't work. Booking in admin page. So as u can see I have a Room(raum) called "seestern" and a Position(Platz) it shows 4 choices. But Room Seestern has Only "A1" and "A2". I want to only display those that belongs to a … -
How to make a lan based software? [on hold]
I searched the internet but didn't got the idea on how to actually make it. Btw, i got this https://softwareengineering.stackexchange.com/questions/228238/how-to-write-an-optimal-lan-messenger-software?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa which i think is quite useful but i want to know it from basic ie., what would i need and how to start?? Add: I want to do it with Python using Django framework. Thank You! -
Cannot cast type jsonb to character varying[] - Django
I have django model with field locations = JSONField(default=list, blank=True) I want to alter field type to ArrayField using: locations = ArrayField(CharField(max_length=100)) django makemigrations created migration file as: operations = [ migrations.AlterField( model_name='Employee', name='locations', field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=100), size=None), ), ] But while running migration it throws error: django.db.utils.ProgrammingError: cannot cast type jsonb to character varying[] LINE 1: ... "locations" TYPE varchar(100)[] USING "locations"::varchar(... What is the correct way of altering jsonb list field to arrayfield and how to typecast jsonb to arrayfield while running migration ? -
I do not want to show form's label in html
I do not want to show form's label in html. I wrote in forms.py class SearchForm(forms.Form): keyword = forms.CharField(min_length=2, max_length=100) in views.py def index(request): form = SearchForm() return render(request, 'index.html',{'form':form}) in index.html <div> <form action="{% url 'app:search' %}" method="POST"> <table> {{ form|as_bootstrap }} </table> <input type="image" src="{% static 'app/box.png' %}"> {% csrf_token %} </form> </div> When I run the app, form’s label’s keyword is shown.I want not to show it.What is wrong in my codes? I read as_p delete form’s label, so I rewrote the codes, {{ form.as_p|as_bootstrap }} But it is same . How should I fix this? -
Create <django.forms.fields.TimeField object> from string
I am creating form fields dynamically in the init form method and I need to show the fields in the form. Currnetly I have: ('start_hour_0', '11:11') I need to have e.g: ('start_hour_0', <django.forms.fields.TimeField object at 0x10c01ab70>), -
Kubernetes Pod Object which encapsulates PostgreSQL docker image crashes in infinite loop
I am trying to run my Django + PostgreSQL application on Kubernetes Google Cloud cluster. I've successfully deployed the following files: Django App Deployment Django App Service Kubernetes Secret object for DB credentials PersistentVolumeClaim But I am having trouble when deploying my PostgreSQL DB to the cluster. Here is the definition of my .yml file: apiVersion: v1 kind: Service metadata: name: postgres-service spec: selector: app: postgres-container tier: backend ports: - protocol: TCP port: 5432 targetPort: 5432 type: ClusterIP --- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: postgres-pvc labels: type: local spec: accessModes: - ReadWriteOnce resources: requests: storage: 2Gi --- apiVersion: apps/v1beta2 kind: Deployment metadata: name: postgres spec: replicas: 1 selector: matchLabels: app: postgres-container tier: backend template: metadata: labels: app: postgres-container tier: backend spec: containers: - name: postgres-container image: postgres:9.6.6 env: - name: POSTGRES_USER valueFrom: secretKeyRef: name: postgres-credentials key: user - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: postgres-credentials key: password - name: POSTGRES_DB value: agent_technologies_db ports: - containerPort: 5432 volumeMounts: - name: postgres-volume-mount mountPath: /var/lib/postgresql/data volumes: - name: postgres-volume-mount persistentVolumeClaim: claimName: postgres-pvc - name: postgres-credentials secret: secretName: postgres-credentials And here is the error I get when I run kubectl logs postgres-85c56dfb9b-95c74 command: initdb: directory "/var/lib/postgresql/data" exists but is not empty It contains a … -
Multiple cache backends in Django with minimal changes
I want to extend my default Django cache backend, to something that is based on the application referencing cache. This is to make sure one application doesn't disturb the other in case of any plausible failures of the cache server. One way to do this is as shown here. Django multiple caches backends However, there are two caveats here. 1) I need to change my code in 1000 places wherever I was using cache 2) get_cache is deprecated in Django effective v1.9 We are using redis as our cache backend, but want it to be distributed based on the application which is referring to cache. Any simple way possible? Please advise. -
Getting extra information in UI for formset creation in django view
I am not sure if title describes what i want accurately. i have an employee that have N criterion and a evaluator can evaluate each criterion for specific employee in one page like this: <table> <thead> <tr> <td>Criterion</td> <td>Result</td> </tr> </thead> <tbody> <tr> <td>criterion1</td> <td><input id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" /></td> </tr> <tr> <td>criterion2</td> <td><input id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" /></td> </tr> <tr> <td>criterion3</td> <td><input id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" /></td> </tr> <tr> <td>criterion4</td> <td><input id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" /></td> </tr> </tbody> </table> <input type="submit" name="submit" value="Submit" class="submit submitButton submit-under-form btn btn-default" id="submit-for-vacation"/> i want to create one object of model named "Evaluation" for each result which have a foreign key to Criterion model. i'am using a formset of Evaluation model for results but my problem is that i don't know how can i relate these results with their criterion in their row when i'am creating their object in my view. i prefer to use class-based view. is there a solution by using formset? or is there another easier way?