Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamic subdomains and url paths in django project
I am trying to implement a dynamic subdomain and urls system in my django project. Generally, each user has its domain, eg. myusername.example.com User may define dynamic URLs, for example: myusername.example.com/something1 myusername.example.com/something2 myusername2.example.com/something1 myusername2.example.com/something2 But I have also my website running on example.com, with urls like example.com/contact, example.com/about-us and so on. I want to all of these URLs to point to my custom view (class based) where I do some DB queries and return dynamic content. this somethin1/something2 part is fully dynamic, and there may be anything . defined by user. I've got something like this: urls.py from web.views import HomeView, ContactView urlpatterns = [ path('admin/', admin.site.urls), path('contact', ContactView.as_view()), path('', HomeView.as_view()), re_path('.*', HomeView.as_view()) ] web.views.py class HomeView(TemplateView): template_name = 'home.html' def dispatch(self, request, *args, **kwargs): SERVICE_DOMAIN = settings.DOMAIN http_host = str(request.META.get('HTTP_HOST')) if SERVICE_DOMAIN in http_host: subdomains = http_host.split(SERVICE_DOMAIN)[0] subdomain = slugify.slugify(subdomains) else: subdomain = False if subdomain: print('Our subdomain is {}'.format(subdomain)) kwargs['subdomain'] = subdomain return CustomUrlView.as_view()(self.request, *args, **kwargs) if not subdomain: print('run normally') return super().dispatch(request, *args, **kwargs) class CustomUrlView(View): def dispatch(self, request, *args, **kwargs): subdomain = kwargs.get('subdomain') url = request.META.get('PATH_INFO').lower().strip().replace('/', '', 1) # here I do some queries in DB with my url variable - it has own model etc. … -
django no reverse match form action don't work
11 and python 2.7, and i have a error while rendering a view. Is when load the html in action form url don't work, i don't know why. Any suggestions? The url: url(r'^admin/user_list/(?P<user_id>\d+)/edit/$', views.admin_zone_edit_user, name='edit_users'), The html: {% extends 'admin/baseadmin.html' %} {% load staticfiles %} {% block content %} {% csrf_token %} <div ><form id="login" action="{% url 'admin_zone_edit_user' %}" method ="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Save"></input> </form></div> {% endblock %} And the error, no reverse match. NoReverseMatch at /admin/user_list/3/edit/ Reverse for 'admin_zone_edit_user' not found. 'admin_zone_edit_user' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/admin/user_list/3/edit/ Django Version: 1.11.11 Exception Type: NoReverseMatch Exception Value: Reverse for 'admin_zone_edit_user' not found. 'admin_zone_edit_user' is not a valid view function or pattern name. Exception Location: /usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py in _reverse_with_prefix, line 497 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/rokanas/rummi', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/rokanas/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client'] Server time: Mon, 9 Apr 2018 18:52:37 +0000 Error during template rendering -
Django annotate() on two step relationship confusion
I have the following 3 models: Category: date_start date_end active: bool Player: name: str age: int category = models.ForeignKey(Category) PlayerContact: contact_result: int player = models.ForeignKey(Player) In this case I have: 2 Categories 10 Players per Category 1 to 3 Players in each Category with a contact_result = 3 How do I annotate a Category queryset to get the amount of players with a contact_result=3? I've tried this: Categories.objects.annotate(Count('player', filter=Q(player__playercontact__contact_result=3))) # returns all players for each Category Categories.objects.annotate(Count('player__playercontact__contact_result')) # returns players with a contact_result but it's not filtered -
In Django admin to truncate the number of characters for an field
I want in Django admin to truncate the number of characters for a field. For example, for: list_display = ('description') I want to show only the first 20 characters. -
How to use Django with an existing database in MySQL?
I have an application in Django 2.0 and as a database engine I use MySQL. I have a problem because the database was previously created and already has records, my idea is to use this same database for the application I am creating. Use the command python manage.py inspectdb > models.py To create the models.py file which will be cleaned as indicated by the models.py file that was generated. #This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey has `on_delete` set to the desired behavior. # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. After this I proceed to execute: python manage.py migrate python manage.py makemigrations python manage.py migrate But it generates the following error: (1050, "Table 'XXXXXXX' already exists") Obviously it tells me that the table already exists, but how do I not generate this error and continue administering the tables … -
How to write a commenting system with Django only for authenticated users
For educational purposes I don't want to use ready packages, What I want to do is, allowing authenticated users to comment under a "post". My problem is that, Django only allow a user to write only one comment not anymore, otherwise an error will be raised, Here is the error: File "<console>", line 1, in <module> File "/Users/Guest2/Desktop/Untitled/venv/lib/python3.6/site-packages/django/db/models/base.py", line 729, in save force_update=force_update, update_fields=update_fields) File "/Users/Guest2/Desktop/Untitled/venv/lib/python3.6/site-packages/django/db/models/base.py", line 759, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/Users/Guest2/Desktop/Untitled/venv/lib/python3.6/site-packages/django/db/models/base.py", line 842, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/Users/Guest2/Desktop/Untitled/venv/lib/python3.6/site-packages/django/db/models/base.py", line 880, in _do_insert using=using, raw=raw) File "/Users/Guest2/Desktop/Untitled/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/Guest2/Desktop/Untitled/venv/lib/python3.6/site-packages/django/db/models/query.py", line 1125, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/Users/Guest2/Desktop/Untitled/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1284, in execute_sql cursor.execute(sql, params) File "/Users/Guest2/Desktop/Untitled/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/Users/Guest2/Desktop/Untitled/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/Users/Guest2/Desktop/Untitled/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/Users/Guest2/Desktop/Untitled/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/Users/Guest2/Desktop/Untitled/venv/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/Users/Guest2/Desktop/Untitled/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/Users/Guest2/Desktop/Untitled/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: debate_comment.creator_id here … -
How to create a refine or advance search with individual fields in Django
I have made a search field in the navbar, Currently the search finds posts by title, username, first_name, last_name. A search with "title" could have 100 results and so on. I now want to create a refined search page. In that page there will be 4 separate search fields, Example: Search Posts by Title: __Search box_____ Search Posts by username __Search box____ Search Posts by first_name __Search box____ Search Posts by last_name __Search box____ <form class="navbar-form navbar-left" action="{% url 'posts:all' %}"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search" name="q"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> This is how the views look . class Postlist(SelectRelatedMixin, ListView): model = Post select_related = ('user', 'group') def get_queryset(self): queryset = super(Postlist, self).get_queryset() query = self.request.GET.get('q') if query: queryset = queryset.filter( Q(title__icontains=query)| Q(user__username__iexact=query)| Q(user__first_name__iexact=query)| Q(user__last_name__iexact=query) ) return queryset I am sorry if the question is too basic I am a beginner with django. How do I go about doing this. Will there be 4 forms with different names. example instead of name="q", Will I have name="a", name="b", name="c", etc. Also how will the views look -
django simple custom queue without 3rd party software
first time posting here so my apologies if something is incorrect. I am trying to build a simple queue system using Python's inbuilt Queue class in a Django application. Python Queue Documentation https://docs.python.org/3/library/queue.html I think I know how to construct and initialize a queue on site startup so there is only one queue I add jobs to based on this post Execute code when Django starts ONCE only? However, my problem and question is after constructing a queue on Django site startup how would I grab that queue from my various Django apps in order to add jobs to it in the Views files? I don't see a way to get the constructed queue. I could construct a queue at the time I want to add a job but then I would run into the issue where each job added would construct its own queue which is not the functionality I want. so far I have a a queue_construction.py file in the base dir of my django site with some test functions in it and that is working great when I execute it on command line. Now I need to get it working in the Django environment. I do not … -
Select from deep association in Django
I have few models like Course, Chapter, QuestionType, ChapterQuestion, CourseLearn and CourseLearnResponse class Course(models.Model): name = models.CharField(max_length=250) class Chapter(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) name = models.CharField(max_length=250, blank=False) class QuestionType(models.Model): title = models.CharField(max_length=250, blank=True, default=None) slug = models.CharField(max_length=250, blank=True, default=None) class ChapterQuestion(models.Model): chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE) word = models.CharField(max_length=250) definition = models.CharField(max_length=250) class CourseLearn(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) start_date = models.DateTimeField(auto_now=True) class CourseLearnResponse(models.Model): course_learn = models.ForeignKey(CourseLearn, on_delete=models.CASCADE) chapter_question = models.ForeignKey(ChapterQuestion, on_delete=models.CASCADE) question_type = models.ForeignKey(QuestionType, on_delete=models.CASCADE) response = models.CharField(max_length=250) correct = models.BooleanField(default=False) score = models.IntegerField(default=0) One Question is displayed at a time using ajax. I'm wiriting CourseLearnManager to retrieve next question class CourseLearnQuerySet(models.query.QuerySet): pass class CourseLearnManager(models.Manager): def get_queryset(self): return CourseLearnQuerySet(self.model, self._db) def get_next_question(self, course_learn): // currently retrieving first question from ChapterQuestion question = ChapterQuestion.objects.first() return question in view class LearnQuestion(TemplateView): template_name = 'learn/learn_question.html' def post(self, request, *args, **kwargs): context = super(LearnQuestion, self).get_context_data(**kwargs) form = CourseLearnResponseForm(request.POST) if request.POST['response'] is not None: if form.is_valid(): context['question'] = CourseLearn.objects.get_next_question(request.POST['course_learn']) return context else: context['question'] = CourseLearn.objects.get_next_question(request.POST['course_learn']) return context What I want is to get question from ChapterQuestion and QuestionType whose entry in not in the CourseLearnResponse for the specified course_learn inside the CourseLearnManager. I'm new to Django and could not found what to … -
Firebase + Phonegap plugin push: How to send silent messages but update app?
My current stack is: Django using FCM to send push notifications to an Ionic app. The app uses the phonegap-plugin-push. I have the problem, that the on notification handler doesn't get called. Here is the data that I'm sending: 'message': { 'token': '<my-device-token>', 'data': { 'yup': 'okay' }, 'apns': { 'payload': { 'aps': { 'data': 'here is my data', 'badge': 1, 'content-available': 1 }, 'notId': 2 } } } The app gets the data, but somehow the on notificatoin handler doesn't get called. Also here is my code in the app: import { Injectable } from '@angular/core'; import { Push, PushObject, PushOptions } from '@ionic-native/push'; import { AlertController, Platform } from 'ionic-angular'; import { FcmDataProvider } from './fcm.data'; @Injectable() export class FcmProvider { /* * FIREBASE CLOUD MESSAGING */ constructor(private push: Push, private alertCtrl: AlertController, private platform: Platform, private fcmDataProv: FcmDataProvider) { } getPermission(): Promise<{isEnabled: boolean}> { // Listen for res.isEnabled. return this.push.hasPermission(); } initPush() { console.log("Init push!"); const options: PushOptions = this.initPushOptions(); const pushObject: PushObject = this.push.init(options); pushObject.on('notification').subscribe((notification: any) => { console.log('Received a notification', notification); if(this.platform.is('ios')) { this.handleIOSNotification(notification, pushObject); } else if(this.platform.is('android')) { this.handleAndroidNotification(notification); } this.presentSuccessAlert(notification.message); }); pushObject.on('registration').subscribe( (registration: any) => { console.log('Device registered', registration); // TODO: Send registration.registrationId … -
bind csv file with django model while showing as output within html
I have a django model and csv file separately. What I want to do is that user upload a csv file with a single colomn ('fp_Item').If colomn line exists in the django model as per below (queryset_list.filter( Q(fp_Item__contains=query))) I want to retrieve the necessary fields from the database and show within html if does not exists it shouldn't retrieve anything and leave empty but still should have to print the csv file line. def check_fp(request): if not request.user.is_active: return render(request, 'login.html') else: if request.method == 'POST' and request.FILES['csv_file2']: myfile = request.FILES['csv_file2'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) data = csv.reader(fs.open(filename, mode='r')) queryset_list = fp.objects.all() lines=[] for row in data: if row[0] != 'fp_Item': line = row[0] lines.append(line) query= line if query: queryset_list.filter( Q(fp_Item__contains=query)) queryset_list= fp.objects.all() context = {'lines': lines, 'instances': queryset_list, } return render(request, 'check_fp.html', context) context = {'lines': lines, 'instances': queryset_list, } return render(request, 'check_fp.html', context) return render(request, 'check_fp.html', {}) lines.append(line) is working and writing csv column to html file but I couldn't somehow bind the django model and the csv column together. Isn't "if query" method usable for this scenario ? Here is my html file: I want to match line at retrieve description and detail,timestamp and … -
Django date comparison throws exception
I'm generating a date in this way, profile.key_expires = datetime.now() + datetime.timedelta(days=2) if profile.key_expires > datetime.now() This throws an exception, what am I doing wrong here? -
How to return a 404 when drf returns empty queryset using ListAPIView
class listapiview(ListAPIView): queryset = testobj.objects.all() serializer_class = testobjSerializer def get_queryset(self): queryset = testobj.objects.all() build_id = self.request.query_params.get('id', None) if id is not None: queryset = queryset.filter(id=id) return queryset I just rewrote some views from APIView to ListAPIView and it broke some of my unittests because an empty queryset still returns a 200. I would like to figure out the best way to return a 404 (or whatever the appropriate error code would be in this) using my example. I tried adding: if queryset: return queryset else: return Response(status=status.HTTP_404_NOT_FOUND) But received a paginator error: TypeError: object of type 'Response' has no len() -
Django form using bootstrap
I have the following dictionary: POSSIBLE_POSITIONS = ( ('1', 'Brazo'), ('2', 'Muñeca'), ('3', 'Pierna'), ('4', 'Pie'), ) This is used in the following form: from interface.positions import * from django import forms class PositionForm(forms.Form): position = forms.ChoiceField(choices = POSSIBLE_POSITIONS, label="", initial=1, widget=forms.Select()) This is the view that renders my html template: def add(request): return render(request, 'interface/add_user.html', {'device_list': Device.objects.all(), 'form': PositionForm()}) And this is the html code: <body> <form class="square" action="{% url 'interface:add_perform' %}" method="post"> {% csrf_token %} <div class="form-group"> <label>ID paciente</label> <input autofocus class="form-control" name="user_id" placeholder="Ejemplo: 58192"> </div> <div class="form-group"> <label>Dispositivo a usar</label> <select name="device_id" class="form-control"> {% for device in device_list %} <option>{{ device.id }}</option> {% endfor %} <option selected="selected"> Sin dispositivo </option> </select> </div> <div class="form-group"> <label>Posición dispositivo</label> <div class=form-control> {{ form }} </div> </div> <div class="form-group square_button"> <button class="btn btn-success btn-md form-control" type="submit"> Crear Paciente </button> </div> </form> </body> The problem is that as you can see on the following image, this isn't bootstrap css, so it is really weird. How I can fix that? I want it like the 'Dispositivo a usar' selector. -
Django: Debug = False
I've just deployed my django project on live server. Problem is that whenever I turns Debug = False all the images stops showing up! Here's the main urls.py file, urlpatterns = [ . . . # URLS! ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The settings.py file, Debug = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') So, if I turns Debug = True here images starts showing up but not with Debug = False. How can we fix this problem? Thank You! -
Gunicorn blocking logging for django app using docker-compose
my django app has a pretty simple logging set up DEBUG = True LOGGING_DIR = os.path.join(BASE_DIR, 'logs') LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(LOGGING_DIR, 'django2.log'), 'formatter': 'verbose' }, 'SysLog': { 'level': 'DEBUG', 'class': 'logging.handlers.SysLogHandler', 'formatter': 'verbose', 'address': ('logsXX.papertrailapp.com', XXXXX) }, }, 'loggers': { '': { 'handlers': ['console', 'file', 'SysLog'], 'propagate': True, 'level': 'DEBUG', }, 'django.server': { 'handlers': ['console', 'file', 'SysLog'], 'propagate': True, 'level': 'DEBUG', }, 'django.template': { 'handlers': ['console', 'file', 'SysLog'], 'propagate': True, 'level': 'DEBUG', }, }, } When I run python3 manage.py runserver --settings=my_app.local I can see the logging work in console, in my file and is pushed to papertrail. However, when I use docker-compose to run the app I'm only seeing output to console for explicitly logged errors like logger.info('some_error') but not for requests, nothing is writing to the file I have and nothing is being sent to papertrail. My docker compose file looks like this: # docker-compose.test.yaml version: '3' services: webapp: image: local-build:latest command: ["gunicorn", "my_app.wsgi", "-b", "0.0.0.0:8000", '-t', '500'] env_file: … -
Is there a way to import processing.py or processing.js as Python module for Django web development?
I am trying to develop interactive web content using processing on Python Django. But I can't locate any material showing how to import processing.py or processing.js as a python module for Django development. -
add user to active directory group sometimes does not working
i am using in django the function call imported from subprocess to run powershell script. this script receiving an username as argument and adding it to active directory group. there is something weird, no errors, and it's not working. but if i run it manually it sometimes working and sometimes not working. im really confused and need your help. python line running the PS script: call(["powershell", "{0} {1}".format(powershell_script_path, username)]) returns no error. and the powershell script: $username=$args[0] Add-ADGroupMember -Identity "some_group" -Members $username thanks for your help! -
django ORM: Filter results differ between shell and application
I've got a headache-causing issue regarding the filter-function within django ORM: The filter function returns different values if executed in the manage.py shell compared to the actual application I'm building. What I try to achieve: Querying all entries in my sqlite database by using the ORM's filter-function targeting a foreign-key relationship. a) Executed in the shell it returns the actual expected results. b) Executed the same way from within the application it returns a completely different (and bigger) subset of results. Relevant Models: class ZeitbuchungHead(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) datum = models.DateTimeField() status = models.ForeignKey(ZeitbuchungStatus, related_name='zeitstatus', on_delete=models.CASCADE) class ZeitbuchungDetail(models.Model): zeitbuchung_head = models.ForeignKey(ZeitbuchungHead, on_delete=models.CASCADE) zeit_von = models.TimeField() zeit_bis = models.TimeField() zeitbuchungsart = models.ForeignKey(ZeitbuchungArten, on_delete=models.CASCADE) Database: ZeitbuchungHead ZeitbuchungDetail Shell-Query: In [1]: import datetime In [2]: from erfassung_app import models In [3]: from django.contrib.auth.models import User In [4]: u = User.objects.get(username='TestUser1') In [5]: date = datetime.date.today() In [6]: head = models.ZeitbuchungHead.objects.get(user=u, datum=date) In [8]: details = models.ZeitbuchungDetail.objects.filter(zeitbuchung_head = head) In [9]: print(details) <QuerySet [<ZeitbuchungDetail: TestUser1 2018-04-09 00:00:00 08:00:00 09:00:00 Arbeitszeit>, <ZeitbuchungDetail: TestUser1 2018-04-09 00:00:00 08:00:00 09:00:00 Arbeitszeit>, <ZeitbuchungDetail: TestUser1 2018-04-09 00:00:00 08:00:00 09:00:00 Arbeitszeit>, <ZeitbuchungDetail: TestUser1 2018-04-09 00:00:00 08:00:00 09:00:00 Arbeitszeit>, <ZeitbuchungDetail: TestUser1 2018-04-09 00:00:00 08:00:00 09:00:00 Arbeitszeit>, <ZeitbuchungDetail: TestUser1 2018-04-09 00:00:00 08:00:00 … -
Error while installing Django channels
I am using python 3.5 version . I am getting this error while trying to install django-channels. Exception: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 278, in run requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1266, in prepare_files req_to_install.extras): File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2291, in requires dm = self._dep_map File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2484, in _dep_map self.__dep_map = self._compute_dependencies() File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2508, in _compute_dependencies parsed = next(parse_requirements(distvers)) File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 45, in <lambda> next = lambda o: o.next() File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2605, in parse_requirements line, p, specs = scan_list(VERSION,LINE_END,line,p,(1,2),"version spec") File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2573, in scan_list raise ValueError("Expected "+item_name+" in",line,"at",line[p:]) ValueError: ('Expected version spec in', 'asgiref ~=2.1', 'at', ' ~=2.1') Storing debug log for failure in /home/praneet/.pip/pip.log -
Using AJAX to execute a python script that takes a picture (raspberry pi)
I am working on a project for which I need to build a web interface that will allow interaction with a Raspberry Pi camera. I am using Django and python for the back end. I want to be able to press a button on the web interface that will execute a python script to take a picture with the pi camera. I am thinking I need to use AJAX to complete this, but I don't really understand how I would set this up. I am relatively new to Django itself. -
Django Models class attribute
Most likely pretty basic question but I can't get my head around it. My Django model consists of two different classes: Project and Inventory with the attributes Project_Amount and Inventory_Amount, respectively. The method in Project is meant to display the remaining amount in the inventory after a client etc. ordered a certain amount for his project. Any hints on how to solve this? class Inventory(models.Model): Inventory_Amount Item ... etc. ... class Project(models.Model): Project_Amount Project_Item ... etc. ... def In_Stock(self): return Inventory.Inventory_Amount - self.Project_Amount If I change the last bit to def In_Stock(self): return Inventory.Inventory_Amount I get 'django.db.models.query_utils.DeferredAttribute object at 0x0000000003EE6940' which I don't understand.' Thank you guys! -
How to make Django ORM query database through reverse ForeignKey work faster?
I have 3 models connected with ForeignKey: class Product(TimeStampedModel): product_id = models.AutoField(primary_key=True, ) shop = models.ForeignKey('Shop', related_name='products', to_field='shop_name', on_delete=models.CASCADE) brand = models.ForeignKey('Brand', related_name='products', to_field='brand_name', on_delete=models.CASCADE) class Meta: indexes = [ models.Index(fields=['title', 'shop', 'sale']), models.Index(fields=['shop', 'brand', 'price', 'title']), ] class Brand(models.Model): brand_id = models.AutoField(primary_key=True,) brand_name = models.CharField(max_length=50, unique=True, blank=False, null=False) class Shop(models.Model): shop_id = models.AutoField(primary_key=True,) shop_name = models.CharField(max_length=30, unique=True, blank=False, null=False, db_index=True) From my view I try to filter Brands where available for this Shop, accessing Shop via Product ForeignKey: brands = Brand.objects.filter(products__shop__shop_name=shop).distinct('brand_name').order_by('brand_name') The problem is that this query takes a long time to process: from 1-3+ seconds. Is there a way to make it work faster? May be I can add some Indexes? I have already tried some combinations (you can find them in Product - Meta class), but it seems like that doesn't help. Or may be there is a better way when I create a Brand entry - add a some kind available_in_shops = ListField(...)(I have found this can be made with JSONField, but I don't know yet how this works exactly)? And store there a list of shops where that Brand is available? -
How to deactivate user instead of deleting,as a DJANGO admin?
I know that to deactivate a user you would set user.is_active = false and the code would look something similar to this: def ban_profile(request): user = request.user user.is_active = False user.save() messages.success(request, 'Profile successfully disabled.') return redirect('index') and then the action would be called under your list_display. But I'm not sure as to exactly what the code would look like as I can't get it to work. -
Synchronous celery queues
I have an app where each user is able to create tasks, and each task the user creates is added to a dynamic queue for the specific user. So all tasks from User1 are added to User1_queue, User2 to User2_queue, etc. What I need to happen is when User1 adds Task1, Task2, and Task3 to their queue, Task1 is executed and Celery waits until it is finished before it executes Task2, and so on. Having them execute along side each other from multiple queues is fine, so Task1 from both User1_queue, and Task1 from User2_queue. Its just limiting Celery to synchronously execute tasks in a queue in the order they're added. Is it possible to have Celery have a concurrency of 1 per queue so that tasks are not executed alongside each other in the same queue?