Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django LocaleMiddleware only works for LANGUAGE_CODE language
My goal is to have the following: www.example.com/en provides an English website www.example.com/de provides a German website I am using Django 3.1 for this. My settings.py contains the following: LANGUAGE_CODE = 'en' prefix_default_language=True TIME_ZONE = 'Europe/Berlin' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('en','English'), ('de', 'German') ] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'templates/locale'), ) MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ] My root urls.py contains the following: urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path('', include('mainpage.urls', namespace='mainpage')), ) If I visit www.example.com/en it works, if I visit www.example.com/de I get a 404 error. If I now change LANGUAGE_CODE = 'en' to LANGUAGE_CODE = 'de' www.example.com/de will work but www.example.com/en will give me a 404 error. How can I fix this, so that it works for both? I think it should not depend on LANGUAGE_CODE, should it? -
how to get the sum of a field after apply filter by django filter search?
would you please help me, I want to get the sum of a field after applying django filter search. for example I want to acheive the total of apartment's after filter View.py @login_required(login_url='loginPage') @allowed_users(allowed_roles=['admin']) def building(request): fltr_bld = FilterBuilding(request.GET, queryset=Building.objects.all()) apts=Building.objects.all().aggregate(Sum('total_apt')).get('total_apt__sum', 0) return render(request, 'building.html', {'fltr_bld': fltr_bld, 'apts':apts}) Filter.py class FilterBuilding(django_filters.FilterSet): start_date = DateFilter(field_name='date_created', lookup_expr='gte') end_date = DateFilter(field_name='date_created', lookup_expr='lte') name = CharFilter(field_name='name', lookup_expr='icontains') desc = CharFilter(field_name='desc', lookup_expr='icontains', label='Descriptions') class Meta: model = Building fields = ['name', 'total_apt', 'desc', 'end_date', 'start_date'] exclude = ['other_details'] -
Generic detail view View must be called with either an object pk or a slug in the URLconf
how to access foreign key in urls.py? ################models.py ... class Category(models.Model): title = models.CharField(verbose_name='TITLE', max_length=200) slug = models.SlugField('SLUG', unique=True, allow_unicode=True, help_text='one word for title alias.') ... def __str__(self): return self.title class Episode(models.Model): category = models.ForeignKey("Category", verbose_name=("CATEGORY"), on_delete=models.CASCADE) number = models.IntegerField(). ... meta: ... def __str__(self): ... def get_absolute_url(self): return reverse("manga:episode_detail", kwargs={"slug": self.category.slug, "number": self.number}) #####################urls.py ... # path('category/<slug:category.slug>/<int:number>', views.EpisodeDetailView.as_view(), name="episode_detail"), ] #################views.py ... class EpisodeDetailView(DetailView): model = Episode template_name = 'manga/episode_detail.html' context_object_name = 'episode' ** **It throwed `Generic detail view EpisodeDetailView must be called with either an object pk or a slug in the URLconf.`** I wanna see Detail of Episode. but I couldn't... I've tried throw queryset, but it doesn't work... how to access foreign key in urls.py? ** # def get_queryset(self): # return Episode.objects.filter(category__slug=self.kwargs['lab']) def get_queryset(self): employee = Category.objects.get(slug=self.kwargs['slug']) print(employee) return Episode.objects.get(category=employee, number=self.kwargs['number']) -
Adding files to form in Django makes editing form behave differently - why?
I have a simple model I can edit by using another simple form - and that works well, while clicking "edit" it correctly shows existing fields in an editing form; everything changes when I add files=request.FILES to my view - then it somehow forgets existing data and I'm left with clear form and info "This field is required" on required fields (even though they are filled because this item exists) views.py def add_news(request): if request.method == 'POST': news = NewsModel(author=request.user) form = AddNewsForm(instance=news, data=request.POST, files=request.FILES) #this works fine if form.is_valid(): form.save() messages.success(request, 'Added a news!') return redirect('main:news') else: messages.warning(request, "You didn't fill the form, try again") else: form = AddNewsForm() return render(request, 'news/add_news.html', {'form':form}) def edit_news(request, id): news = get_object_or_404(NewsModel, id=id) form = AddNewsForm(request.POST or None, instance=news, files=request.FILES) #here is the problem if request.POST and form.is_valid(): form.save() messages.success(request, 'Changed a news.') return render(request, 'news/add_news.html', {'form': form}) urls.py re_path(r'^news/new/$', views.add_news, {}, 'news_new'), re_path(r'^news/edit_(?P<id>\d+)/$', views.edit_news, {}, 'news_edit'), forms.py class AddNewsForm(forms.ModelForm): class Meta: model = NewsModel fields = '__all__' template <h1> Add/change a news</h1> <form method="POST" enctype="multipart/form-data"> {{form}} {% csrf_token %} <h2> <input type="submit" value="Go!"/> </h2> </form> Without that one files=request.FILES in edit_news, everything works. What's going on? -
Django formset factory and Crispy forms
I'm trying to apply formset helpers to my template and can't figure out where I'm wrong. I have implemented a function in javascript to dynamically add subjects. I am a beginner with formsets, any help would be great! Thanks !!! forms.py I create the form and the form helper : class NuovoSoggetoCsForm(ModelForm): class Meta: model = Soggetto fields = [ 'data_ora_creazione', 'tipologia_soggetto', 'cognome', 'nome', 'sesso', 'data_nascita', 'comune_nascita', 'provincia_nascita', 'stato_nascita', 'comune_residenza', 'localita_residenza', 'provincia_residenza', 'tipo_documento1', 'ente_riascio_doc1', 'numero_documento1', 'telefono1', 'mail_pec', 'foto_documento1' ] class SoggettoFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.layout = Layout( 'data_ora_creazione', 'tipologia_soggetto', 'cognome', 'nome', 'sesso', 'data_nascita', 'comune_nascita', 'provincia_nascita', 'stato_nascita', 'comune_residenza', 'localita_residenza', 'provincia_residenza', 'tipo_documento1', 'ente_riascio_doc1', 'numero_documento1', 'telefono1', 'mail_pec', 'foto_documento1', ) self.render_required_fields = True views.py I create the formset and helper in the view : .....some code..... SoggettoFormset = formset_factory(NuovoSoggetoCsForm, extra=0, can_delete=True) helper = SoggettoFormSetHelper() .....some code..... return render(request, 'soggetto.html', {'formset_soggetto' : formset_soggetto, 'helper' : helper }) soggetto.html I create the template with dynamic addition : ....some code..... <fieldset> {{ formset_soggetto.management_form }} <div id="formset_wrapper_soggetto" style="background-color:#f2f2f2;"> {% for form_soggetto in formset_soggetto.forms %} <div class='table'> <table class='no_error'> {% crispy form_soggetto.as_table helper %} </table> </div> {% endfor %} </div> <div id="emptyform_wrapper_soggetto" style="display: none"> <legend>Soggetto</legend> <div class='table'> <table class='no_error'> {{ formset_soggetto.empty_form.as_table }} </table> </div> </div> </fieldset> … -
I want to limit file size upload below 5 mb before uploading
I am trying to check file size upload in jinja2 template in django. I want to check it before it gets uploaded, the code below is a form which will be submitted after clicking the button. It will upload a dataset in browser. <form method="POST" class="post-form" enctype="multipart/form-data"> {{ form.as_p }} <button onclick="onSubmitBtn()" type="submit" id="btn-hide" class="btn btn-danger">Upload</button> </form> -
PyInstaller with django and django-extensions
I'm trying to build executable with django using PyInstaller and used django-extensions library to use 'runserver_plus'. Using, django==1.11 PyInstaller==3.4 django-extensions==2.2.1 Added in settings.py file, INSTALLED_APPS = ( ... 'django_extensions', ) In PyInstaller loader file for django, PyInstaller\loader\rthooks\pyi_rth_django.py import django.core.management import django.utils.autoreload def _get_commands(): # Django groupss commands by app. # This returns static dict() as it is for django 1.8 and the default project. commands = { 'changepassword': 'django.contrib.auth', 'check': 'django.core', 'clearsessions': 'django.contrib.sessions', 'collectstatic': 'django.contrib.staticfiles', 'compilemessages': 'django.core', 'createcachetable': 'django.core', 'createsuperuser': 'django.contrib.auth', 'dbshell': 'django.core', 'diffsettings': 'django.core', 'dumpdata': 'django.core', 'findstatic': 'django.contrib.staticfiles', 'flush': 'django.core', 'inspectdb': 'django.core', 'loaddata': 'django.core', 'makemessages': 'django.core', 'makemigrations': 'django.core', 'migrate': 'django.core', 'runfcgi': 'django.core', 'runserver': 'django.core', 'runserver_plus':'django_extensions', 'shell': 'django.core', 'showmigrations': 'django.core', 'sql': 'django.core', 'sqlall': 'django.core', 'sqlclear': 'django.core', 'sqlcustom': 'django.core', 'sqldropindexes': 'django.core', 'sqlflush': 'django.core', 'sqlindexes': 'django.core', 'sqlmigrate': 'django.core', 'sqlsequencereset': 'django.core', 'squashmigrations': 'django.core', 'startapp': 'django.core', 'startproject': 'django.core', 'syncdb': 'django.core', 'test': 'django.core', 'testserver': 'django.core', 'validate': 'django.core' } return commands After creating executable for django project. Where as, 'runserver' works smoothly. Not able to use 'runserver_plus' command after building executable with PyInstaller. ubuntu@ubuntu:~/executables$ ./dist/myproject/myproject runserver_plus * Running on http://127.0.0.1:8000/ (Press CTRL+C to quit) * Restarting with stat Unknown command: '/home/ubuntu/executables/dist/myproject/myproject' Type 'myproject help' for usage. ubuntu@ubuntu:~/executables$ After executing, ubuntu@ubuntu:~/executables$ ./dist/myproject/myproject help Type 'myproject help <subcommand>' … -
How to validate form by getting exact value on integer field
I am new in Django, I am trying to validate a form to get the particular value, if value is not exact validate error. For example, i have a field in a model (cot_code), the field has a integer value (12345). I have created a form for this field, i want if the user enter 12345 in form, the form will be valid as success "code is correct", but when user enter a wrong code (55777) the form will raise a validator error "Wrong code". I do not know how to go on with the views. Model: class CotCode(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) cot_code = models.IntegerField(default='0', blank=True) # I have set this field as 12345 in model. date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'CotCode' verbose_name_plural = 'CotCode' ordering = ['-date'] def __str__(self): return self.user.username Forms: class CotCodeForm(forms.ModelForm): class Meta: model = CotCode fields = ('cot_code',) Views: @login_required def TransferCOTView(request): #Don't know how to go on here return render(request, 'transfer_cotcode.html') Template: <form method="POST" action="" class="text-center needs-validation" novalidate> {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroup-sizing-default">C.O.T</span> </div> <input type="text" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-default" placeholder="Enter your COT Code" required> <div class="invalid-feedback"> Please enter your C.O.T code. </div> </div> … -
Why is gettext giving me automatically incorrect translations?
I am using gettext translations for my Django project and I keep adding to the .po file new and new translations by makemessages and compilemessages. What is happening now is that when I make messages then I check the .po file and there many of the strings have been automatically translated, although this is 100% unique string. example: Now generated: #: .\agregator\models.py:1855 #, fuzzy #| msgid "Distribution order" msgid "Distribution Product Parameters" msgstr "Objednávka u distribuce" it automatically translated according to the msgid "Distribution order" that is not any close to the actual string neither there is any link to this msgid. Can anyone explain to me what is happening in the background and how can I remove all such links so for msgstr I get only empty strings, (unless the strings are 100% similar)? Thank you in advance. -
How to keep Database entries on Server after git pull working with Django?
Everytime i pull the new Version of my Django app on my Server it doesnt keep the entries that i made. It only keeps the entries i made on my local Version. So all entries i did on my server are lost. Is there a way to keep the entries. I work with postgressql. So i tried to google the problem, but i couldnt find any solution to my problem. I work with digitalocean and ubuntu on the server. I dont think that it does matter but i want to give as much information as possible. Can i save the database or do i need to do anything completely different. I hope that you can help me figure this out. -
How can I go from my javascript to views.py of another app from present app
My javascript: xhttp.open('POST', 'avgsize/avgpython' ,true); xhttp.setRequestHeader("content-type","application/json"); xhttp.send(JSON.stringify(dates)); xhttp.onreadystatechange=function(){ if(this.readyState==4 && this.status==200){ alert(this.responseText); } } My present Home app(all urls am visiting are working from this app ) urls.py: urlpatterns = [ path('' , views.HomeBase , name="HomeBase"), path('Home' , views.Home , name="Home"), path('astroids' , include('Astroids.urls')), path('nearest' , include('Nearest.urls')), path('fastest' , include('Fastest.urls')), path('avgsize/' , include('Avgsize.urls')), ] My Avgsize app urls(i want to come here from Home app): path('avgpython' , views.avgpython , name="averagesizePython"), what changes should i make in the code so that i can go from javascript to Avgsize app and link avgpython and get access to views.avgpython. Please Help...!! -
Django prepends url name to imagefield location, causing 404
Everything was working fine and images were loading. from model: image = models.ImageField(upload_to='static/images/bin_sheet/', default='static/images/bin_sheet/no-img.jpg') from urls.py path('bin_sheet/', views.IndexView.as_view(), name='bin_sheet'), from views.py: class IndexView(generic.ListView): template_name = 'bin_sheet.html' context_object_name = 'bin_list' from template: <img class="card-img-top" src="{{ bin.image }}" alt="no image"> from html souce in rendered html: <img class="card-img-top" src="static/images/bin_sheet/sb_HAm6pem.jpg" alt="no image"> from django terminal output: Not Found: /bin_sheet/static/images/bin_sheet/sb_HAm6pem.jpg "GET /bin_sheet/static/images/bin_sheet/sb_HAm6pem.jpg HTTP/1.1" 404 3324 It's adding /bin_sheet/ now. If I enter in that address minus the bin sheet then it loads the image. wtf would cause django to add bin_sheet? The page has the correct location but django tries to load if from a non existent location. -
How to Get the exact address location like google map tracker with python/django
I've tried to get the location by ip address..but result is wrong.. import requests res = requests.get("https://ipinfo.io/") data = res.json() print(data) I want to know location like this: Food panda Location Tracker Google location Tracker -
Why am I getting a 404 error while testing a django listview?
I have a ListView of movies. For viewing this list the user has to be authenticated. I create a user in the testing runtime with self.user = User.objects.create_user(username='fake_user', email='user@fakeemail.com', first_name='fake', last_name='user') self.user.set_password('password') self.user.save() and then when I run this test self.client.login(username='fake_user', password='password') response = self.client.get(reverse('movie-list')) self.assertEqual(response.status_code, 200) I always get a 404 response, even though I have no problem when accessing this URL from the browser. What am I missing here? -
how can I use LoginView in my own view and show in HTML templates?
I want to use ready Django LoginView, but in the same time I have to use my own view for registration in same HTML template. If in urls.py file I will connect 2 views than i will connect only first. So my question is that how can use LoginView in my own view and use 2 forms with jinja? here is my views.py file and html ;) def index(request): if request.method == 'POST': form = UserRegisterForm(request.POST) formlog = auth_views.LoginView.as_view(template_name='main/index.html') if 'signup' in request.POST: if form.is_valid(): form.supervalid() form.save() username = form.cleaned_data.get('username') messages.success(request, f'Dear {username} you have been created a new accound!') return redirect('main') elif 'login' in request.POST: if formlog.is_valid(): formlog.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('main') else: form = UserRegisterForm() formlog = auth_views.LoginView.as_view(template_name='main/index.html') return render(request, 'main/index.html', {'form': form, 'formlog': formlog}) # this code is not working , but not returning any errors HTML {% if not user.is_authenticated %} <!-- Login --> <div class="container"> <div class="log-1"> <div class="log-0"> <p class="logtitle">BareTalk</p> <form method="POST" name="login"> {% csrf_token %} {{ formlog|crispy }} <button class="log-button first" type="submit">Login</button> </form> <button class="log-button second" onclick="modalwindowops.open();" id="signup">Sign Up</button> </div> </div> </div> <!-- Signup --> <div class="modal-overlay"> <div class="modal-window"> … -
Users can't pay each other django-paypal
I have an online store where users can pay each other to buy things, I have been testing it with sandbox accounts but I don't think it's working. I really can't get where the issue is Here is my views.py: def payment_process(request, trade_id): trade = get_object_or_404(Trade, id=trade_id) host = request.get_host() paypal_dict = { 'business': trade.seller.email, 'amount': Decimal(trade.price), 'item_name': trade.filename, 'invoice': str(trade.id), 'currency_code': 'USD', 'notify_url': 'https://{}{}'.format(host, reverse('paypal-ipn')), 'return_url': 'https://{}{}/{}'.format(host, *reverse('payment_done', kwargs={'trade_id': trade.id})), 'cancel_return': 'https://{}{}'.format(host, reverse('home')), } form = PayPalPaymentsForm(initial=paypal_dict) return render(request, 'payment/payment_process.html', {'trade': trade, 'form': form}) @csrf_exempt def payment_done(request, trade_id): # Do some very important stuff after paying ... # It would be really nice if someone can help me with a checker messages.success(request, 'Your product is in your inbox now') return redirect('trade:inbox') My urls.py: urlpatterns = [ path('admin/', admin.site.urls), ... # Prodbox Payment path('payment/process/<int:trade_id>/', payment_views.payment_process, name="payment_process"), path('payment/done/<int:trade_id>/', payment_views.payment_done, name="payment_done"), # Prodbox packages path('paypal/', include('paypal.standard.ipn.urls')), ] The template which handles paying: {% extends 'users/base.html' %} {% block title %}Payment Process | Prodbox {% endblock title %} {% block content %} <div class="container row justify-content-center"> <div class="shadow-lg p-3 mb-5 col-md-8 bg-white rounded m-4 p-4"> <section> <p>Seller: {{ trade.seller.email }}</p> <p>Product: {{ trade.thing }}</p> <p style="color: #2ecc71;">Price: ${{ trade.price }}</p> </section> <section> <h4>Pay … -
In Python 3.7 ,Django3.1.1 ,Apache/2.4.46 (cPanel) getting ther error : AttributeError: 'module' object has no attribute 'lru_cache'
I am new to deploying the Django project on cpanel. My cpanel was on python 2.7 but my project need python3.7 so I have installed a separate version of python 3.7 on cpanel by following this tutorial https://sysally.com/blog/install-python-3-x-whm-cpanel-server/ .After successfully installing python 3.7 I followed this tutorial to server my project on cpanel https://docs.cpanel.net/knowledge-base/web-services/how-to-install-a-python-wsgi-application/ Firstly I was getting this error "ImportError: No module named django.core.wsgi" which i have solved by adding my virtual environment path to wsgi.py file , now my project wsgi.py file looks like this import os, sys # add the virtualenv site-packages path to the sys.path sys.path.append('/home/***/public_html/app/unltdenv/lib/python3.7/site-packages') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'unltdsample.settings') application = get_wsgi_application() Now I am getting this error Traceback (most recent call last): File "/opt/cpanel/ea-ruby24/root/usr/share/passenger/helper-scripts/wsgi-loader.py", line 369, in <module> app_module = load_app() File "/opt/cpanel/ea-ruby24/root/usr/share/passenger/helper-scripts/wsgi-loader.py", line 76, in load_app return imp.load_source('passenger_wsgi', startup_file) File "/home/umadmin/public_html/app/unltd/passenger_wsgi.py", line 1, in <module> from unltdsample.wsgi import application File "/home/umadmin/public_html/app/unltd/unltdsample/wsgi.py", line 19, in <module> from django.core.wsgi import get_wsgi_application File "/home/umadmin/public_html/app/unltdenv/lib/python3.7/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/home/umadmin/public_html/app/unltdenv/lib/python3.7/site-packages/django/utils/version.py", line 71, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' i have searched about it, what i found is that the problem is of wsgi python version mismatch. … -
Django get correct userprofile for user.id
I am using DRF to create an api where to get userprofile according to the user.id from url like path('<id>/profile', UserProfileView.as_view(), name='profile') The view Looks like class UserProfileView(RetrieveAPIView): queryset = models.Profile.objects.order_by("-id") serializer_class = serializers.UserProfileSerializer lookup_field = 'id' permission_classes = (permissions.AllowAny, ) #serializers.py class UserProfileSerializer(serializers.ModelSerializer): name = serializers.CharField(source='user.name', read_only=True) email = serializers.CharField(source='user.email', read_only=True) class Meta: model = models.Profile fields = '__all__' extra_kwargs = {'password': {'write_only': True}} lookup_field = 'id' def create(self, validated_data): user = models.Profile( email=validated_data['email'], name=validated_data['name'] ) user.set_password(validated_data['password']) user.save() return user #models.py class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) bio = models.TextField(default='', max_length=800, blank=True) The api return an userprofile object as { id: 4, name: "kehoji", email: "kehoji2061@vmgmails.com", bio: "", user: 3} But for same logged in user returns { name: "kehoji", id: 3, email: "kehoji2061@vmgmails.com" } so, when I try to fetch userprofile by user.id it return other profile. How I can I solve this. This mismatch happend because I deleted the user of id=2. -
. Package install error: Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE] Error launching application on MSEmulator. Exited
Launching lib\main.dart on MSEmulator in debug mode... ✓ Built build\app\outputs\flutter-apk\app-debug.apk. Installing build\app\outputs\flutter-apk\app.apk.. -
How do I create a new user model in Django named student without modifying the already existing base user?
So in my academic management system when I want to modify the model student with fields like class and division but the base admin used that I create with create super user should remain the same . How to achieve this in Django ? -
Index out of range & name 'messages' is not defined
I am trying to import .csv file to database and getting index out of range.(List range) My file fields are as shown below. I have tried by changing delimiter value but no luck.My view.py file is views.py def contact_upload(request): prompt = { 'order': 'Order of the CSV file should be releasedate,moviename,hero,heroine,rating' } if request.method == "GET": return render(request, 'testapp/upload.html') csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, "This is not a CSV file") data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=' ', quotechar="|"): # print(column) _, created = Movie.objects.update_or_create( releasedate=column[0], moviename=column[1], hero=column[2], heroine=column[3], rating=column[4] ) context = {} return render(request, 'testapp/upload.html', context) upload.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {%if messages %} {% for message in messages %} <div> <strong>{{message|safe}}</strong> </div> {% endfor %} {% else %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <label>Upload a File:</label> <input type="file" name="file"> <p>Only accept CSV File.</p> <button type="submit">Upload</button> </form> {% endif %} </body> </html> Problem2: #I am using ImportExportModelAdmin for importing and exporting data but here id value is get added by django and based on this only changes are happening.I want to change id field and wanted to make hero field to be considered for … -
winapi.WaitForSingleObject takes a long time to execute while django is performing system checks
I'm running Django 3.0.8 and windows 10. I've got a development server running on my local machine that usually "performs system checks" then starts up nice and promptly ( after a few seconds). At this time the winapi.WaitForSingleObject process takes in the order of 1000ms to execute. At times winapi.WaitForSingleObject will take up to 60,000ms (!!) to execute (I think it's timing out, but I'm not sure). I can't find any pattern to these slow starts. I don't know what the 'SingleObject' is that's causing the delay. What steps can I take to prevent winapi.WaitForSingleObject from taking so long to execute? -
Views in the Django model
I'm a beginner in Django and I need your help. Please tell me how I can make it so that when you go to the page with the article, in my model views = models.IntegerField(default=0, verbose_name='Views') were views read and added to the database? models.py class News(models.Model): title = models.CharField(max_length=150, verbose_name='Наименование') content = models.TextField(blank=True, verbose_name='Контент') created_ad = models.DateTimeField(auto_now_add=True, verbose_name='Дата публикации') updated_at = models.DateTimeField(auto_now=True, verbose_name='Обновлено') photo = models.ImageField(upload_to='photos/%Y/%m/%d/', verbose_name='Картинка', blank=True) is_published = models.BooleanField(default=True, verbose_name='Опубликовано') category = models.ForeignKey('Category', verbose_name='Категория', on_delete=models.PROTECT) # on_delete=models.PROTECT - защита от удаления статей привязанных к категории. views = models.IntegerField(default=0, verbose_name='Просмотры') def get_absolute_url(self): return reverse('view_news', kwargs={"pk": self.pk}) # Строковое представление объекта def __str__(self): return self.title -
Supporting multiple requests - django API backend
I'm currently building a backend API for a chat app with Django and DRF. It basically handles direct interaction with a MySQL database and also manages other important components like authentication, authorization, and user management. Our team has built an API microservice for enabling chat on our client mobile app. We're doing this through websockets and rabbitMQ on node.js. So we've put this up online and are realizing that the Django backend doesn't seem to support the vast requests being sent from the chat API. Running a load test on the Django app shows that it's dropping up to 90% or requests. Adding more servers connected to a load balancer has not improved the situation either. I suppose this is being bottlenecked by the blocking nature of Django (actually DRF in particular). But it's just my hunch and I'm not really sure as to what the problem really is. Does anyone have advice on how to improve performance for the Django API. -
Django FileField/ImageField validation when the file upload is being done from the client side
When ever client wants to upload a file it first request the Django server for a pre-signed URL the server then generates a pre-signed URL and sends it back to the client. The client can use this URL to upload to file directly to S3. Once the upload is successful the client sends the file key back to the server (the file key is also present in the response given by the server along with the URL). Now I'm confused as to how to pass the FileField validation given that I only have the file key with me and not the actual file. For example: class Company(models.Model): name = models.CharField(max_length=100) logo = models.ImageField(null=True) def __str__(self): return f'name:{self.name}' class CompanySerializer(serializers.ModelSerializer): CLIENT_COMPANY_LOGO_KEY = 'logo' def to_internal_value(self, data): # Replace file/image keys with file/image instances so that they can pass validation. if data.get(self.CLIENT_COMPANY_LOGO_KEY): try: data[self.CLIENT_COMPANY_LOGO_KEY] = default_storage.open(data[self.CLIENT_COMPANY_LOGO_KEY]) except (TypeError, OSError, ParamValidationError): pass return super().to_internal_value(data) def process_logo(self, validated_data): logo = validated_data.get(self.CLIENT_COMPANY_LOGO_KEY) if logo: # Replace file/image instances with keys. validated_data[self.CLIENT_COMPANY_LOGO_KEY] = logo.name return validated_data def create(self, validated_data): validated_data = self.process_logo(validated_data) company = super().create(validated_data) return company Within the serializer I'm first replacing the file key with the actual file using the default_storage which is hooked …