Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: array(['cycling'], dtype=object) is not JSON serializable
hi I've made an text classification classifier which i've used in this it is returning me an array and I want to return jsonresponse but the last line of code giving me error 'array(['cycling'], dtype=object) is not JSON serializable' def classify_text(request): if request.method == 'POST' and request.POST.get('text'): test = [] text = request.POST.get('text') text = re.sub('[^a-zA-Z]', ' ', text) text = text.lower() text = text.split() ps = PorterStemmer() text = [ps.stem(word) for word in text if not word in set(stopwords.words('english'))] text = ' '.join(text) test.append(text) pred = cv.transform(test).toarray() pred = svm_model_linear.predict(pred) return JsonResponse(pred, safe=False) -
overriding django form in Forms.modelAdmin
I have a problem overriding a field in my Django form. I have a class for my form: class UserCreationForm(forms.ModelForm): class Meta: model = User fields = ['password', 'services', 'project', 'email', 'name', 'first_name', 'role'] and I want to modify the returned value of services with another value, so I used the get_form function as follows: class UserAdmin(admin.ModelAdmin): exclude = ('uuid',) search_fields = ('email', "project") list_display = ("email", "project", "nb_connexion") form = UserCreationForm def get_form(self, request, obj=None, **kwargs): if obj != None: print(obj.name) print(request) form = super(UserAdmin, self).get_form(request, obj=obj, **kwargs) form.base_fields['services'].initial = Service.objects.filter(projects=obj.project) return form but I'm still getting the original results which is all the services from all the projects. I want to get just the services of one project. I tried all the possible solutions. Need help; thank you. -
Can I use django for object oriented calculations like Java?
I'm coming from Java so I am used to performing calculations I require in separate functions. I would like to know if the below code makes sense in my Django model especially the loop and calling functions from within functions. Thanks. class L3(models.Model): user = models.ForeignKey(User, related_name="L3") MachineID = models.CharField(max_length=256) TimeOnline = models.DateTimeField() Commission = models.IntegerField(default='10') TimeOffline = models.IntegerField(default='0') def indivMachineHoursWorked(self): this_month = datetime.now().month if self.TimeOnline == this_month: x = datetime.now() - self.TimeOnline else: x = datetime.now() - datetime.today().replace(day=1) #need to update hour to 0 too i.e. start of month return x def totalMachineHoursWorked(self): L3_total = L3.objects.all() hrs=0 for l3 in L3_total: hrs =+ l3.indivMachineHoursWorked() return hrs def btcToHour(self): main_api = 'https://api.nicehash.com/api?method=balance&id=513396&key=48730a3c-bfab-bcde-f6c1-1d7750c0e9fe' url = main_api json_data = requests.get(url).json() print(json_data) balance1 = json_data['result']['balance_confirmed'] print(balance1) btc2hour = balance1/self.totalMachineHoursWorked() return btc2hour def indivMachineTurnover(self): return self.indivMachineHoursWorked()*self.btcToHour() def __str__(self): return self.user.get_full_name() -
External Javascript file returning 404 error in django
<head> <!-- Include Google Maps JS API --> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/?key=my-KEY&sensor=true"> Each time I call the view up the other html element show but the google map is not displayed. the console reveals a GET https://maps.googleapis.com/maps/api/?key=KEY&sensor=true 404 () PLS how will I load an external js in django? -
Implementing Django Model for existing MongoDB diagram
can you help me to implement django model for this mongo schema? enter image description here -
Django Python on a Mac via pip and HomeBrew - Getting Started
I am trying to get started with Python Web Programming with Django, so I installed pip first (via HomeBrew) and now the latest version of Django, but the following happens, which I have no idea what is wrong or what I should do next. Could someone please help me understand what is going on + what I need to do + what commands I should issue to resolve this, etc...? $ pip --version pip 9.0.1 from /Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg (python 2.7) $ pip install Django==1.11.7 Collecting Django==1.11.7 Downloading Django-1.11.7-py2.py3-none-any.whl (6.9MB) 100% |████████████████████████████████| 7.0MB 184kB/s Requirement already satisfied: pytz in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from Django==1.11.7) Installing collected packages: Django Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install **kwargs File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/django' -
answering user from dictionary django 1.9
I am a beginner in python programming and I want to answer user's input from my dictionary. This is my views.py file from django.shortcuts import render answer = {'Hi': 'Hello!', 'How are you?': 'I am fine'} def index(request): return render(request, 'answer/index.html', answer) def detail(request): return render(request, 'answer/detail.html') urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^answer$', views.detail, name='detail'), ] index.html <form type="get" action="." style="margin: 0"> <input id="search_box" type="text" name="search_box" placeholder="Search..." > <button id="search_submit" type="submit" >Submit</button> {% if question in answer.items %} <a href="{% url 'answer:result' %}"></a> {% endif %} </form> When I put something from the server in submit box, I get the same page but '?search_box=Hi' this is added in the url. How can I respond? I have to add another template 'detail.html' but i don't know what should i put in it. If you answer this question, write an explanation too, please. -
how to read data from one DB and write to another using django router or any other way
i am new to django , here is my settings and i am following this(https://docs.djangoproject.com/en/dev/topics/db/multi-db) routing but this is not for read from other and write in another DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'default', 'USER': 'defaultadmin', 'PASSWORD': 'adminpass' }, 'users': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'users', 'USER': 'usersadmin', 'PASSWORD': 'adminpass' } } DATABASE_ROUTERS = ['DBrouting.default_db_router.default_db_router', 'DBrouting.users_db_router.users_db_router'] -
Convert datetime format within ListView
I attempt to change the displaying format of datetime in template, Here is my Codes in views.py: class RestaurantListView(LoginRequiredMixin, ListView): def get_queryset(self): return RestaurantLocation.objects.filter(owner=self.request.user) Codes in template: <ul> {% for obj in object_list %} <li>{{ obj.city }},{{ obj.location }} {{ obj.category }}</li> <li>FirstVisit: {{ obj.visited }}</li> <br> </ul> Browser displays the datetime: FirstVisit: Sept. 9, 2015, 3:08 p.m. I intend to convert to: FirstVisit: 2015-09-09 3:08 p.m. So I import datetime in views.py and format datetime object in template, <li>FirstVisit: {{ obj.visited.strftime('%Y-%m-%d %I:%M %p') }}</li> It reports error: django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '('%Y-%m-%d %I:%M %p')' from 'obj.visited.strftime('%Y-%m-%d %I:%M %p')' How to change the format of datetime in template? -
Djoser user activation email POST example
I am using DREF and Djoser for Authentication and User Registration. When a new user registers, Djoser sends an activation email with a link that does a GET request. In order to activate, I need to extract uid and token from the activation url and make a POST request for Djoser to be able to activate the user. My environment is Python 3 and Django 1.11, Djoser 1.0.1. Any help on how to handle this in Django / Djoser? What I would like to do is to handle the get request in Django, extract uid and token and then make a POST request. I have extracted uid and token and would like to make a POST (within this GET request). I do not know how to make this POST request in the background. -
change default change_list view for only filtered views
We are in process of removing count(*) queries that are fired for admin page, we don't want that query to be fired on the landing page but should be fired on filtered pages. Is there any way in django that we can customize filtered views but not landing views. I read through the documentation, went through the code, but didn't find anything, so asking here. I have found some information about the places where the count queries are firing, but I couldn't find way to modify change list view based on filtered and normal views. -
Django Rest Framework nested serilaizer throw Field name `server` is not valid for model `Server`
I try to create nested serilaizer but no luck, the error thrown in list request in WebsiteViewSet: Field name server is not valid for model Server. In model.py class Server(models.Model): name = models.CharField(max_length=50) class Website(models.Model): server = models.ForeignKey(Server) name = models.CharField(max_length=50) In serilaizer.py class ServerSerializer(FieldMixin, serializers.ModelSerializer): class Meta: model = Server # fields = '__all__' fields = ('id', 'name') class WebsiteSerializer(FieldMixin, serializers.ModelSerializer): server = ServerSerializer() class Meta: model = Website fields = ('id', 'server', 'name') In views.py class WebsiteViewSet(AdminGroupMixin, viewsets.ViewSet): def list(self, request, servers_pk=None): queryset = Website.objects.filter(server=servers_pk) #queryset = get_object_or_404(Website, pk=servers_pk) serializer = WebsiteSerializer(queryset, many=True, context={'fields': ['id', 'server', 'name', 'domain_url', 'created', 'last_modify_date']}) return Response(serializer.data) -
Can I realize the exclude fields function in Serializer?
In my serializers.py, I created a UserListSerializer: class UserListSerializer(ModelSerializer): class Meta: model = User fields = '__all__' exclude = [ 'password', ] I want to realize the exclude fields function, but failed. AssertionError at /api/users/list/ Cannot set both 'fields' and 'exclude' options on serializer UserListSerializer. Is it possible to realize this function, because the fields is too much? -
How to store third party apps migrations in django
I'm fairly new to python and django, and trying to build a simple calendar based on django-scheduler package. According to django-scheduler docs, a custom base class can be used to add additional fields, managers and such. So, I used an abstract model to add a new field: #myproject/customer_calendar/models.py from django.db import models from main.models import Customer class CalendarAbstract(models.Model): customer = models.OneToOneField(to=Customer, null=True, blank=True, related_name='calendar') class Meta: abstract = True And added this to settings.py SCHEDULER_BASE_CLASSES = { 'Calendar': ['customer_calendar.models.CalendarAbstract'], } Now, if I use makemigrations command, a new migration is created inside scheduler app (which is located in site-packages of the current virtual env), which doesn't allow me to keep track of migrations via VCS. I've found a couple of solutions: 1) Keep the whole scheduler app inside my project. According to SO it' s considered a bad practice and third-party apps should always be retrieved via pip. 2) Use django setting to store all django-scheduler migrations inside my calendar app MIGRATION_MODULES = { 'schedule': 'customer_calendar.migrations', } The second one looks good to me, but I don't know if it's considered to be a valid solution to this problem. Is there any other ways to store third-party apps migrations? -
python django response time long but don't know what's wrong
My django app use django-rest-framework, and MySQL. I tested my app, but almost functions had long response time. I don't know what is the problem. This is one of most long response time functions. 180232 function calls (171585 primitive calls) in 1.110 seconds Ordered by: internal time List reduced from 757 to 151 due to restriction <0.2> ncalls tottime percall cumtime percall filename:lineno(function) 105 0.597 0.006 0.597 0.006 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:268(query) 2 0.154 0.077 0.174 0.087 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:81(__init__) 4 0.020 0.005 0.020 0.005 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:254(autocommit) 8800/3582 0.010 0.000 0.828 0.000 {built-in method builtins.getattr} 20156 0.010 0.000 0.022 0.000 {built-in method builtins.isinstance} 200/100 0.009 0.000 0.886 0.009 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/rest_framework/serializers.py:479(to_representation) 2 0.009 0.005 0.009 0.005 {function Connection.set_character_set at 0x109b506a8} 6920 0.009 0.000 0.009 0.000 {built-in method builtins.hasattr} .... This function is first page of list, total count is 1000, page size is 100. Each records join just one table. Query took long time so I changed Django ORM to Raw Query but time is same. (Maybe I used wrong raw query) Even auth check response time long 2199 function calls (2133 primitive calls) in 0.195 seconds Ordered by: internal time List reduced from 419 to 84 due to restriction <0.2> ncalls tottime percall cumtime percall filename:lineno(function) 2 … -
Django populate form
In my modelClass in admin.py I've defined sub-classes "changelist_view" and "changeform_view" to send two custom values to my template view. As result when I open the change page of my model form it remain empty. Can I populate the form? class WorkerAdmin(admin.ModelAdmin): change_form_template = 'admin/change_form.html' change_list_template = 'admin/change_list.html' form = WorkerAdminForm def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} extra_context['model_title'] = 'Workers' extra_context['page_title'] = 'Workers Manage' return super(WorkerAdmin, self).changelist_view(request, extra_context=extra_context) def changeform_view(self, request, object_id=None, form_url='', extra_context=None): extra_context = extra_context or {} extra_context['model_title'] = 'Workers' extra_context['page_title'] = 'Worker Add' return super(WorkerAdmin, self).changeform_view(request, extra_context=extra_context) admin.site.register(Worker, WorkerAdmin) -
How to deal with the two custom User model case in Django?
I make two models that inherit form from django.contrib.auth.models import AbstractUser, names User and AdminUser. But there are check identified errors when runserver, so I add : AUTH_USER_MODEL = "qiyun_admin_usermanage.User" In my settings.py. the half error gone, but there still has the qiyun_admin_usermanage.AdminUser's issue. I don't know whether I can set two custom models in the AUTH_USER_MODEL, or there must only be one AUTH_USER_MODEL? The traceback: ... django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: qiyun_admin_usermanage.AdminUser.groups: (fields.E304) Reverse accessor for 'AdminUser.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'AdminUser.groups' or 'User.groups'. qiyun_admin_usermanage.AdminUser.user_permissions: (fields.E304) Reverse accessor for 'AdminUser.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'AdminUser.user_permissions' or 'User.user_permissions'. qiyun_admin_usermanage.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'AdminUser.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'AdminUser.groups'. qiyun_admin_usermanage.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'AdminUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'AdminUser.user_permissions'. -
How to escape html character in django sending email
I design a email verify mechanism in my django app. When sending email with the verify link, there're some escape character, such as the 'amp;' in http://localhost:8000/confirm/username=testuser1&token=4qy-c97f409d02dcddfca663 The original string is fine, but when sent out with email it become some strange words -
Admin password change does not take effect
Session expired for my local environment admin user and I can't remember the password. Well, I thought I did remember it but the login just rejected it so I guess it is a different one. I am trying to change the admin's password so I can log in, but none of the ways I have tried worked: python manage.py changepassword myadmin Does report that the password change was successful, however the login keeps failing. I have also tried changing it via shell: u = User.objects.first() # there is only one user: the admin pwd = make_password('admin') u.password = pwd u.save() At first this didn't seem to be working because u.password didn't output the same than pwd. But now for some reason it does. However, u.password == make_password('admin') evaluates to False, but check_password('admin', u.password) evaluates to True. I guess the reason of this disparity is the used seed. I don't even know what's going on. I have been able to change admin passwords in the past without a problem. How can I solve this issue? -
Passing merchant key and salt in website
I have integrated payu in my website for transaction. I have a doubt, in their dev guide they pass merchant key, salt, hash etc. to form parameters. Now, if anybody does an inspect element in my website then he/she can see those parameters.I want to know the best way people use payu apis and how do they make sure that mechant id, salt remains on server only. My backend is in django and front end in angular js -
Display child nodes of the item when using graphene
I am using graphene as GraphQL Framework for Python for the first time. I wanted to show all the categories include sub-categories if it has but i could not do it. Here is the list of categories I could show sub-categories when using rest_framework where the response looks like this (I wanted something like this but in graphql) { "id": 1, "name": "Bedroom Items", "slug": "bedroom-items", "subcategories": [ { "id": 3, "name": "Almirah", "slug": "almirah", "image": null, "subcategories": [ { "id": 12, "name": "3 piece Almirah", "slug": "3-piece-almirah", "image": null, "subcategories": [] }, }, } but in graphql i have no idea on how to show sub-categories as I am using mptt model class Category(MPTTModel): name = models.CharField(max_length=100, blank=True, null=True) slug = models.SlugField(max_length=200, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) class MPTTMeta: order_insertion_by = ['name'] def __str__(self): return self.name class CategoryNode(DjangoObjectType): class Meta: model = Category filter_fields = ['name', ] interfaces = (Node, ) class Query(ObjectType): category = Node.Field(CategoryNode) all_categories = DjangoFilterConnectionField(CategoryNode) This is the query I have done { allCategories { edges { node { name children { edges { node { name } } } } } } } This query yields the following response (one level … -
print `object_list` within ListView
I have the following class in views.py: class RestaurantListView(LoginRequiredMixin, ListView): def get_queryset(self): qs = RestaurantLocation.objects.filter(owner=self.request.user) return qs in restaurantlocation_list.html <ul> {% for obj in object_list %} <li>obj</li> {% endfor %} I want to print object_list within views.py by adding print statement, class RestaurantListView(LoginRequiredMixin, ListView): def get_queryset(self): qs = RestaurantLocation.objects.filter(owner=self.request.user) Add print statement: print(object_list) return qs Error reports then: NameError: name 'object_list' is not defined What confuses me is that template receive arguments from views, whereas it can not be reached in views? How to print the object_list in views.py? -
Whether I extend the AdminUser should inherit from AbstractUser?
Previous, I extend the AdminUser from AbstractUser: class AdminUser(AbstractUser): username = models.CharField(max_length=16) password = models.CharField(max_length=40) # sha1加密 real_name = models.CharField(max_length=12, null=True, blank=True) phone = models.CharField(max_length=11) # 手机号码 is_staff = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) You see I use the is_staff and is_superuser to define whether is a admin user. But, today when I read the Django document: There is Admin and UserAdmin: from django.contrib.auth.admin import UserAdmin as BaseUserAdmin Whether I was wrong to subclass from AbstractUser? whether I should inherit from BaseUserAdmin or UserAdmin? -
Django doesn't manage properly auto generated class from models
I have designed my tables in mssql and then autogenerated the models with the inspectdb tools. But when I modify the models and run the makemigrations tools, django recreate all the tables as if they didnt exist in the first place, and prevent me from migrating the newly modified tables. I removed the managed=False from the autogenerated models as advised and I am using pyodbc as mssql librairy I would like to be able to modify the models and only carry that changes to mssql as it is supposed to be. -
Django - How to listen response before sending it? DRF
I'm using DRF for creating the APIs. It automatically sends the validates the input data, apply CRUD operations and then send the response. I want to update the response format. Such for eg:- to GET all users, the response send by DRF is a list of user details. I want something like this:- { 'response':[{}, {}], 'status': 200 } How and where can I listen to response for every API and customize the response before sending it back to the client. I've found something similar for custom_exceptions. Is there something similar for normal responses.