Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python web application framework for large data sets?
I'm wondering if anyone here can help with a general impression of suitability for frameworks? I work in a role that somewhat resembles data-scientist along-side many other disciplines and I almost exclusively use python. I'm writing a dashboard app in plotly-dash with the hopes of deploying to a client. It has lots of multi-select dropdown menus for filtering the data and displays graphs which update when the selections are changed. My issue is that the data-set the app is dealing with is roughly 25 columns, 12 filters and 1.5milion rows. The app is slow to say the least... Does anyone here know of a suitable framework for the development of webapps in python that can handle very large data-sets with some sort of "speed"? I'm perhaps looking at django for this though if anyone has experience doing something like this with performant results i'd love to know what you used. Thanks a lot. -
how to find previous url that user comes from
I want to find out which URL user comes from to redirect there after doing something in my views.py def. I have three URLs like : mysite/link1 mysite/link2 mysite/link3 and in one of them, there is an a tag that loads mysite/superlink. now in my superlink def in views.py, I want to know user comes from which one of three links? i use request.META.get('HTTP_REFERER') but it returned current URL, means mysite/superlink ! -
How to load an initial value for a ClearableFileInput / FileField (before form is bound)
How do I set an initial value for a FileField that will display in a ClearableFileInput widget when creating a new object (unbound form)? I have tried the following but widget.value does not return a FeildFile instance if it is the first time the user is creating the object: models.py class MyModel(models.Model): myfile=models.FileField() forms.py class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['myfile'].initial= 'myfile.pdf' class Meta: model = Issuer fields = ['myfile'] This results in : Similarly, setting a default value in the modelfield does not work: class MyModel(models.Model): myfile=models.FileField(upload_to='mydocs', default='mydocs/myfile.pdf') The widget initial value is still None, but if it is left empty and saved the file object will be created. The settings.MEDIA_URL and urls.py is definitely correct and the file is on the system because it is loaded after form save. What I am missing is showing it as an initial value before a form is saved and an object created. -
my pre_save signal is not working as i want to update my slug field using this signal
here i want to create slug based on the content automatically just before the Question model instance is saved but the slug field is not created as i want to here is my models.py class Question(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) content = models.CharField(max_length=240) slug = models.SlugField(max_length=240, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="questions") class Answer(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) body = models.TextField() question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="answers") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) voters = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="votes") my apps.py from django.apps import AppConfig class QuestionsConfig(AppConfig): name = 'questions' def ready(self): import questions.signals my init.py default_app_config = "questions.apps.QuestionsConfig" and finally the signals.py from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils.text import slugify #we'll use it to create slug based on the content of the instance from core.utils import generate_random_string from questions.models import Question @receiver(pre_save, sender=Question) def add_slug_to_question(sender,instance,**kwargs): if instance and not instance.slug: slug = slugify(instance.content) random_string = generate_random_string() instance.slug = slug + "-" + random_string -
Regex to check validation in Django
I am trying to code for the following validation in Django: "Capital Letters are allowed only as of the first-word letter or only if all letters in a word are uppercase" I have done this till now, but it is failing, Can someone please help me? RegexValidator( regex='(^[A-Z][\sa-z0-9]+$)|(^([A-Z]\w*\s*)+$)', message='Capital Letters are allowed only as first word letter or only if all letters in word are uppercase', code='invalid_capitalisation' ) -
How best to make a view executable via cron or Heroku schedular?
I have the following view. The template just asks "Are you sure you want to do X?", if the user clicks yes then it submits a blank for which then executes the code under `if request.method == 'POST':'. I need this same code to also be executed once a night using Heroku Schedular. Heroku schedular allows me to execute admin tasks on a given schedule, eg every day at 2am I can execute python manage.py someAdminCommand How best to organise this code so that it can be executed by both the view and an admin command without writing the code twice in the view and admin command? The code doesn't require any inputs from the user, it just queries the database and sends the data to another microservice. I was thinking maybe put this code into a function in a new library (python file) and then call it from both the view and the admin command? Views.py @login_required def populategsheet(request): if request.method == 'POST': print('Populating Google Sheet...') # A bunch of code here return render(request, 'journal/populate_gsheet.html') -
Django ImportError: cannot import name 'ReporterProfile' from partially initialized module 'accounts.models' (most likely due to a circular import)
I have two apps named collection, accounts. Both apps have models defined. I am importing a model ReporterProfile from accounts app to collection. Similarly, a model Report from the app collection to accounts. The Report model from collection app is called in a model class method in accounts app like this: from collection.models import Report class ReporterProfile(models.Model): .... def published_articles_number(self): num = Report.objects.filter(reporterprofile=self.id).count() return num Similarly, I am importing ReporterProfile and User models from accounts app to collection app model like this: from accounts.models import ReporterProfile, User from <project_name> import settings class Report(models.Model): reporterprofile = models.ForeignKey(ReporterProfile, on_delete=models.CASCADE, verbose_name="Report Author") ... class Comment(models.Model): report = models.ForeignKey(Report, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name="Comment by") ... When running the server or makemigrations, I'm getting the error: File "F:\project_name\accounts\models.py", line 8, in from collection.models import Report File "F:\project_name\collection\models.py", line 2, in from accounts.models import ReporterProfile, User ImportError: cannot import name 'ReporterProfile' from partially initialized module 'accounts.models' (most likely due to a circular import) (F:\project_name\accounts\models.py) I think the error is coming because of wrong importing pattern. What should I do? -
Not able to serve django static css and js by using apache http server
Looking for instant help on this. The wsgi content is working fine and images from static are also loading, but css and js is missing. The servername and alias is fine. Here is my conf file. : WSGIDaemonProcess abc.com python-home=/opt/new python-path=/opt/new/4finalTest WSGIProcessGroup abc.com WSGIApplicationGroup %{GLOBAL} Alias /static/ /opt/new/4finalTest/staticfiles/ <Directory /opt/new/4finalTest/staticfiles> Options Indexes FollowSymLinks MultiViews AllowOverride None Require all granted </Directory> Alias /media /opt/new/4finalTest/media/ <Directory /opt/new/4finalTest/media> Require all granted </Directory> WSGIScriptAlias / /opt/new/4finalTest/kumauni/wsgi.py <Directory /opt/new/4finalTest/kumauni> <Files wsgi.py> Require all granted </Files> </Directory> -
How to initialize datas for a choice field in createview?
I want to initialize datas for a choice field in my createview to limit the choices. My model : class TimeSlot(models.Model): """ add a timeslot """ DAYS_CHOICES = ( (0, "Lundi"), (1, "Mardi"), (2, "Mercredi"), (3, "Jeudi"), (4, "Vendredi"), (5, "Samedi"), (6, "Dimanche") ) room = models.ForeignKey(Room, on_delete=models.CASCADE) day = models.IntegerField(choices=DAYS_CHOICES, default=0) time_start = models.TimeField() time_end = models.TimeField() class Meta: verbose_name = "horaire d'ouverture" verbose_name_plural = "horaires d'ouverture" def __str__(self): return "Horaire d'ouverture" My view : class TimeSlotCreateView(CreateView): model = TimeSlot template_name = "dashboard/createTimeSlot.html" success_url = reverse_lazy('dashboard_list_timeslot') form_class = CreateTimeSLotForm def get_form_kwargs(self): kwargs = super(TimeSlotCreateView, self).get_form_kwargs() rooms = Room.objects.filter(club=self.request.user.profil.club_administrator) kwargs.update({'rooms': rooms}) return kwargs My form : class CreateTimeSLotForm(forms.ModelForm): """ add room """ class Meta(): model = TimeSlot fields = ('room', 'day', 'time_start', 'time_end') def __init__(self, rooms, *args, **kwargs): super(CreateTimeSLotForm, self).__init__(*args, **kwargs) self.fields['room'] = forms.ChoiceField(choices=tuple([(room.pk,room.name) for room in rooms])) The field room is correctly initialize but when I submit the form : Cannot assign "'1'": "TimeSlot.room" must be a "Room" instance. It's very strange because the POST datas are correct : -----------------------------26633367911547435358524036933 Content-Disposition: form-data; name="csrfmiddlewaretoken" xXmjTKTBLT4BvzPyW2yH9GZBPosRMChVtSLR4GHskgOivxchmfWaK6rLEILGkbRP -----------------------------26633367911547435358524036933 Content-Disposition: form-data; name="room" 1 -----------------------------26633367911547435358524036933 Content-Disposition: form-data; name="day" 0 -----------------------------26633367911547435358524036933 Content-Disposition: form-data; name="time_start" 12:00:00 -----------------------------26633367911547435358524036933 Content-Disposition: form-data; name="time_end" 18:00:00 -----------------------------26633367911547435358524036933-- I don't understand because … -
Django-Filter FilterSet Show Only User Generated Objects
I'm using a django-filter form and it's filtering all objects for 'associated_portfolios' how can I make it so it only shows the user the objects they created? Error message: 'StatsFilter' object has no attribute 'fields' Filters.py class StatsFilter(django_filters.FilterSet): associated_portfolios = django_filters.ModelMultipleChoiceFilter(queryset=associated_portfolios) class Meta: model = Trade fields = ['type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios'] def __init__(self, request, *args, **kwargs): super(StatsFilter, self).__init__(*args, **kwargs) self.fields['associated_portfolios'].queryset = Trade.objects.filter(user=request.user)] views.py class StatsView(LoginRequiredMixin, FilterView): model = Trade template_name = 'dashboard/stats.html' filterset_class = StatsFilter def get_context_data(self, **kwargs): filter = StatsFilter1(self.request.GET, queryset=self.get_queryset()) context = super().get_context_data(**kwargs) context['filter'] = filter context['get_users_trades'] = Trade.objects.get_users_trades('tj3admin') context['get_largest_winning_trade'] = filter.qs.aggregate(max_value=Max('profit_loss_value_fees'))['max_value'] return context -
waypoints infinite scroll not working on django
So I wanted to add infinite scroll to one of my pages and decided to apply waypoints infinite scroll but I could not get it to work. The problem occures in two different ways; sometimes the function keeps triggering forever and views.py keeps rendering request but nothing is loaded or it only triggers once and doesn't load anything at all neither. I'm not sharing the whole function as it works fine while performing a standart pagination. I think the only part I need to tell is that in html I do not iterate over the paginator list but instead I use another list that my code creates by modifying query objects. I do not know if that is the problem. Html code: {% extends "layout.html" %} {% load static %} {% block body %} <h1 class=yazar>{{yazar}}</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus auctor pharetra purus in viverra. Suspendisse nec sem eget urna blandit malesuada. Duis pellentesque nibh vel rutrum placerat ligula.</p> <div class=yazar-top> <a class=t-holder href=""> <p class=p1>takipçiler</p> <b class=b1>{{follow}}</b> </a> <a class=t-holder href=""> <p class=p1>takip ettikleri</p> <b class=b1>{{followed}}</b> </a> <a class=t-holder href=""> <p class=p1>başlıkları</p> <b class=b1>{{titles}}</b> </a> <a class=t-holder2 href=""> <p class=p1>yazıları</p> <b class=b1>{{entry_count}}</b> </a> </div> … -
Django Logbook Timefield() subtraction for total time
i have been trying to figure how how do I do a simple subtraction between two time fields and show the total time on the admin page as well for confirmation before saving. example would be actual time of arrival - actual time of departure = total flight time atd = models.TimeField(null=True, default='00:00:00') ata = models.TimeField(null=True, default='00:00:00') trying to get atd - ata to get the total flight time, how do i do this in django. thanks for your help! -
Make special field that partially submits form for further processing
I want to make a custom form field, for example an address search field. The user enters a partial address, and can pick from a list of suggestions. With Javascript, it is clear to me how to do this (do some Ajax, show a popup, return the final value with a normal HTML field). How would I implement such a pattern in Django without Javascript? I would like a special field where the user can press enter (or click a button). This submits the form, but not for final processing. Instead, it computes the list of suggestions, and renders the form again with the suggestions (and the other data filled in). One solution I can imagine is: Make the form field return a special "incomplete" value In the view, reach into the form, and check for 'addressfield.incomplete' If true, calculate the list to the field can render it and show the form again If false, process the form as usual The downside is that this requires cooperation by the view, and possibly the form object. So this makes it complicated to use if I want to package my Field in an app. Is there a sanctioned way in Django to … -
Django filter by two parameters
I want to filter by two parameters. I have this: def get_queryset(self): queryset = Product.objects.filter( Q(category__in=self.request.GET.getlist("category")) & Q(brand__in=self.request.GET.getlist("brand"))) return queryset But this works only if two filters are chosen(otherwise it returns nothing). I want my program to filter by one filter if only one is chosen and filter by two parameters if two are chosen. How can I do that? -
Treat as empty submitted form if only date field is submitted
I have an inlineformset_factory with a couple of fields where date = forms.DateField() is one of them. If i submit an empty form there is no error. But if i submit it with only date filled in I get an error that the other fields are needed (what is the normal behaviour and it should work like this as those other fields are necessary in case of a valid form). What I want is that if only the date field is filled in the form should be regarded as an empty form and an error is not raised. How can I do this? The reason I want this is that I want to fill in the date field with the current date (via js) so the user doesn't need to fill that in as it the current date 9 out of 10 times. -
how to debug django custom management commands in pycharm
I am not able to add command-line arguments in edit configuration. I cannot see Additional options in the edit configuration which is mentioned in the docs. Here is the step I have followed: Run > Edit Configurations... Click green + (plus sign) In the drop-down menu, choose Django Server. Check "Custom run command" and enter your command (the part that goes after manage.py in the console. Make sure "Port" and "Host" are empty. If not—make them empty. 5."Apply" and "Close" but my query is how to pass command-line arguments in the debugger? Here is my script: python manage.py insert -n "subhanshu" -tz " Africa/Abidjan" --activityperiod '[{"starttime":"24/11/1995-11:00PM"}]' -
cl.formset does't exist in change_list.html
Something very strange happened. This is really weird and I can't really explain it but I was working on a model.py yesterday and when I came back today, I see that the change_list doesn't show me the change_list results. Here's my change_list: {% extends "admin/base_site.html" %} {% load i18n admin_urls static admin_list %} {% block extrastyle %} {{ block.super }} <link rel="stylesheet" type="text/css" href="{% static "admin/css/changelists.css" %}"> {% if cl.formset %} <link rel="stylesheet" type="text/css" href="{% static "admin/css/forms.css" %}"> {% endif %} {% if cl.formset or action_form %} <script src="{% url 'admin:jsi18n' %}"></script> {% endif %} {{ media.css }} {% if not actions_on_top and not actions_on_bottom %} <style> #changelist table thead th:first-child {width: inherit} </style> {% endif %} {% endblock %} {% block extrahead %} {{ block.super }} {{ media.js }} {% endblock %} {% block bodyclass %}{{ block.super }} app-{{ opts.app_label }} model-{{ opts.model_name }} change-list{% endblock %} {% block content %} {% if cl.formset and cl.formset.errors %} <p class="errornote"> {% if cl.formset.total_error_count == 1 %}Please correct the error below.{% else %}Please correct the errors below.{% endif %} </p> {{ cl.formset.non_form_errors }} {% endif %} <div class="col-12"> <div class="card"> <div class="row card-header m-0 mt-2"> <div class="col-auto pr-2 pl-2"> {% block … -
Django - Make migration command detects changes but on migrating says 'No migrations to apply'
i am new to django developement after making changes to my model i tried to run the command python manage.py makemigrations my_app it detects changes in my model and shows me the message todoapp/migrations/0001_initial.py - Create model confess - Create model UserChoice - Create model comment but on executing python manage.py migrate my_appcommand i've got this message No migrations to apply. i usually do this after making changes in models, i don't know what happened now. plss help me. -
GenericAPIView' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method
class GenericAPIView(generics.GenericAPIView,mixins.ListModelMixin): queryset = Article.objects.all() serilizer_class = ArticleSerializer def get (self,request): return self.list(request) -
ModuleNotFoundError: No Module Named cant figure out why
going to retrieve a simple httpresponse from view at nested app, but some how having this error which cant figure out what the problem. project url.py from django.contrib import admin from django.urls import path, include from django.http import HttpResponse, HttpRequest # from .corex import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('corex.urls')), ] app[corex] url.py from django.urls import path, include from . import views urlpatterns = [ path('', views.testcorex, name='testcorex'), ] app views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def testcorex(request): return HttpResponse('module passed') traceback error File "/home/differentmonster/App/x_house_project/x_house_backend/x_house_cms/urls.py", line 11, in <module> path('', include('corex.urls')), File "/root/.cache/pypoetry/virtualenvs/x-house-cms-p6EwdKv_-py3.8/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'corex the installedApp should be no problem cause, if i import corex.views directly into root urls.py, the response works. but after i added the url.py into app, … -
How to use AJAX spinner in django(prefer to use some library) while waiting until file is processed in backend
The Form I want that after I click the submit button a spinner/progressbar(preferred) should pop up on the screen while the uploaded file is being processed in the backend. A csv file will be processed and based on number of rows processed the width of the progressbar should change. I don't know how that signal to change the width dynamically can be tuned.It would be better if the progressbar hides the form for the duration the file is being processed. Once the file is processed then the /success/ template will be loaded where I would show some stats of the files like number of rows failed to process. I saw this package but 'm too noob to use it. I know javascript and so please don't hesisate to talk about that if required. https://pypi.org/project/django-lazy-tags/ Thanks, class EmailView(FormView): template_name = 'Email/index.html' form_class = forms.EmailForm success_url = '/success/' def form_valid(self, form): # form.send_email() # return super().form_valid(form) print(form) index.html {% extends 'Base/index.html' %} {% load static %} {% load crispy_forms_tags %} {% load bootstrap4 %} {% load lazy_tags %} {% bootstrap_css %} {% block main %} <link rel="stylesheet" href="{% static 'Email/index.css' %}"> {% crispy form %} {% endblock main %} form.py class EmailForm(forms.Form): … -
I've installed the django-cors-headers but still get No 'Access-Control-Allow-Origin' header error
I use a simple JS code to get data from an API, but I encountered No 'Access-Control-Allow-Origin' error, I installed django-cors-headers and configured settings.py according to the tutorial, but still got the same error.Am I missing something here? I use Google Chrome and have not tested other browsers yet. part of my settings.py ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sde.apps.SdeConfig', 'mptt', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True and my js code <script> var x = new XMLHttpRequest(); x.open("GET","https://www.ceve-market.org/api/marketstat?typeid={{i.typeid}}&regionlimit=10000002",true); x.onreadystatechange = function() { if (x.readyState==4 && x.status==200){ var doc = x.responseXML; console.log(doc); } }; x.send(null); </script> error messages on console Access to XMLHttpRequest at 'https://www.***.org/api/' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. VM2118:10 GET https://www.***.org/api/ net::ERR_FAILED -
ajax succes function not worked
i' trying to send data from ajax to django. here is my script: $(document).ready(function(){ $('#accept_all').click(function(){ var id_list = []; $('#table input:checked').each(function() { id_list.push($(this).attr('value')); }); $.ajax({ url: "/myurl", type: "post", data: { 'id_list': id_list, }, headers: {'X-CSRFToken': '{{ csrf_token }}'}, success: function(data) { window.location.reload(); }}); }); }); and in my django views.py: @csrf_exempt def mydef(request): if request.method == 'POST': if request.is_ajax(): id_list=request.POST.getlist('id_list[]') for item in id_list: obj=models.users.objects.get(id=item) obj.Status='1' obj.save() return HttpResponse('done!') this function works correctly and changes to obj done! but in success function of ajax that should reload page not worked -
How to send email in post_save without asking user to wait in form submission?
Here is my post_save method: from asgiref.sync import sync_to_async @receiver(post_save, sender=SubmissionDetails) def create_submission_email(sender, instance, created, **kwargs): if created: data = sync_to_async(call_submssion_email(instance)) def call_manuscript_submssion_email(instance): print("Hi") message = '''Submitted with the title, <br> {0}'''.format(instance.title) subject = 'Article Submitted' to_address = 'example@gmail.com' from_address = "from@mail.example.com" msg = EmailMessage( subject, message,from_address,[to_address] ) msg.content_subtype = "html" msg.send() The problem is while submitting the form, the user has to wait till email is sent to see the results. I am using django 3.0 with some async support. -
Customized location choices in Django/JS/Paypal Buttons Integration
Below I have my Payal Checkout setup. User can input any address they want but I want to limit the country, State/Province, and City choices they have with a dropdown menu. Does anyone know how to do that? or any alternate options for this?