Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Not able to install virtual environment in python
I was trying to install virtual environment in python-django project. But, I am getting this error: Could not find a version that satisfies the requirement virtualenv (from versions: ) No matching distribution found for virtualenv Please help. Thank you! -
Is there a risk in my design User in Django?
I am creating the extend User like bellow: class User(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) # 手机号码 email = models.EmailField(blank=True, null=True) qq = models.CharField(max_length=10, null=True, blank=True) address = models.CharField(max_length=64, blank=True, null=True) # 地址 nickname = models.CharField(max_length=16, blank=True, null=True) is_staff = True is_superuser = False You see there are two fields here: is_staff = False is_superuser = False So, when I create the AdminUser, if there is a risk? Because the hacker may use : AdminUser(xxxxx, is_staff=True, is_superuser=True, xxx) to create a superuser. Or whether my User model is complete wrong? -
The already checked items gets appended in a list
script: function checkCount(elm) { var checkboxes = document.getElementsByClassName("checkbox-btn"); var selected = []; for (var i = 0; i < checkboxes.length;i++) { if(checkboxes[i].checked){ selected.push(checkboxes[i].value); alert(selected); } } var uniqueNames = []; html: {% for alertDict in alertnamefile %} {% for alertnames in alertDict.alertname %} {% if alertnames in alertDict.alertPresentFile %} <li><input type="checkbox" value={{alertnames}} class='checkbox-btn' checked onchange='checkCount(this.value)'>{{alertnames}}<br></li> {% endif %} {% if alertnames not in alertDict.alertPresentFile %} <li><input type="checkbox" value={{alertnames}} class='checkbox-btn' onchange='checkCount(this.value)'>{{alertnames}}<br></li> {% endif %} {% endfor %} {% endfor %} $.each(selected, function(i, el){ if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el); }); document.getElementById("alert_selected").value = uniqueNames.join(); } //I have certain items which are checked already.But while appending it in on list.If we uncheck the item it gets unchecked.But in the list selected the old values too get appened. ex:suppose we have a,b,c,d,e items in a checkbox :a,b are checked.So when the loop executes and we uncheck a.The result comes as b,a,b.If we uncheck b now it will be like a,b -
Django template : {% if %} tag can't get it to work
I am looking for a way in order my templates can recognize an attribute from my extended userprofile, specifically if he is an affiliate and show different content in the templates whether he is an affiliate or not. Is there an other approach to this like to build an decorator? i have worked with other {%if%} tags like this built-in auth request {% if request.user.is_authenticated %} models.py project/useprofile/ , the book is in an other app project/book class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) affiliate = models.BooleanField(default=False) add_book.html {%extends 'base.html' %} {% load i18n %} {% load crispy_forms_tags %} {% block content1 %} {% if userprofile.profile.affiliate = True %} <h1>New post</h1> <form method="POST" class="post-form"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="save btn btn-primary">Save</button> </form> {% endif %} {% endblock %} urls.py url(r'^book/add/$', 'book.views.addbook', name='addbook'), views.py def addbook(request): if request.method == "POST": form = BookForm(request.POST) if form.is_valid(): book = form.save(commit=False) book.save() return redirect('home') else: form = BookForm() return render(request, 'add_book.html', {'form':form, }) -
Why filtering django with icontains is case sensitive?
I want to filter a queryset with icontains because I don't want the filtration to be case sensitive: some_title = "Foo" result = Article.objects.filter(title__icontains=some_title) articles with the title "foo" are not within the result. why? I am using Django (1.9.12). -
Django_Filter - Only Allowing Certain ForeignKey Options to Be Selected
I'm using django_filters for users to filter through campaigns. I have different groups and users within those groups. I have the view set-up fine so that only the campaigns for the group will show up and the respective users within that group can view them. For the filter, though, there is an option for filtering by User, the foreign key. It lists every user. I want it to only list users within the group of the current, request.user. I was able to do it on ModelForm but not on django_filters. filters.py class CampaignFilter(django_filters.FilterSet): #def group(self): # user = self.request.user # print user # group = Group.objects.get(user=user) # users = User.objects.filter(groups=group) # return users #sender = django_filters.ModelChoiceFilter(queryset=group) @staticmethod def __init__(self, group, *args, **kwargs): super(CampaignFilter, self).__init__(*args, **kwargs) # populates the post self.form.fields['sender'].queryset = User.objects.filter(groups=group) title = django_filters.CharFilter(lookup_expr='icontains') date = django_filters.DateFromToRangeFilter( label='Date', widget=django_filters.widgets.RangeWidget(attrs={'placeholder': 'Date'})) class Meta: model = Campaign fields = ['title', 'sender', 'template', 'send_time', 'date', ] views.py def campaigns(request): user = request.user group = Group.objects.get(user=user) q = request.GET.get('q') if q: campaigns = Campaign.objects.filter(sender_group=group) results = campaigns.objects.filter( Q(title__icontains=q)) else: campaigns = Campaign.objects.filter(sender_group=group) results = campaigns.all().order_by('-date') if request.method == 'GET' and 'filter' in request.GET: filter = CampaignFilter(request.GET, group=group, queryset=Campaign.objects.filter(sender_group=group)) campaignTable = CampaignTable(filter.qs) RequestConfig(request, paginate={'per_page': … -
How to filter by range of specific hours in Django Orm?
I have a queryset below, that allows me to get objects that where created at last 14 days: qs_1 = Model.objects.filter(datetime_created__gte=datetime.now()-timedelta(days=14)) What I want is to create a new queryset that will allow me to get objects for last 14 days and filter them by range from 11 pm to 9am. How can I do that ? -
Over-ride DRF custom exception response
I want to send error_codes while sending the response back to the client, in case of an error!! So, I've a form where params a and b is required. If any of the param is not POSTed, then DRF serializer sends back a response saying This field is required. I want to add the error code to the response as well for the client to identify. Different errors different error codes. So, I wrote my own custom exception handler. It goes like this. response = exception_handler(exc, context) if response is not None: error = { 'error_code': error_code, # Need to identify the error code, based on the type of fail response. 'errors': response.data } return Response(error, status=http_code) return response The problem I'm facing is that I need to identify the type of exception received, so that I can send the error_code accordingly. How can I achieve this? -
Dead letter Queue for Sqs and Celery
I'm trying to push tasks to a dead letter queue after celery throws MaxRetriesExceededError. I'm using celery 4.1 and Aws SQS as Broker in my Django project. I found a solution for RabbitMQ here, Celery: how can I route a failed task to a dead-letter queue. For some reason my code is not creating a new dlq or use exiting queue in SQS. Following is my code, I've removed exchange and routing keys part in my code from the given link: class DeclareDLQ(bootsteps.StartStopStep): """ Celery Bootstep to declare the DL exchange and queues before the worker starts processing tasks """ requires = {'celery.worker.components:Pool'} def start(self, worker): app = worker.app # Declare DLQ dead_letter_queue = Queue( 'local-deadletterqueue') with worker.app.pool.acquire() as conn: dead_letter_queue.bind(conn).declare() default_queue = Queue( app.conf.task_default_queue) # Inject the default queue in celery application app.conf.task_queues = (default_queue,) # Inject extra bootstep that declares DLX and DLQ app.steps['worker'].add(DeclareDLQ) def onfailure_reject(requeue=False): """ When a task has failed it will raise a Reject exception so that the message will be requeued or marked for insertation in Dead Letter Exchange """ def _decorator(f): @wraps(f) def _wrapper(*args, **kwargs): try: return f(*args, **kwargs) except TaskPredicate: raise # Do not handle TaskPredicate like Retry or Reject except Exception … -
django url not calling corresponding view and going back to the calling view
This is the project structure of my project. The below code is the url configuration in course/urls. from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.views.static import serve from django.views.generic import TemplateView from .views import course_list_of_faculty, course_detail_view urlpatterns = [ url(r'^list/$', course_list_of_faculty, name='course_list_of_faculty'), url(r'^(?P<pk>.+)/$', course_detail_view, name='course_detail_view'), ] From course_detail_view I am calling url course_material_upload in coursematerial app. from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.views.static import serve from django.views.generic import TemplateView # app_name = 'coursematerial' from .views import course_material_upload, files_list, download urlpatterns = [ url(r'^upload/$', course_material_upload, name='course_material_upload'), url(r'^files_list/$', files_list, name='course_material_view'), ] The below is the template of course_detail_view {% extends 'base.html' %} {% block content %} <p><a width="30%" align="center" href="{% url 'coursematerial:course_material_upload' pk=pk %}">Upload Course Material</a></p> <p><a width="30%" align="center" href="{% url 'coursematerial:course_material_view' pk=pk %}">View Course Material</a></p> {% endblock %} Here I am calling a url from coursematerial/urls. My problem is it is going to /faculty/course/coursename/upload but not going into its views 'course material upload' and repeating the current course_detail_view. The below is all my project urls from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.views.static import serve from . import views …