Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django raw query join many to many field
Models.py class RestaurantKeyword(models.Model): keywords=models.CharField(max_length=200) def __str__(self): return str(self.keywords) class Restaurant(models.Model): name=models.CharField(max_length=500) email=models.CharField(max_length=500) web=models.CharField(max_length=500) short_description=models.CharField(max_length=500) description=models.CharField(max_length=500) phone=models.IntegerField(blank=True,null=True,default=0) lat =models.FloatField(blank=True,null=True) lng =models.FloatField(blank=True,null=True) address1 = models.CharField(max_length=100) address2 = models.CharField(max_length=100,blank=True) city = models.CharField(max_length=100) state = models.CharField(max_length=2) postalcode = models.CharField(max_length=20) avg_rating=models.FloatField(blank=True,null=True) restaurant_type=models.ForeignKey(RestaurantType,on_delete=models.CASCADE) price=models.IntegerField(blank=True,null=True,default=0) keywords=models.ManyToManyField(RestaurantKeyword,blank=True) def __str__(self): return self.name SQL raw query SELECT id,name,( 3959 * acos ( cos ( radians(30.696627)) * cos( radians( lat ) ) * cos( radians( lng ) - radians(76.693764) ) + sin ( radians(30.696627) ) * sin( radians( lat ) ) ) ) AS distance FROM newbackend_restaurant I have parameters like lat,lng, keyword. I need a query there i can use keywords to find my result.but keywords is many to many fields. -
Heroku CI Unable to initialize CI build environment,
I'm setting up Heroku CI for my app and I'm getting the following error: Could not create test run. Unable to initialize CI build environment, please try again. Problem is I have no idea why. I have my app.json set up like so: { "environments": { "test": { "scripts": { "test-setup": "python manage.py flush --noinput && python manage.py migrate --settings=app.settings.heroku", "test": "python manage.py heroku --settings=app.settings.heroku" }, "addons": [ "heroku-postgresql:in-dyno", "heroku-redis:in-dyno" ], "buildpacks": [ { "url": "https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-python" } ] } } } Any idea what could be causing this error? -
return token after registration with django-rest-framework-simplejwt
I'm using django-rest-framework-simplejwt and was wondering if it's possible to return a token after registering a user? This post has a solution for another jwt package and I was wondering how I could do something similar for simplejwt? thanks -
Django request.body has incomplete data
I am sending a large amount of data to server from Android App using volley. The request which I receive in Django, sometimes has incomplete data. While doing json.loads(data) it throws ValueError: Unterminated string starting at: line 1 column 278491 (char 278490). It doesn't happen every time. What can be the possible error in my Django or Android Code? Sample Code: request_data = request.body data = json.loads(request_data) I am using Python 2.7 -
Django - Cannot compilemessages in Alpine?
I'm trying to migrating our docker image to alpine based, but I got a problem that I cannot compile messages during image building. FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 # Creating working directory RUN mkdir /code WORKDIR /code # Copying requirements COPY ./myproject/ . RUN apk add --no-cache --virtual .build-deps \ ca-certificates gcc postgresql-dev linux-headers musl-dev \ libffi-dev jpeg-dev zlib-dev \ && pip install -r requirements.txt \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && runDeps="$( \ scanelf --needed --nobanner --recursive /usr/local \ | awk '{ gsub(/,/, "\nso:", $2); print "so:" $2 }' \ | sort -u \ | xargs -r apk info --installed \ | sort -u \ )" \ && apk add --virtual .rundeps $runDeps \ && apk del .build-deps RUN python manage.py compilemessages The only problem I have is in the step compiling messages. Here the error CommandError: Can't find msgfmt. Make sure you have GNU gettext tools 0.15 or newer installed. -
Referencing the User model
In my Django projects I have two a apps. Each app have it's own users. App1 User is inherited from django AbstractUser where as in App2 User inherited from User. Now while trying to runserver I'm getting following errors. App1 models.py from django.contrib.auth.models import AbstractUser class ApiUser(AbstractUser): api_key = models.CharField(max_length=100,blank=True, unique=True) class Meta: db_table = 'app1_apiuser' app_label = 'app1' App2 models.py from django.contrib.auth.models import User class MyUser(User): my_key = models.CharField(blank=True, max_length=255) class Meta: db_table = 'app2_myuser' managed = False app_label = 'app2' class Device(models.Model): created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING) class Meta: db_table = 'app2_device' managed = False settings.py AUTH_USER_MODEL = 'app1.ApiUser' errors app1.ApiUser.groups: (fields.E304) Reverse accessor for 'ApiUser.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'ApiUser.groups' or 'User.groups'. app1.ApiUser.user_permissions: (fields.E304) Reverse accessor for 'ApiUser.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'ApiUser.user_permissions' or 'User.user_permissions'. app2.Device.created_by: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. oe1.MyUser.user_ptr: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. -
Django class admin logic error
I tried to make some changes in Django admin and it got me really confused as it seems like I made some sort of a big basic logic error..? my error is : <class 'foodordering.admin.CInline'>: (admin.E202) 'foodordering.Customer' has no ForeignKey to 'foodordering.Order'. <class 'foodordering.admin.DInline'>: (admin.E202) 'foodordering.Deliveryboy' has no ForeignKey to 'foodordering.Order'. <class 'foodordering.admin.DishInline'>: (admin.E202) 'foodordering.Dish' has no ForeignKey to 'foodordering.Menu'. <class 'foodordering.admin.DishInline'>: (admin.E202) 'foodordering.Dish' has no ForeignKey to 'foodordering.Order_dish'. <class 'foodordering.admin.MenuAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'name', which is not a callable, an attribute of 'MenuAdmin', or an attribute or method on 'foodordering.Menu'. <class 'foodordering.admin.MenuAdmin'>: (admin.E112) The value of 'list_filter' must be a list or tuple. <class 'foodordering.admin.ODAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'name', which is not a callable, an attribute of 'ODAdmin', or an attribute or method on 'foodordering.Order_dish'. <class 'foodordering.admin.ODAdmin'>: (admin.E108) The value of 'list_display[1]' refers to 'delivery', which is not a callable, an attribute of 'ODAdmin', or an attribute or method on 'foodordering.Order_dish'. <class 'foodordering.admin.ODAdmin'>: (admin.E108) The value of 'list_display[3]' refers to 'status', which is not a callable, an attribute of 'ODAdmin', or an attribute or method on 'foodordering.Order_dish'. <class 'foodordering.admin.ODAdmin'>: (admin.E108) The value of 'list_display[4]' refers to 'grade', which is not a … -
Celery tasks when specifying custom vhost in rabbitmq is not running
I am using celery and rabbitmq as the broker to handle my async tasks in my django projects. When I was using the default broker url, everything was working fine, but in my production server, I needed to run two django projects both of which will need a async task manager. Now, to do this I created two vhosts in rabbitmq. Then, I changed my CELERY_BROKER_URL in settings.py to amqp://guest:guest@localhost:5672/vhost_name in both projects. Then, I ran it using supervisor worker with the command celery -A proj worker -l info. Weirdly, one of my project is working fine, but in the other one the task is being received but not being executed! So, for that project I changed it to the default CELERY_BROKER_URL and it started working, and also ran the tasks which weren't executed. To debug, I ran the same thing on my local machine and the same thing happened. The project configurations are mostly similar apart from the number of tasks. The first project (which worked) had 3 tasks while the other had 8 tasks. Is this a bug? If not can someone point me to the right direction? celery.py in project root import os import logging from celery … -
import from app not working in django jupyer notebook
Error 1 - import error I am having an app named insights which is defined as: INSTALLED_APPS = [..other apps, 'insights', 'rest_framework',] Also Django_SETTINGS_MODULE is configured, though I am able to import the function in other python .py files, why can't I access it in jupyter notebook. The error is: The error says: ImproperlyConfigured Traceback (most recent call last) <ipython-input-2-d95a2c1d29cc> in <module>() ----> 1 from insights.machine_learning.get_dataframes import get_all_transactions_df C:\ProjectPath\insights\machine_learning\get_dataframes.py in <module>() 8 from datetime import timedelta 9 from django.views import View ---> 10 from rest_framework.views import APIView 11 from operator import itemgetter 12 from itertools import groupby C:\ProjectPath\venv\lib\site-packages\rest_framework\views.py in <module>() 16 from django.views.generic import View 17 ---> 18 from rest_framework import exceptions, status 19 from rest_framework.request import Request 20 from rest_framework.response import Response C:\ProjectPath\venv\lib\site-packages\rest_framework\exceptions.py in <module>() 15 16 from rest_framework import status ---> 17 from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList 18 19 C:\ProjectPath\venv\lib\site- packages\rest_framework\utils\serializer_helpers.py in <module>() 6 from django.utils.encoding import force_text 7 ----> 8 from rest_framework.compat import unicode_to_repr 9 from rest_framework.utils import json 10 C:\ProjectPath\venv\lib\site-packages\rest_framework\compat.py in <module>() 174 guardian = None 175 try: --> 176 if 'guardian' in settings.INSTALLED_APPS: 177 import guardian # noqa 178 except ImportError: C:\ProjectPath\venv\lib\site-packages\django\conf\__init__.py in __getattr__(self, name) 54 """Return the value of a setting and cache it … -
NoReverseMatch happens in any Exception
I'm using django-framework. There is a question that whatever exception happens in program,it will invoke NoReverseMatch(for example, I put "a = 1/ 0 " in my view code). Following is my Traceback: File "/usr/lib/python3.5/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/usr/local/lib/python3.5/dist-packages/django/contrib/staticfiles/handlers.py", line 66, in __call__ return self.application(environ, start_response) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/wsgi.py", line 146, in __call__ response = self.get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 81, in get_response response = self._middleware_chain(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 37, in inner response = response_for_exception(request, exc) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 87, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 122, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/usr/local/lib/python3.5/dist-packages/django/views/debug.py", line 91, in technical_500_response text = reporter.get_traceback_text() File "/usr/local/lib/python3.5/dist-packages/django/views/debug.py", line 341, in get_traceback_text return t.render(c) File "/usr/local/lib/python3.5/dist-packages/django/template/base.py", line 175, in render return self._render(context) File "/usr/local/lib/python3.5/dist-packages/django/template/base.py", line 167, in _render return self.nodelist.render(context) File "/usr/local/lib/python3.5/dist-packages/django/template/base.py", line 943, in render bit = node.render_annotated(context) File "/usr/local/lib/python3.5/dist-packages/django/template/base.py", line 910, in render_annotated return self.render(context) File "/usr/local/lib/python3.5/dist-packages/django/template/defaulttags.py", line 211, in render nodelist.append(node.render_annotated(context)) File "/usr/local/lib/python3.5/dist-packages/django/template/base.py", line 910, in render_annotated return self.render(context) File "/usr/local/lib/python3.5/dist-packages/django/template/base.py", line 993, in render output = self.filter_expression.resolve(context) File "/usr/local/lib/python3.5/dist-packages/django/template/base.py", line 703, in resolve new_obj = func(obj, *arg_vals) File "/usr/local/lib/python3.5/dist-packages/django/template/defaultfilters.py", line 229, in stringformat return ("%" + str(arg)) % value File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 79, in … -
How to include a parent object when serializing a Django Model?
I have two simple models with a foreign key relation like this: class Foo(models.Model): code = models.CharField(max_length=255) class Bar(models.Model): foo = models.ForeignKey(Foo) description = models.CharField(max_length=255) The current rest_framework-based serializers look like this: class FooSerializer(serializers.ModelSerializer): class Meta: model = models.Foo fields = ('id', 'code') class BarSerializer(serializers.ModelSerializer): class Meta: model = models.Bar fields = ('id', 'foo', 'description') So a GET request for a Bar will return something like this: { "id": 1, "foo": 2, "description": "[…]" } How do I change BarSerializer to instead return the full Foo object, like this: { "id": 1, "foo": { "id": 2, "code": "[…]" }, "description": "[…]" } ? Keep in mind I still need to be able to create a Bar by providing only a description and Foo ID. -
How can I only depth one field in Django-Rest-Framework?
I have a IPv4ListSerializer, it has a depth = 1: class IPv4ListSerializer(ModelSerializer): """ ipv4 """ ip_status = serializers.CharField(read_only=True) class Meta: model = IPv4Manage fields = "__all__" depth = 1 but the result it become every field depth 1: [ { "id": 281, "ip_status": "Vlaned", "ip": "43.243.33.1", "netmask": "255.255.255.248", "prefix": 29, "is_gateway": false, "is_network_ip": false, "is_broadcast_ip": false, "desc": null, "ctime": "2018-04-26T21:17:33.623092+08:00", "uptime": "2018-06-02T12:48:41.882016+08:00", "ipv4network": { "id": 21, "network_ip": "43.243.33.0", "prefix": 24, "ctime": "2018-04-26T21:17:33.533667+08:00", "uptime": "2018-04-26T21:17:33.533814+08:00", "area_partition": 7 }, "vlaned_ipv4network": { "id": 1, "network_ip": "43.243.33.0", "prefix": 29, "gateway_ip": "43.243.33.6", "broadcast_ip": "43.243.33.7", "ctime": "2018-04-26T21:27:56.011624+08:00", "uptime": "2018-04-26T21:27:56.258053+08:00", "ipv4network": 21, "vlanedipv4networkgroup": 4 }, "physical_server": { "id": 23, "name": "SE01-A1", "desc": "desc", "cpu": "Intel Xeon E3-1230 v5", "ram": "Supermicro DDR4___16", "disk": "Inter SSD___240", "price": "1000.00", "server_status": "ready", "pay_time": null, "expire_time": null, "ipmi_addr": "172.16.30.1", "ipmi_account_and_pwd": null, "has_intranet": true, "intranet_ip": null, "customer_desc": null, "whmcs_tblorders_id": null, "ctime": "2018-05-08T16:15:50.639962+08:00", "uptime": "2018-08-20T18:25:27.289100+08:00", "switches": 3, "physical_server_model": 5, "switchesport": 57, "cabinet": 3, "task": null, "user": null, "trade_record": null } }, .... ] Can I only depth one field? such as if depth ipv4network, my requirement is: [ { "id": 281, "ip_status": "Vlaned", "ip": "43.243.33.1", "netmask": "255.255.255.248", "prefix": 29, "is_gateway": false, "is_network_ip": false, "is_broadcast_ip": false, "desc": null, "ctime": "2018-04-26T21:17:33.623092+08:00", "uptime": "2018-06-02T12:48:41.882016+08:00", "ipv4network": { "id": … -
Django python error (importing issue?)
Following Thenewboston's Django tutorial on YouTube. I'm using Python 3.4 and Django 1.9.1 & the IDE PyCharm 2018 2.2. My views.py: from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^music/', include('music.urls')), ] My music\urls.py: from django.conf.urls import url import views urlpatterns = [ url(r'^$', views.index, name='index') ] My website\urls.py from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^music/', include('music.urls')), ] Disclaimer: I can't format this right because the traceback's 3rd to last line has a ' in it. When I run website\urls.py, I get this: **Traceback (most recent call last): File "C:/Users/Kyle/Desktop/website/website/urls.py", line 2, in from django.contrib import admin File "C:\Python34\lib\site-packages\django-1.9.1-py3.4.egg\django\contrib\admin__init__.py", line 13, in from django.contrib.admin.sites import AdminSite, site File "C:\Python34\lib\site-packages\django-1.9.1-py3.4.egg\django\contrib\admin\sites.py", line 258 `^ from django.contrib.contenttypes import views as contenttype_views SyntaxError: invalid syntax** -
What I am missing in order filtering against query parameter in url to work in Django Rest Framework?
I was trying to implement function filtering against query parameter in url following this page and it worked in other environment. Thus, I tried to replicate this code in other application. However, even though I implemented same code, cannot find filtering interface as below. Does anyone know what I am missing? urls.py router=routers.SimpleRouter() router.register(r'list',projectViewSet) urlpatterns = [ url(r'^api/', include(router.urls)), ] views.py class projectViewSet(viewsets.ModelViewSet): """ This API returns the list of all projects with basic information to be able to filter """ queryset=html.objects.all() serializer_class = projectSerializer filter_class=projectAPIfilter serializer.py class projectSerializer(serializers.ModelSerializer): area=areaSerializer(read_only=True) unmet=unmetSerializer(read_only=True) energy = energySer(read_only=True) class Meta: model = html fields = ('pk', 'project', 'version', 'program', 'location', 'certificate', 'user', 'good', 'final','area','unmet','energy','good','final') filters.py class projectAPIfilter(filters.FilterSet): user = django_filters.CharFilter(lookup_expr="iexact") project = django_filters.CharFilter(lookup_expr="icontains") class Meta: model=html fields=['project','program','location','certificate','user','good','final'] settings.py REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 100 } INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'widget_tweaks', 'crispy_forms', 'rest_framework_swagger', #'el_pagination', 'django_tables2', 'django_filters', 'heatBalance', 'project', 'ecm', 'help', 'BEAM', 'social_django', # 'social_django_mongoengine' ] -
AngularJS Forbidden (403) CSRF verification failed. Request aborted
Please note, I am a complete beginner in this stuff. I am trying out Python and angular js by maintaining and extending existing project. I'm having issues figuring out what is causing errors in my project. Before adding show/hide two different div on dropdown select in angular js ,it was working.It returns CSRF verification failed when i submit the form. **register.html** <div id="charkilla" ng-controller="charkilla"> <div id="blank-ch-form-container"></div> <div class="charkilla-form-wrapper" ng-repeat="ch in charkillas track by $index"> <form method="post" action="{% url 'charkilla-create' %}" ng-submit="submit($event)"> {% csrf_token %} <input type="hidden" name="reg" id="id_reg" value="{{ registrationid }}"/> <input type="hidden" name="id" ng-value='ch.id'/> <fieldset ng-disabled="ch_form_disability_{[{ $index }]}"> <div class="row"> <div class="col-md-5"> <div style="margin-top: 10px" class="input-group"> <span class="input-group-addon">दिशा*</span> <select name="ch_direction" class="form-control" ng-model="ch.ch_direction"> <option value="n">उत्तर</option> <option value="e">पुर्व</option> <option value="s">दक्षिण</option> <option selected="selected" value="w">पश्चिम</option> </select> </div> </div> <div class="col-md-5"> <!-- Removed map_sheet_no for temporary <div style="margin-top: 10px" class="input-group"> <span class="input-group-addon">तर्फ़*</span> <select name="ch_direction_through" class="form-control" ng-model="ch.ch_direction_through"> <option value="front">Front</option> <option value="back">Back</option> <option value="left">Left</option> <option selected="selected" value="right">Right</option> </select> </div> --> </div> <div class="col-md-2 remove-killa-wrapper"> <a class="remove-killa" ng-click="removeKilla($event, true, ch.id)"><span class="glyphicon glyphicon-remove"></span></a> </div> </div> <div style="margin-top: 10px" class="input-group col-md-5 "> <span class="input-group-addon">लेन्डस्केप टाईप*</span> <select name="ch_landscape_type" class="form-control" ng-model="ch.ch_landscape_type"> <option value=''>Select</option> <option value="road">सडक </option> <option value="main_road">मूख्य सडक</option> <option value="dead_end_road">मुख्य (सडक डेड इन्ड भएको)</option> <option value="ghar">घर</option> <option value="land">जग्गा</option> <option value="school">स्कूल</option> … -
Combining Grunt and Webpack in Django projects
I have a Django project that has both Vue.js for SPA but also uses allauth and built in templates. Library management in the templating system is currently done with Grunt + package.json, Vue.js uses WebPack. How do people usually approach these kinds of projects? Do they get rid of Grunt and template and try to rework everything using SPAs? Do they use one directory for Grunt/WebPack/JQuery? Am I committing some cardinal sin by leaving both in? One of the tricky things is that I currently have two package.json files and that does seem like a problem. -
Checking if relationship exists with query
I am trying to check whether or not a following relationship exists using a query. First, I get all of the followers the user has and then I check whether or not the user follows those followers. Here are my models: class Following(models.Model): target = models.ForeignKey('User', related_name='followers', on_delete=models.CASCADE, null=True) follower = models.ForeignKey('User', related_name='targets', on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return '{} is followed by {}'.format(self.target, self.follower) class User(AbstractBaseUser): username = models.CharField(max_length=15, unique=True) email = models.EmailField(max_length=100, unique=True) I am using the Django Rest-Framework so I go to the specific URL to get the information I need. After going to the URL, the output is expected. I get all the followers the user has. def get_queryset(self): requested_user = get_requested_user(self) return User.objects.filter(targets__target=requested_user).order_by('-targets__created_at'). \ annotate(is_following=Count('followers__follower', filter=Q(followers__follower=requested_user), distinct=True)) def get_requested_user(self): filter_kwargs = {'username': self.kwargs['username']} return get_object_or_404(User.objects.all(), **filter_kwargs) However, the problem is in the is_following annotation. I'd like to see whether or not the user follows each specific follower. If they follow that follower, then is_following should be 1 if not, then it is a 0. I'm getting incorrect results in is_following is there a way I can check if the user follows each specific follower? -
Populate django models to a specific python file in a json type format
I want to access the name/business name/email fields data of my models (in a json type format : example: your_name = “kelis”) from a specific python file (receiver.py) that contains the api of google spreadsheet. Models.py from django.db import models from django.contrib.auth.models import User class Questionnaire(models.Model): your_name = models.CharField(max_length=30) business_name = models.CharField(max_length=30) email = models.EmailField(max_length=30, blank=False) def __str__(self): return self.your_name how can i achieve this??? -
How to use filter Search List in django?
This is my models.py file class Report_item(models.Model): title = models.CharField(max_length=255, help_text='*Title for the post e.g. item identity') item_type = models.CharField(default="", max_length=100, help_text='*Enter the item name you found e.g. Marksheet,key,wallet,bag,watch,pendrive') def __str__(self): return self.title I am using generic create view for forms: class ReportCreate(generic.CreateView): model = Report_item fields = ['title', 'item_type', 'location', 'image', 'Description'] def get_form(self,form_class=None): if form_class is None: form_class = self.get_form_class() form = super(ReportCreate, self).get_form(form_class) form.fields['title'].widget = TextInput(attrs={'placeholder': '*Enter UID e.g. CBSE Marksheet Roll nunber 0506***'}) form.fields['item_type'].widget = TextInput(attrs={'placeholder': '*What do you found e.g. marksheet,passport,key,wallet'}) form.fields['location'].widget = TextInput(attrs={'placeholder': '*Enter street and city name where you found this item'}) form.fields['Description'].widget = Textarea(attrs={'rows':4, 'cols':15,'placeholder': 'Optional Field: Any other related detail'}) return form def form_valid(self, form): self.object = form.save(commit=False) self.object.owner = self.request.user self.object.save() return FormMixin.form_valid(self, form) I want to use a filter search for the item type. For example when I start typing in the text field of item type then it should show me Marksheet, key, wallet, bag, watch, pen drive etc category suggestion and then when I input m then it should show me only marksheet. -
How to hide google map api key in django before pushing it on github?
This is my google address api script which contains the api key <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=api_key&libraries=places&callback=ActivatePlacesSearch"> I have used .env file in project directory to hide sensitive info from settings.py file. How can I use .env file to hide my api key from my template? -
login not found login is not a valid view function
This is the first time I am using Django login template and I ran into a problem. It keeps saying that login is not a valid view function but I define it in the urls.py in my users app. Not sure what I am doing wrong. main urls.py urlpatterns = [ path('', include('blogging_logs.urls', namespace='blogging_logs')), path('users/', include('users.urls', namespace='users')), path('admin/', admin.site.urls), ] app: blogging_logs: base.html <p> <a href="{% url 'blogging_logs:index' %}">Home</a> <a href="{% url 'blogging_logs:categories' %}">Categories</a> {% if user.is_authenticated %} Hello, {{ user.username }}. {% else %} <a href="{% url 'users:login' %}"> login in</a> {% endif %} </p> {% block content %}{% endblock content %} app: users: urls.py from django.contrib import admin from django.urls import re_path, path from django.contrib.auth import authenticate, login from django.contrib.auth import views as auth_views app_name = 'users' urlpatterns = [ # Login Page path('login/', auth_views.LoginView.as_view(template_name='login.html')), ] app:users: login.html {% extends "blogging_logs/base.html" %} {% block content %} {% if form.errors %} <p>Your username and password din't match. Please try again.</p> {% endif %} <form class="" method="post" action="{% url 'users:login' %}" > {% csrf_token %} {{ form.as_p }} <button name='submit'> Login in </button> <input type="hidden" name="next" value="{% url 'blogging_logs:index' %}" /> </form> {% endblock content %} -
Django Admin or Angular JS
Guys i have a very simple project where i need 2 main screens, let's see: 1- The main and first screen is where user select a BANK account, something like a "combobox" when user choose a BANK ACCOUNT and click in confirm. 2- The second screen is just a list that shows all Bank Account(Selected in step 1) movements. So, I'm just starting with Django and create a Admin Site is very very simple and useful. But my project is not like a CRUD, as you can see. I need only one CRUD (BANK ACCOUNT) but another screens is not crud. So, my questions are: 1) Is better customize Admin Django to my case or create this pages in another language more customizable like Angular JS ? Django give me some "ready-to-go" CRUD's but i have to customize index page, menu bar, colors and logo. 2) Is a good choice use Django Rest Framework to generate a Viewset and build my frontend using Angular JS to consume this backend ? -
How to hide city and country name from google auto fill address api?
This my form field <div class="row"> <div class="signupdiv col-md-5"> <label for="id_location">Location:</label> </div> <div class="signupfield col-md-7"> <input type="text" name="location" placeholder="Enter street/address where you found this item" required id="id_location" /> </div> </div> <div class="row"> <div class="signupdiv col-md-5"> <label for="id_city">City:</label> </div> <div class="signupfield col-md-7"> <input type="text" name="city" placeholder="Enter city name e.g. New Delhi, Hyderabad" required id="id_city" /> </div> </div> This is how I am using google Address API <script type="text/javascript"> function ActivatePlacesSearch(){ var input=document.getElementById('id_location'); var autocomplete=new google.maps.places.Autocomplete(input); } </script> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=api&libraries=places&callback=ActivatePlacesSearch"> </script> As you can see I have two different field one is location and one is a city. But by using this API it adds the city as well as the country in my location field. I want only address in the location field and the city name is next field.I am using django 1.11? So how can I achieve it? Below is models.py file class Report_item(models.Model): location = models.CharField(max_length=60, help_text='*Enter the address/street where you find this item') city = models.CharField(max_length=60, help_text='*Enter the city name') def __str__(self): return self.city -
django rest framework serializers validate field
I tried many solutions from the internet, but nothing helped. I have a problem with field validation. I would like to set custom messages and display them in my template. I use django rest framework and bootstrap 4. My code: views.py class CommissionGroupForm(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'group/add.html' def get(self, request): return Response() def post(self, request): serializer = CommissionGroupSerializer(data=request.data) if serializer.is_valid(): serializer.save() return redirect('/group/add') return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) add.html (my form template) {% extends 'forms.html' %} {% block form_url %}{% url 'group:add' %}{% endblock %} {% block form_fields %} <div class="form-group row"> <label for="name" class="col-sm-4 col-form-label">Name</label> <div class="col-sm-8"> <input type="text" class="form-control" id="name" name="name"> </div> </div> <div class="form-group row"> <label for="value" class="col-sm-4 col-form-label">Value</label> <div class="col-sm-8"> <input type="numer" class="form-control" id="value" name="value"> </div> </div> {% endblock %} serializers.py class CommissionGroupSerializer(serializers.ModelSerializer): class Meta: model = CommissionGroup fields = ('name', 'value') read_only_fields = ('id', ) # it doesn't work def validate(self, data): name = data['name'] value = data['value'] if not self._is_field_valid(name, value): raise serializers.ValidationError({'name': ['sample message'], 'value': ['sample message 2']}) models.py class CommissionGroup(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=500) value = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) class Meta: db_table = 'commission_group' When I try to print error message in views.py (print serializer.errors) I cannot see my custom message. … -
urandom in django model / mySQL Database
I am trying to store a urandom value into the mySQL Database of my Django project. The value must be totally random for cryptography purposes. I am trying for hours and I am really frustrated. I googled some answers but the solutions wont work. If I try this as here suggested Store os.urandom variable to Sqlite database in Django def createkey(): random_bytes = urandom(16) return b64encode(random_bytes) key = models.BinaryField(max_length=16, default=createkey) ... i get this error message django.db.utils.OperationalError: (1067, "Invalid default value for 'key'") I also tried it with the binascii library os.urandom() decoding Issue like this def createkey(): return binascii.hexlify(urandom(16)).decode() With that above i get this error message: string argument without an encoding I am using Python 3.6, Django 1.11.5 and a MySQL Database. Is there any way to store the value of urandom into a Django Model? I would like to store it in a CharField but I am also glad if it works with other Fields.