Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Messaging App With Django
I'm trying to build a messaging app, here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") ... created_at = models.DateTimeField(auto_now_add=True) I wants to order the Users based upon who sent a message to request.user & to whom request.user sent a message most recently! As we see on social networks. This is what I tried, users = User.objects.filter(Q(sender__receiver=request.user) | Q(receiver__sender=request.user)).annotate(Max('receiver')).order_by('-receiver__max') This code is working fine only when request.user sends someone a message (It re-orders their name & place it to the top). But, It's not changing the order of users in case if someone sends a message to request.user. I also tried, users = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by("created_at") But, I could't filter out the distinct users. It's showing equal number of users as messages. Also, I have to use {{ users.sender }} OR {{ users.receiver }} in order to print the users name which is a problem itself in case of ordering & distinct users. Please help me, how can I do that? -
How to pass JavaScript variables to React component
I'm somewhat new to React and I'm having some trouble passing some variables from my Django server to my React components. Here's what I have: The server is Django, and I have a url mydomain.com/testview/ that gets mapped to a views.py function testview: def testview(request): now = datetime.datetime.now() return render(request, 'testview.html', { 'foo': '%s' % str(now), 'myVar': 'someString' }) In other words, running testview will render the template file testview.html and will use the variables foo and myVar. The file testview.html inherits from base.html which looks like this: <!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> </head> <body> {% block main %}{% endblock %} </body> </html> The file test.html basically inserts the needed code into block main: testview.html: {% extends "base.html" %} {% load render_bundle from webpack_loader %} {% block main %} <script type="text/javascript"> var foo = {{ foo }}; var myVar = {{ myVar }}; </script> <div id="App"></div> {% render_bundle 'vendors' %} {% render_bundle 'App' %} {% endblock %} Note that just before the div id="App", I created a couple of javascript variables foo and myVar and set them to the values from Django. Now to REACT: my file App.jsx looks like this: import React from … -
Django: Can you format DateTimeField in annotate?
I have Customer and Order models and I would like to get the last order date of each customer and format it. I have the following code in views: customers = ( User.objects .prefetch_related('orders', 'addresses') .select_related('default_billing_address', 'default_shipping_address') .annotate( num_orders=Count('orders', distinct=True), last_order=Max('orders', distinct=True), last_order_date=Max('orders__created', distinct=True), gross_sales=Sum('orders__total_net'))) last_order_date is returning date in this format: Nov. 1, 2017, 11:39 p.m. I would like to update it so it returns 11/01/2017 only. How can I achieve this? I tried this: last_order_date=Max(('orders__created').strftime("%d/%m/%Y"), distinct=True), but it turns out ('orders__created') is already returning an str, I got this error: 'str' object has no attribute 'strftime' I also tried creating a method in orders that will return a formatted created field: def get_day_created(self): self.created.strftime("%d/%m/%Y") but i'm not sure if I can call it in annotate and how to properly do it. 'orders__get_day_created()' is giving me the error: Cannot resolve keyword 'get_day_created()' into field. Please advise :) Thank you -
Need to get data from News APIs into a django application, run it through an algorithm and store the same in a database
I am trying to make a news summarizing application. Although my algorithm seems to be working, I am having trouble making the web application. -
django how to authenticate user until verify email
How to authenticate user until he verify the email? In my sign up process, I create the User, which means he can login even without verify email. Is there a build-in method to set a un-verified status on a User?