Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django getlist getting null
Hello guys im currently learning on how to send data from HTML to Django backend using Ajax. I have this HTML <div class="form-row"> <input type="checkbox" name="car-checkbox[]" value="Audi" id="chck1"> <input type="checkbox" name="car-checkbox[]" value="BMW" id="chck2"> <input type="checkbox" name="car-checkbox[]" value="Lambo" id="chck2"> <input id="submit-car" type="button" value="Submit"> </div> and then to send the data i use this code (Ajax) $('#submit-car').click(function () { const data = {user_id: user_id} $.ajax({ type: 'POST', url: '/submit-car/', data: data, beforeSend: function (request) { request.setRequestHeader("X-CSRFToken", csrftoken); }, success: function (data) { $('#submit-form-field').prop('disabled', true); location.reload(); alert("Submit OK!"); } }); }); and then on the Django side i try to get the checked checkbox def insert_car_to_db(self, request): cars = request.POST.getlist('car-checkbox[]') print(cars) Weirdly enough when i try to get the checked data, i keep getting [] value, where did i miss ? am i misunderstand something? P.S i followed this post How to get array of values from checkbox form Django -
Django RestFramework JWT Token: Get User DoesNotExist error
After a user is deleted, the tokens on the client side are still valid until the time has expired. The issue is django restframwework does not handle a request from a deleted user and causes a 500. How can I prevent this? aceback (most recent call last): File "/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/lib/python3.6/site-packages/rest_framework/views.py", line 493, in dispatch self.initial(request, *args, **kwargs) File "/lib/python3.6/site-packages/rest_framework/views.py", line 410, in initial self.perform_authentication(request) File "/lib/python3.6/site-packages/rest_framework/views.py", line 324, in perform_authentication request.user File "/lib/python3.6/site-packages/rest_framework/request.py", line 220, in user self._authenticate() File "/lib/python3.6/site-packages/rest_framework/request.py", line 373, in _authenticate user_auth_tuple = authenticator.authenticate(self) File "/lib/python3.6/site-packages/rest_framework_jwt/authentication.py", line 33, in authenticate payload = jwt_decode_handler(jwt_value) File "/lib/python3.6/site-packages/rest_framework_jwt/utils.py", line 105, in jwt_decode_handler secret_key = jwt_get_secret_key(unverified_payload) File "/lib/python3.6/site-packages/rest_framework_jwt/utils.py", line 26, in jwt_get_secret_key user = User.objects.get(pk=payload.get('user_id')) File "/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/lib/python3.6/site-packages/django/db/models/query.py", line 431, in get self.model._meta.object_name -
Grouping by date intervals of multiple datetime columns
I have a queryset that I want to group by months, quarters, and years. However, instead of just grouping based on one datetime field of a model, I would want to group by several datetime fields. E.g., I have sign ups for multiple event types (different models) and each of them has a date associated with the sign up. Now, I would like to find how many sign ups I have in total for each month. I used Coalesce(TruncMonth(x), TruncMonth(y), TruncMonth(z)) but that only groups on the first none null field. Is there any other way? -
How to connect android application with django?
I’m making an android app where I’m going to collect sensor data from the android phone and send a collection of data for machine learning model prediction. I have prepared a jupyter notebook for model fitting. How do I connect the android application with Django local server? -
django python has_change_permission for handling DATA_UPLOAD_MAX_NUMBER_FIELDS
I have a questions related about Django Python I'm having problems error of The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. I have red some of the documentations that I need to change / add in settings.py DATA_UPLOAD_MAX_NUMBER_FIELDS to 10240, but i think it won't solve of my problems. on my model, I have Inline models which related one to many, and they can't be modified, but how about if i add permission has_change_permission to false? will the inline value still sent to the server? thanks before -
How do i Fix django.db.utils.DatabaseError
How do i fix Django Database error. I'm using MongoDB with Djongo. Everything was working fine until recently when i decided to add NewApp. Whenever i try to migrate it greets me with django.db.utils.DatabaseError . I tried reseting the DataBase Manually as well as from Terminal but had no luck. I think it's super simple but imm new to Django and MongoDB can't seem to figure out how to fix it, any help will be greatly appreciated. Here's what the error looks like. Not implemented alter command for SQL ALTER TABLE "articles_article" ADD COLUMN "author_id" int NOT NULL Applying articles.0002_article_author...Traceback (most recent call last): File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 783, in __init__ self._query = self.parse() File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 875, in parse raise e File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 856, in parse return handler(self, statement) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 888, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 425, in __init__ super().__init__(*args) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 84, in __init__ super().__init__(*args) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 435, in parse self._add(statement) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 598, in _add raise SQLDecodeError(err_key=tok.value, djongo.exceptions.SQLDecodeError: Keyword: int Sub SQL: ALTER TABLE "articles_article" ADD COLUMN "author_id" int NOT … -
Django, Many-to-one relationship with Abstract entities
Say object contains multiple types of objects (Models) in an array, like a Page, that could contain a Post, Blog, Picture, in any quantity or order, where the user scrolls down and sees the following element and that depending on the page, is next element one of these types of elements. Thus a Page could contain: A Post A Post A Picture Or something pretty different such as: A Picture A Blog A Picture An element could be an abstract entity that has an attribute as a ForeignKey relating itself with Page, and its inheritance would gain access to that relationship: class Page(models.Model): ... class PageElement(models.Model): page = models.ForeignKey(LandingPage, verbose_name="Page", on_delete=CASCADE) class Meta: abstract = True class Post(PageElement): ... class Blog(PageElement): ... class Picture(PageElement): ... With this approach, you can serialize Page with a REST serializer, but you wouldn't have access to an pageElement_set, instead you would need to call post_set, blog_set, picture_set and loose the order of the objects. The question is: How do you implement such relationships in Django? So that you can have an order set of PageElement instances, and be able to have the desired order. -
Django: Do i have to restart celery beat, celery worker and Django gunicorn when new changes are uploaded to production server
I have a production server running Django application Django server is run using gunicorn and nginx pipenv run gunicorn --workers=1 --threads=50 --bind 0.0.0.0:8888 boiler.wsgi:application celery worker is run using pipenv run celery -A boiler worker celery beat is run using pipenv run celery -A boiler beat Now i have updated my model and few views on my production server (i.e pulled some changes using github) Now inorder to reflect the changes should i restart all celery beat,celery worker and Django server gunicorn or only celery worker and Django server gunicorn is sufficient or only Django server gunicorn is sufficient -
Django REST on Local Network
I know this is probably not the best place to ask but I can't seem to find a better one so here goes... I want to set up a local system using DJango REST and react.js/native as the UI for accessing the API on the same network e.g. a tablet which is fed a PWA would be fine. The server exists in-house and I do not want it connected to the web. Is it possible to deploy a production site from a local server and have it accessed only locally? It seems like it should be possible. If it is, how do you go about handling Https/SSL? I see self-signed certs but everywhere says not to use them on a production system. Can someone give me advice on how I can make this secure/possible? Edit: I should add that I would want to use Apache web server. -
Query a data in legacy mysql table views in django
I would like to connect in my legacy mysql view using django, but the models read tables only, how can i query in a mysql view using django models and orm? I tried something like this, here is my models.py from django.db import models class VwFullDetailBi(models.Model): control_no = models.CharField(max_length=50) fname = models.CharField(max_length=50) mname = models.CharField(max_length=50) lname = models.CharField(max_length=50) birthday = models.DateField(blank=True, null=True) class Meta: managed = False db_table = 'vw_fulldetail_bi' my serializers.py from rest_framework import serializers from .models import VwFullDetailBi class DetailsSerializer(serializers.ModelSerializer): class Meta: model = VwFullDetailBi fields = '__all__' and my views.py from django.shortcuts import render from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.generics import get_object_or_404 from .models import VwFullDetailBi from .serializers import DetailSerializer @api_view(['GET']) def farmerDetails(request): control_no = request.GET.get("control_no") details = VwFullDetailBi.objects.using("other_db").filter(control_no=control_no) detailSerializer = DetailSerializer(details, many=True) return Response(detailSerializer.data) I got this error and i know that perhaps the models treating it as table and not as view. (1146, "Table 'other_db.vw_fulldetail_bi' doesn't exist") -
How to generate multiple Dash App (and URLs) programmatically?
I have a simple Dash app with a choropleth map along with a simple dropdown. The data is sourced from a pandas dataframe and contains a few different metrics for each US state. I'd like to reproduce this standard layout for each of the US state but here's the problem: I'd like to avoid having to create 50 different dash apps (it doesn't look really practical neither scalable) I don't want to have a dropdown for users to select the state: the goal is to have multiple URLs, one for each state (mostly for search engine purposes). I was thinking of passing the US state as a URL parameter: I'd use this variable to filter the dataframe (limiting the dataframe scope will automatically make the choropleth zoom to the relevant state). However this is problematic since: Dash doesn't allow to set a default base URL for the app (at least as far as I could tell) The df cleaning/filtering happens before I can call the flask instance in Dash (this would be easily solvable though) as well as the app URL. I wanted to do this all within Dash for practicality but I guess I'd need to rely on Flask/Django … -
Django Allauth integration with Django CMS
I'm using DjangoCMS and AllAuth on a website I'm working on - I'm trying to get Django CMS to automatically send you to AllAuth's login page, instead of it's own admin page. Here's my current urls.py file: urlpatterns = [ path("sitemap.xml", sitemap, {"sitemaps": {"cmspages": CMSSitemap}}), path('en/accounts/', include('allauth.urls')), ] urlpatterns += i18n_patterns(path("admin/", admin.site.urls), path("", include("cms.urls"))) The issue is that DjangoCMS, when it's grabbing the admin page to show, using namespacing to get admin:login. Now, my thought was I can just have the namespace admin refer to AllAuth - but AllAuth doesn't support namespacing. Is there any way to either: Have that automatically redirect to AllAuth? I'd think it might be possible to have the default admin's page redirect in the view itself, but I'd rather not try to change the built in Django code Have that namespace get sent to a specific URL, even if AllAuth doesn't support it by default. Thanks! -
send_mail() missing 1 required positional argument: 'recipient_list'
Why i am receiving this error? send_mail() missing 1 required positional argument: 'recipient_list' did i miss something? from django.core.mail import send_mail from django.template import Context, loader def contact(request): .... email_template = loader.get_template('accounts/print.html') send_mail(email_template, [settings.EMAIL_HOST_USER], Email, fail_silently=False) -
GenericViews - and pushing model name in URL
using Django Generic CreateView - is it possible for me to pass a value into the CreateView from the URL call, that defines which model/table to base the view on? I did try get_context_data but believe that is not the solution, as I think it only pushes it to the rendered template. You will see from my scripts - I am pushing the value 'syslog_policy' - i would like the view to set the model variable to be, what-ever value I push from the URL. The reason for this, I have some pages/models that are similar - so rather than create multiple html pages and views - I wouldn't need to if I could get this to work. URL Call <li><a href="{% url 'security_app:HardenTemplateCreate' 'syslog_policy' %}">Update/Delete Policies</a></li> urls.py path('HardenTemplateCreate/<str:element>', HardenTemplateCreate.as_view(success_url="/security_tooling/add_success") ,name="HardenTemplateCreate") views.py def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['element']= self.kwargs['element'] print(context['element']) return context model = !!<NEED VALUE SUPPLIED IN URL HERE>!! fields = ['name','template'] template_name = 'security_app/add.html'``` -
Generating audio files in a Django project template
I am attempting to create a pretty simple website using Django that will have a number of audio files stored in it and available for streaming and downloading. I know that there are other ways to do this, like using AWS, but I wanted to figure this way out first. I'll include my template here but wanted to note that it is currently messy because I have been experimenting with different structures to figure this problem out. {% for song in concert.song_set.all %} <li>{{ song.song_title }}</li> <li>{{ song.song_location }}</li> <!-- Working --> <audio class = "audioPlayer uniqueShowAP" controls <--controlsList="nodownload" src="{% static 'shows/audio/redRocks2019/01 Yi.mp3' %}"> Your browser does not support the <code>audio</code> element. </audio> <!-- Not Working...yet --> <audio class = "audioPlayer uniqueShowAP" controls <--controlsList="nodownload" src="/shows/static/shows/{{ song.song_location }}"> Your browser does not support the <code>audio</code> element. </audio> {% endfor %} What I want to happen is for every concert that I save it will go through the songs saved under that concert and add them to under the name of the song. I have each song's relative location saved in the data base so that I should be able to just call upon it's location. I've tested this out by calling … -
Django 3.1 bug: Reflexive Many-to-many relations. Add creates two relationships instead of one
in the model called Business: sold_at_businesses = models.ManyToManyField('self', db_table='businesses_to_sold_at_businesses', related_name='businesses_selling') test code - ms is a Business instance. ms.sold_at_businesses.clear() b = Business.objects.get(slug="test-business") if b: ms.sold_at_businesses.add(b) Bug: This single add call adds two entries to the pivot table. m -> b and b -> m Why are two connections being created when I clearly specify only one? this seems like a reflexive model bug in Django. -
How to set dynamic attributes in django rest framework serializers?
I have some json in the following format: { "daySchedules": { "500000004061582000": { "scheduleName": "Friday-Sunday", "services": [ { "name": "Lunch", "hours": { "startTime": "12:00:00.000", "endTime": "16:00:00.000" }, "overnight": false }, { "name": "Dinner", "hours": { "startTime": "17:00:00.000", "endTime": "23:00:00.000" }, "overnight": false } ], "openTime": "12:00:00.000", "closeTime": "23:00:00.000" }, "500000004061559163": { "scheduleName": "Tuesday-Thursday", "services": [ { "name": "Breakfast", "hours": { "startTime": "04:00:00.000", "endTime": "11:00:00.000" }, "overnight": false }, { "name": "Lunch", "hours": { "startTime": "12:00:00.000", "endTime": "16:00:00.000" }, "overnight": false }, { "name": "Dinner", "hours": { "startTime": "17:00:00.000", "endTime": "20:00:00.000" }, "overnight": false } ], "openTime": "04:00:00.000", "closeTime": "20:00:00.000" } }, "weekSchedule": { "monday": null, "tuesday": "500000004061559163", "wednesday": "500000004061559163", "thursday": "500000004061559163", "friday": "500000004061582000", "saturday": "500000004061582000", "sunday": "500000004061582000" } } The attributes in the json 500000004061582000 and 500000004061559163 is dynamic and determined by what's returned in the weekSchedule. I wish to create the following serializers: class ScheduleForDaySerializer(serializers.Serializer): schedule_name = serializers.CharField() services = serializers.ListField() open_time = serializers.CharField() close_time = serializers.CharField() class WeekScheduleSerializer(serializers.Serializer): monday = serializers.CharField(allow_null=True) tuesday = serializers.CharField(allow_null=True) wednesday = serializers.CharField(allow_null=True) thursday = serializers.CharField(allow_null=True) friday = serializers.CharField(allow_null=True) saturday = serializers.CharField(allow_null=True) sunday = serializers.CharField(allow_null=True) class DaySchedulesSerializer(serializers.Serializer): # what comes here? class SchedulesSerializer(serializers.Serializer): day_schedules = DaySchedulesSerializer() week_schedule = WeekScheduleSerializer() I'm struggling to determine how … -
Django Drop Down List Values
I am using a helper.py to store all my queries and not taking advantage of the models.py. I have a form that inserts the value into my helper.py queries. Basically its filtering my search results. THe issue I am having is that once it filters the results. The drop down menu also shrinks with it. I would have to hit the back button to get a whole list to filter again. Is there a way I can filter the results and still keep all my drop down list values? Also, my page takes a very long time to load because the query executing has thousands of rows! Actual Result Drop down List: Chris Evan Patty Then if I choose Chris on the drop menu then Evan and Patty disappear when it narrows the query results and inputs Chris in my query. drop down list: Chris code helper.py def EmployeeBalancing(get_dropdown_value, procdate): cursor = connection.cursor() print(cursor.execute(f'''select distinct to_char(processingdate,'YYYY-MM-DD'), opstattypeskey, loginname, firstname, lastname, active_time, idle_time, items, keys, rejects,bypass,b_function, from ppc_data.emp_performance where to_char(processingdate,'YYYY-MM-DD') = '{procdate}' and loginname='{get_dropdown_value}' order by to_char(processingdate,'YYYY-MM-DD'), opstattypeskey, loginname, firstname, lastname, active_time, idle_time, items, keys, rejects,bypass,b_function desc ''')) query = cursor.fetchall() return query def EmployeeBalancing_Null(): cd = datetime.now().strftime('%Y-%m-%d') print(cd) cursor = … -
Django Run a Test By Its Filename
I have a django application with a test called test_thing.py Ive been running my test as such: python3 manage.py test --pattern="test_thing.py" Is there a way that I can run the test by its filename? I tried python3 manage.py test apiv2/tests/test_thing.py but I get an error: TypeError: 'NoneType' object is not iterable But when I run with the --pattern it works. -
Django multiple ManyToManyField with same model
When I only have one ManyToManyField the model works but when I add a second the serializer doesn't save. View: @api_view(['POST']) def update(request, pk): poll = Poll.objects.get(id=pk) serializer = PollSerializer(instance=poll, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) Model: class Poll(models.Model): title = models.CharField(max_length=200) option1 = models.CharField(max_length=200) option2 = models.CharField(max_length=200) option1total = models.IntegerField(default=0) option2total = models.IntegerField(default=0) owner = models.CharField(max_length=150, null=True) option1votes = models.ManyToManyField(User, related_name="option1votes") option2votes = models.ManyToManyField(User, related_name="option2votes") Example request: {'id': 17, 'title': 'What is your favorite programming language?', 'option1': 'Javascript', 'option2': 'Python', 'option1total': 2, 'option2total': 25, 'owner': None, 'option1votes': [], 'option2votes': [14]} -
HTML if div content is long show button
I have this django app I made, and it is a blog app. The blogs are quite long, so I want to be able to show a little and then more of the div's text if the blog is long. Here is my html: <a style="text-decoration: none;color: #000;" href="{% url 'post-detail' post.id %}"> <div id="content-blog"><p class="article-content">{{ post.content|safe }}</p></div> </a> I want something like this: <script> content = document.getElementById("content-blog"); max_length = 1000 //characters if(content > max_length){ //Do something } </script> So how would I get this to actually work. To summarize, I want this to check if a div is longer than 1000 characters, and if it is, to run the if statement above. Thanks. -
Reload DataTable content with jQuery ajax call
I have a DataTable and I want to filter it's content depending on what user selects in form. Here is the sample of code I use: $(document).on('click', '#filter_btn', filterList) function filterList (event) { event.preventDefault() var form_data = $('.filter-form').serialize() var url = window.location.origin + '/my-amazing-url/' $('#dataTable-x').DataTable({ ajax: { url: url, type: 'get', dataType: 'json', data: form_data } }) $('#dataTable-x').DataTable().ajax.reload() } On server side Django returns following: ... data = self.get_queryset().values() return JsonResponse(data) ... Yet nothing is changed. How should I modify the code? Thanks. -
Using Django REST on local network
I am wondering if it is reasonable to use Django REST on a private network with a local in-house server, using React.js/Native as a UI for a security system? I know Django REST, react, and other JS libraries so my thoughts are that it will be much easier/faster to develop this way. Are there any obvious issues with this? Has anyone else used a local Progressive Web App or local website for this type of system? With the amount of JS libraries out there I am sure the development would be much faster. Thanks! -
Django Class based view loading another form with data
I am not sure if I am using this Class based view correctly. What I am trying to do I thought was very simple. Basically is a form based on a model where I only use the 'User' field from: class OnSiteLog(models.Model): objects = models.Manager() user = models.ForeignKey(User, on_delete=models.CASCADE) checkIn = models.DateTimeField('checkin_date', null=True, blank=True) checkOut = models.DateTimeField('checkout_date', null=True, blank=True) notes = models.CharField(null=True, blank=True,max_length = 200) location = models.CharField(null=True, blank=True, max_length=200) autoCheckin = models.BooleanField(null=True, blank=True, default=False) class QueryUser(LoginRequiredMixin, FormView): model = OnSiteLog form_class = QueryForm template_name = 'log/query.html' success_url = '/' def post(self, request, *args, **kwargs): theRecord = OnSiteLog.objects.filter(user_id=24) print(theRecord[0].user) super(QueryUser, self).post(request, *args, **kwargs) return render(request, 'log/query.html', {'log':theRecord}) From there: the template is pretty simple with a crispy form: {% block content %} <div class="breadcrumb-area"> <!-- Background Curve --> <div class="breadcrumb-bg-curve"> <img src="{% static '/img/core-img/curve-5.png' %}" alt=""> </div> </div> <div class="container"> <h2> Query for User </h2> <div class="row"> <div class="col-sm"> {% crispy form %} </div> </div> <div class="row"> Logs <div class="col-sm"> <table class="table"> <tr> <th>User</th> <th>Check In</th> <th>Check Out</th> <th>Location</th> <th>Notes</th> </tr> {% for ins in log %} <tr> <td>{{ ins.user }}</td> <td>{{ ins.checkIn }}</td> <td>{{ ins.checkOut }}</td> <td>{{ ins.location }}</td> <td>{{ ins.notes }}</td> {% if request.user.is_superuser %} <td> <a href="{% … -
How can you output something when login is completed? Django
I'm trying to build a form that when the login button is clicked, it displays a login succesful message. Here is the thing, I want that when the "login" button is clicked, the user gets redirected and in the redirected page (which is the home page), it should show the message. How can you do this in Django? I've tried doing: {% if request.user.is_authenticated %} But the problem with this code is that the message appears each time, even when you reload the page.