Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to attribute Bootstrap dropdown to ajax inserted object
I'm doing a Django project and i need to insert rows dynamically (ajax) with a dropdown menu for each one. When the content is static it works just fine, but when new data are loaded from ajax, i can't bind it to the dropdown functionality and have a message like : applyStyle.js:66 Uncaught TypeError: Cannot read property 'setAttribute' of null at Object.onLoad (applyStyle.js:66) at index.js:69 at Array.forEach (<anonymous>) at new t (index.js:67) at c.t.toggle (dropdown.js:177) at HTMLAnchorElement.<anonymous> (dropdown.js:328) at Function.each (jquery-3.3.1.slim.min.js:2) at w.fn.init.each (jquery-3.3.1.slim.min.js:2) at w.fn.init.c._jQueryInterface [as dropdown] (dropdown.js:315) at HTMLAnchorElement.<anonymous> (dropdown.js:472) When i try to call the dropdown() function to bind it manually, i got the message : Uncaught TypeError: $dropdown1.dropdown is not a function Is somebody knows what to do ? Thank you ! Byga -
Shibboleth + Django + WSGI
I am triying to deploy an customized login on Django, I would like to have 2 differents login: · One through django allauth (done) · Another one through Shibboleth Shibboleth is working on mi server (apache 2.4), can login and returns token and objects with user attributes. Where is the problem? When I deploy the app in the server, I need to active WSGI on apache, then when I try to access to /Shibboleth.sso/Login I get a Django url helper error. I am stuck on this step and I don't know where to go. -
How to count items in a foreign key?
I am making a blog app using django... This is my model.py class categories(models.Model): Title = models.CharField(max_length=40) class Blog(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) Date = models.DateTimeField(default=datetime.now) Blog_title = models.CharField(max_length=255) likes = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='likes',blank=True) Description = RichTextUploadingField(blank=True, null=True,config_name='special') Blog_image = models.ImageField(upload_to='blog_image', null=True, blank=True) Category = models.ForeignKey(categories,on_delete=models.CASCADE,related_name='Categories') I was wondering How to count the total no of blog present under a particular category? Can anyone help me out on this... Thank you... -
How to customize django admin dashboard page
I am new in django framework. I want to customize django admin panel. I want to create a page after login which has menu to left panel and some details to right panel, how can I create this type of page. -
python annotate count with filter datetime
I have model Token: class Token(models.Model): name = models.CharField() ... I have model Phrase which has a fk to token class Phrase(models.Model): token = models.ForeignKey(Token, on_delete=models.SET_NULL, null=True, related_name = "phrases") frequency = models.IntegerField() I need to perform a complex query As result I want to have list of objects with token names and phrases filtered by some param count, like this: [{'name':'token1', 'phrases_with_freq_greater_than_100': 50},{'name':'token2', 'phrases_with_freq_greater_than_100': 250}] How do I do this? I know I can do this using annotate function, but not sure how. So far I am doing it by simply iterating through token objects but this is not effective. -
How to get category array from mapping table, MySQL in Django
I have 5 table, 2 table for products ie. products, product_translations, two tables for category ie. product_categories, product_category_translations and one table for mapping table product_product_category. Now I want to fetch all products and inside products array I want all related category array. Array{ 0 => { id => 1 name => 'Camera', is_featured => 1, categories => { 0 => { id => 1, name => 'abc', locale => 'en' }, 1 => { id => 2, name => 'def', locale => 'en' }, 2 => { id => 3, name => 'test', locale => 'en' } } }, 2 => { id => 2 name => 'Computer', is_featured => 1, categories => { 0 => { id => 2, name => 'def', locale => 'en' }, 1 => { id => 3, name => 'test', locale => 'en' } } } } I can fetch category ids inside template file using category_set but can not fetch records from category translation records.c -
How to make two models related to each other(vice versa) in django. one company should have mutiple user but one user can have only one company
class Catalog(models.Model): name = models.CharField(max_length=200) no_of_pcs = models.IntegerField(null=True,blank=True) per_piece_price = models.DecimalField(null=True,blank=True,max_digits=10,decimal_places=2) def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=200) phone_number = models.IntegerField(null=True,blank=True) user = models.ManyToManyField(User) catalog = models.ManyToManyField(Catalog) def __str__(self): return self.name`*** -
Django ORM query - Sum inside annotate using when condition
I have a table, lets call it as DummyTable. It has fields - price_effective, store_invoice_updated_date, bag_status, , gstin_code. Now I want to get the output which does a group by of - month, year from the field 'store_invoice_updated_date' and gstin_code. Along with that group by I wanna do thse calculations - Sum of price_effective as 'forward_price_effective' if the bag_status is other than 'return_accepted' or 'rto_bag_accepted'. Dont know how to do an exclude here i.e. using a filter in annotate Sum of price effective as 'return_price_effective' if the bag_status is 'return_accepted' or 'rto_bag_accepted'. A field 'total_price' that subtracts the 'return_price_effective' from 'forward_price_effective'. I have formulated this query, which doesn't work from django.db.models.functions import TruncMonth from django.db.models import Count, Sum, When, Case, IntegerField DummyTable.objects.annotate(month=TruncMonth('store_invoice_updated_date'), year=TruncYear('store_invoice_updated_date')).annotate(forward_price_effective=Sum(Case(When(bag_status__in=['delivery_done']), then=Sum(forward_price_effective)), output_field=IntegerField()), return_price_effective=Sum(Case(When(bag_status__in=['return_accepted', 'rto_bag_accepted']), then=Sum('return_price_effective')), output_field=IntegerField())).values('month','year','forward_price_effective', 'return_price_effective', 'gstin_code') -
Add an existing sql to django project
I have a sql file which I want to add to my django, I don't know: where to put the file which commands should I run for adding it many thanks for your help. -
Download Video from URL using Python is not playing
I'm working on a Python(3.6) & Django(2) project in which I need to download a video from a URL. Here's what I have tried: from views.py: if validation is True: url = request.POST.get('video_url') r = requests.get(url, allow_redirects=True) file = open('my_video.mp4', 'wb').write(r.content) rea_response = HttpResponse(file, content_type='video/mp4') rea_response['Content-Disposition'] = 'attachment; filename=my_video.mp4' return rea_response The URL from where it's downloading the vide is: https://expirebox.com/files/386713962c5f8b7556bc77c4a6c2a576.mp4 It downloads a file with the name as my_video.mp4 but when I try to open this video it's not playing. What can be wrong here with my code? OR is there any better way to download the video from URL. -
Making read_only fields while Updating , but not in CREATE Method in ModelSerializer
Am new in python and I want to make an API in Django, one of the challenges am facing, am trying to make an UPDATE endpoint and a CREATE endpoint work. When I neglect some of the required fields during UPDATING it, but the CREATE method doesn't it brings this error message : IntegrityError at /api/articles/comment/4/replies/ null value in column "author_id" violates not-null constraint DETAIL: Failing row contains (2018-09-20 04:24:36.225977+00, 89, English is better, null, null) When I remove read_only in the serializers, the problem goes to the UPDATE endpoint as below in postman: { "comment": [ "This field is required." ], "author": [ "This field is required." ] } The following is my code snippet: My Serializer in serializers.py class RepliesSerializer(serializers.ModelSerializer): class Meta: model = Replies fields = '__all__' read_only_fields = ('comment', 'author',) The views in views.py. class RepliesView(APIView): permission_classes = (IsAuthenticated,) def get_object(self, pk): try: return Replies.objects.get(pk=pk) except Replies.DoesNotExist: raise Http404 def post(self, request, commentID): content = request.data author = request.user.id content['author'] = author content['comment'] = commentID # print('--> ', author) # print('content ---> ',content) serializer = RepliesSerializer(data=content) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self,request, commentID): instance = Replies.objects.all() serializer = RepliesSerializer(instance, many=True) return … -
Django CheckboxSelectMultiple widget aren't rendered as 'checked' while in the admin page responses are correctly saved
as I wrote in the title, a MultipleChoiceField with CheckboxSelectMultiple in my form does correctly save the user response, but after leaving and re-entering the page, the selection disappears, while other radio selections don't, and I can't figure it out why. This is my UserResponseForm in form.py: class UserResponseForm(forms.ModelForm): selection_1 = forms.ChoiceField( required=True, choice=CHOICE_TYPE_1, widget=forms.RadioSelect ) selection_2 = forms.ChoiceField( required=True, choice=CHOICE_TYPE_1, widget=forms.RadioSelect ) ... # Problematic selection_6 = forms.MultipleChoiceField( required=True, choices=CHOICE_TYPE_3, widget=forms.CheckboxSelectMultiple ) And this is the html part: {% elif item_id == 6 %} <div class="multiple-select"> {% for checkbox in field %} <div class="multiple-button"> <label for="{{ checkbox.id_for_label }}"> {{ checkbox.choice_label }}<br />{{ checkbox.tag }} </label> </div> {% endfor %} </div> And this part of the page is rendered like this: enter image description here -
My django model joining wrong fields when there are multiple related fields with join
My product model has two different relationship with category model: One to One One to Many through ProductShadowCategory table. Now the situation is when I tried to fetch using the second relationship, I am getting the result from my first relationship. For example this is what I am trying to print: Category.objects.get(slug="root").shadow_products.all() but it converts to following sql : print(Category.objects.get(slug="root").shadow_products.all().query) SELECT `product_management_product`.`id`, `product_management_product`.`slug`, `product_management_product`.`category_id`, `product_management_product`.`brand_id` FROM `product_management_product` WHERE `product_management_product`.`category_id` = 720 My models looks like following: class Category(SlugableModel): #... shadow_products = models.ManyToManyField("product_management.Product", through="product_management.ProductShadowCategory") class Product(SlugableModel): #... category = models.ForeignKey(Category,on_delete=models.CASCADE, related_name="products", validators=[leaf_category]) class ProductShadowCategory(MyModel): category = models.ForeignKey(Category,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) class Meta: unique_together = ('category', 'product') -
Django uwsgi + nginx repeated processes
I have my application deployed in django web framework running with wsgi + nginx on the production env. Recently, i found some weird behavior from wsgi where it starts executing/repeating the function if the original request does not complete within 4-5 minutes. I increased the read_timeout and write_timeout under nginx config file, however, this issue is still there!! any expert on nginx uwsgi deployment? snippet from nginx.conf file:- location /netadc/ { uwsgi_pass django; include /apps/netadc/netadc/uwsgi_params;# the uwsgi_params file you installed uwsgi_read_timeout 1800; uwsgi_send_timeout 1800; proxy_read_timeout 1800; } Basically this feature/script does lot of pre-validations, creates a snapshot of the n/w devices, pushes configs to around 30-40 devices and does post validations. so it takes 2-3 mins minimum to execute. sometimes when it takes more than 5 mins., it restarts the wsgi process, but not sure why... since i already increased the timeout to 30 mins as shown above. -
Pros and cons for each Backend and front end language and frameworks
Im creating a web application and I’d like any pointers to resources that can tell me the pros and cons of common backend and front end languages and frameworks like nodejs, php, Java, JavaScript, angularjs, reactjs, etc. -
How can I filter django admin inline data?
I want to filter Django ForeignKey models in my admin panel. It has a student profile and It can be able add subject marks. But Problem is student wants to add her or his marks while he get all subject list. But I want to when class-10 grade student add her marks while he will seen her class-10 grade subject list. How can I implement that? class MarksSubjectInstanceInline(admin.TabularInline): model = Marks fk_name = 'std_name' extra = 2 exclude = ['subject_gradepoint', 'subject_gpa','subject_gpa_sub', 'subject_marks', 'subject_total_marks'] @admin.register(StudentInfo) class StudentAdmin(admin.ModelAdmin): list_filter = ('std_class', 'std_gender', 'std_group',) list_display = ('std_name', 'std_class', 'std_group', 'std_gender', 'std_roll') inlines = [MarksSubjectInstanceInline] search_fields = ('std_name','std_roll','std_group') exclude = ['std_total_marks', 'std_gpa','std_grade_point_total_sum','std_marks_with_fail_sub', 'std_grade_point_total_subject_avg', 'std_fail_subject','school_rank','class_rank'] -
django-notifications-hq: cannot show notifications
while the 'unread_list' API works, I cannot get the tag {% live_notify_list list_class="dropdown-menu" %} to work. When going through the code, it seems that it just returns an empty <div> with the CSS class specified. Do I really need to iterate over all the notifications and have them displayed? I want to use a bootstrap popover and populate the messages in there. This is the git for the lib: https://github.com/django-notifications/django-notifications Thanks, Sebastian -
django backend polling framework
I'm trying to make an app that polls a financial data api on the backend, and after a threshold is met alerts a user (in django). What would be best practices/framework for doing such a thing? I imagine you'd want to run some background process that polls every 1 second or something using celery or django-background tasks, but I was wondering if there was a more pythonic way of doing so, perhaps something built into django. -
Python 3 Django on App Engine Standard: App Fails to Start
I'm trying to deploy a Django application on Google App Engine in the Standard Python37 Environment. I've had a version of it running fine in the Flexible environment, but I'm creating a staging version that I want to run in the Standard env. When I deploy and visit the app I get a 500 error. Looking in the logs I can see some messages about exceptions in worker processes. I get the error: ModuleNotFoundError: No module named 'main' This is the stack trace from the error: Traceback (most recent call last): File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/env/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 104, in init_process super(ThreadWorker, self).init_process() File "/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/env/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/env/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app import(module) ModuleNotFoundError: No module named 'main' I haven't modified my_site/wsgi.py since Django created it for me, here it is: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_site.settings") application = get_wsgi_application() This is my app.yaml: runtime: python37 env: standard beta_settings: cloud_sql_instances: project:us-west1:sql-instance handlers: - url: /static static_dir: staticfiles/ … -
React native fetch api does not work with localhost, IP, or even 10.0.2.2
I am using expo client on my android device and have setup up a django server at localhost:8000 and i'm trying to access and endpoint using fetch in react native. I have looked at How can I access my localhost from my Android device? How do you connect localhost in the Android emulator? and How to connect to my http://localhost web server from Android Emulator in Eclipse but that did not work. I also tried using my machine's ip address instead of localhost, but no results. Here is a sample code componentDidMount(){ return fetch('http://my-ip-address:8000/restapi/') .then((response) => { console.log("success") response = response.json() }).catch(error => { console.error(error) }) } What am I doing wrong here? -
Cannot extend template in django 2.0
After reading the documentation twice and numerous pseudo-tutorials I'm stuck with the template generation/extending in Django. My project structure is: root project templates base.html app templates child.html static imgs logo.png On my settings.js: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] My base.html: {% load static %} <html> <head> <title>BioPy</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <img src="{% static "imgs/logo.png" %}" alt="BioPy Logo"> </head> <body> <div class="container"> <div class="row justify-content-center"> <div class="col-8"> {% block content %} {% endblock %} </div> </div> </div> </body> </html> My child.html: {% extend "base.html" %} {% block content %} <h1 class="mt-2">Registration</h1> <hr class="mt-0 mb-4"> {% load crispy_forms_tags %} <form method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit">Sign Up</button> </form> {% endblock %} I got the following error: In the simplified example, BioPy is the project, BioPyApp is the app, registration.html is the child. Best regards, -
Django RelatedManager nesting to access nested fields
Models.py class Order(models.Model): order_name = models.CharField(max_length=10,unique = True, default = "") class LineItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True, related_name="items") product = models.ForeignKey(Product, on_delete=models.CASCADE,null=True, related_name="prod") quantity = models.IntegerField(default = 0) class Product(models.Model): product_name = models.CharField(max_length=10) product_price = models.DecimalField(max_digits=10,decimal_places=2) So I am trying to create an APIView PUT Request to be able to change Order contents. So my create method in OrderItemSerializer is not working correctly. I'm new to Django.. def update(self, instance, validated_data): So basically I am unable to complete this function. This is the structure of my instance - { "order_name": "OrderA", "line_items": [ { "product": { "id": 7, "product_name": "ProdA", "product_price": "23.99" }, "quantity": 2, "product_total": 47.98 }, { "product": { "id": 9, "product_name": "ProdC", "product_price": "19.99" }, "quantity": 23, "product_total": 459.77 } ], "cart_total": 507.75 } The problem is that if I use RelatedManager(reference line_items from the instance I am unable to go any level further). I only get the option to choose between product, quantity and ids.. -
Django - Unknown field(s) (groups) specified for User
I am facing this error when I am trying to do makemigrations and migrate. I have created a custom user model and when migrating I am facing this issue. I only face this issue when I add "AUTH_MODEL_USER = account.User" to settings.py without this I am able to migrate the code. NOTE: 1) Before creating the custom user I had did some experiment using wagtail, so to do the experiment I had created superuser and I don't know whether this issue is because of superuser being created before creating a custom user model. 2) I didn't add any code in admin.py and form.py yet, I wanted to check whether I'm able to migrate the code before typing any further code. account/model.py -
Using Django Debug Toolbar With React JS
I've setup Django Debug Toolbar (via django-debug-toolbar.readthedocs.io). It works for my Django admin panel queries (loading pages), but what I really want it for is the queries coming from my React app. I understand that what it's doing is grabbing the response, finding the </body> tag and inserting it before that, but is it possible to use the toolbar to debug my queries from my react app? I'm sorry if I'm misunderstanding something fundamental about this, but I can't figure out how this works with React. Thank you so much for any help. -
Django - Admin Interfaces - to allow create users for non-superuser
I have the situation of permits the access to admin interfaces to three types of users: - Admin - Supervisor - Agent It's a situation hierarchycal, the admin is one (the superuser) and it's creates the supervisors, and the supervisors create the agents. All them can login to django admin with distincts authorizations. The login has managed by 'django.contrib.auth' with the default model auth_user (. from django.contrib.auth.models import User class Supervisor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) e_mail = models.EmailField(max_length=60, db_column='E-Mail',blank=True) ...other fields.... class Admin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) e_mail = models.EmailField(max_length=60, db_column='E-Mail',blank=True) ...other fields... But, there is a problem. If I allow the supervisor to create an agent implies that I must add the authorization to ADD and CHANGE the table USER. And this is dangerous, any supervisors could become a superuser, deleting users, etc etc.... How can I resolve this problem?? Is it possible to permit the supervisor to create an Agent without that he can be dangerous?? Thanks