Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django many to many field add with through model fields
I have the models below, and I want to add a member to a group in a view. How could I do this, also adding the date_joined and invite_reason correctly. from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) -
How to use a field as a filter group?
Currently have a list of Records that have fields child (Child model has Parent) and date. class Record(models.Model): child = models.ForeignKey(Child) date = DateField() ... other fields I would like to generate a daily list of Records that are grouped at a date level. i.e. Parent > 2020-06-06 > Child + Record other fields Right now I've devised a way to brute force through all the records at the serializer level if I select from the Parent level. records = serializers.SerializerMethodField() def get_records(self, obj): qs = Record.objects.filter(child__parent=obj) dates_dict = defaultdict(list) for row in qs.all(): date = row.date.strftime('%Y-%m-%d') dates_dict[date].append(RecordSerializer(row).data) return dates_dict However, this messes with pagination as it creates a single record because there's only 1 Parent. I do not need the Parent data at all. What I would like is for the data to be paginated on the date level. { "id": 1, "name": "Parent", "reports": { "2020-05-20": [ { "child": { "id": 1, }, ..other fields }, { "child": { "id": 2, }, ..other fields }, { "child": { "id": 3, }, ..other fields }, ] } } How would I paginate this if I'm filtering on the Python level? I am trying to achieve this: { "count": 100, … -
Key error while trying to access custom environment variable in Django application on a virtual machine running Ubuntu
I have set an environment variable on my VM as follows (in my virtual env): $ export MYSQL_USER="naitik" Also when I tried to echo the value on terminal, it is showing correct output: $ echo $MYSQL_USER naitik Even when I printed the value on python interpreter on the terminal, it is showing correct output. But when I tried to use it in my Django application, it is showing error. settings.py file where I have tried to use the environment variable: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '<myhost>', 'PORT': '3306', 'NAME': 'ndt_db', 'USER': os.environ["MYSQL_USER"], 'PASSWORD': os.environ["MYSQL_PASSWORD"], } } Error log from gunicorn: Traceback (most recent call last): File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/home/ubuntu/env/lib/python3.6/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
Django 3.0.7 unable to change STATIC_ROOT path
Hi I am new to django, I have created a django project with following urls.py and settings.py codes respectively urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include("user_mgmt.urls")), path('',include("dashboard.urls")), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"spaat_static") then I am collecting the static files using: python manage.py collectstatic but Django is collecting files in the ../staticfiles directory, whereas I have defined ../spaat_static in STATIC_ROOT. How to solve this issue ? Thank you in advance! -
Autocomplete with Django + React
I'm creating a web app using Django Rest Framework for the backend and will use React for the frontend. I'd like to create a field where the user can enter the university they attend and want that to be a drop down/autocomplete search option (ex: user types in "U" then "UC Berkeley" and "UC Los Angeles" show up). I have a CSV file with all the college data, and I'd like the search to autocomplete from there. I've found this resource (here: https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html) in other Stack Overflow posts, but nothing of how to import from the CSV file. Are there any resources for this? Any help would be appreciated, thank you! -
I need to implement a flutter app, when 2 phones come near it must alert the 2 phones
I have less experience in this field. I have no idea to implement this feature. I dont know what to google. Please help me out. -
Reshaping django data grouping them
I have the following data in the format of : [ { "sales_project_id": 1, "sales_project_est_rev": "892123.00", "project_status": 1, "userProfile": [ 1 ], "customer_information": [ 1 ] }, { "sales_project_id": 2, "sales_project_est_rev": "892123.00", "project_status": 2, "userProfile": [ 1 ], "customer_information": [ 1 ] }] However i wish to group them together by their project_status ID it such that: [ { "project_status": 1 "data" : [{ "sales_project_id": 1, "sales_project_est_rev": "892123.00", "userProfile": [ 1 ], "customer_information": [ 1 ] }] }] My serializer is as shown below: class SalesProjectAllSerializer(serializers.ModelSerializer): class Meta: model = SalesProject fields = '__all__' depth = 2 -
Distinct() doesn't work on queryset resulting from union()
I have a model: class Person(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) if I do: all_queryset = Person.objects.all() all_queryset.count() # --> 8 all_queryset.order_by('name').distinct().count() # --> 3 Let's union it with another empty queryset: empty_queryset = Person.object.none() all_queryset = all_queryset.union(empty_queryset) all_queryset.count() # --> 8 and now, distinct() doesn't work anymore: all_queryset.order_by('name').distinct().count() # --> 8 ! Is it this 4 year old bug? -
how to schedule my django view function with celery periodic task?
Here I have a Task Model which has various fields but for the scheduling purpose only the task_status, search_frequency and scraping_end_date will be used. I want to schedule my def crawl(request) view (which is working fine) with the task object search_frequency and by checking some task object fields. Task Model class Task(models.Model): INITIAL = 0 STARTED = 1 COMPLETED = 2 task_status = ( (INITIAL, 'running'), (STARTED, 'running'), (COMPLETED, 'completed'), (ERROR, 'error') ) FREQUENCY = ( ('1', '1 hrs'), ('2', '2 hrs'), ('6', '6 hrs'), ('8', '8 hrs'), ('10', '10 hrs'), ) name = models.CharField(max_length=255) scraping_end_date = models.DateField(null=True, blank=True) search_frequency = models.CharField(max_length=5, null=True, blank=True, choices=FREQUENCY) status = models.IntegerField(choices=task_status) tasks.py I want to run the crawl function with task search_frequency time if the task status is 0 or 1 and not crossed the task scraping end date. But I got stuck here. How can I do this? @periodic_task(run_every=crontab(hour="task.search_frequency")) # how to do with task search_frequency value def schedule_task(pk): task = Task.objects.get(pk=pk) if task.status == 0 or task.status == 1 and not datetime.date.today() > task.scraping_end_date: # perform the crawl function ---> def crawl() how ?? if task.scraping_end_date == datetime.date.today(): task.status = 2 task.save() # change the task status as complete. views.py I … -
how to get csrfmiddlewaretoken in react class component
I create a register page on using React and the backend uses Django. There exist a provided registration page UI but it doesn't look so good so I made one using React. I'm trying to use the same parameters as the Django one but the one parameter I Cant figure out how to get is the csrfmiddlewaretoken. i'm using this https://docs.djangoproject.com/en/3.0/ref/csrf/ for help, but the 'getCookie' method return null since my document doesn't have any cookie. -
How to send POST requests to Django Rest Framework without authentication?
I want to create a POST request from React to DRF for a normal search functionality: ANYONE on the site can input something in a search field and that data will be used to query the database. I do not need the users to be authenticated or anything. In DRF there needs to be an authentication class and I dont know which one to use. Any ideas? -
how connect to IoT devices with python
I have 300 sensors in a wide site and every 200 ms I have to send a request to them to get data and sensors reply at max 100 ms sensors manufacturer programmed the sensors to answer requests on socket(TCP/IP) only and I want to make a dashboard for monitor sensors status by python and Django and run it on raspberry pi 4(4 G Ram) is it possible? how I connect to 150 sensors at the same moment (multi-thread? or another way) and raspberry pi 4 can handle this project? -
how to pre-pend a string to the url in django
I want to be able to launch multiple django sites on the same server where each different version has a different prefix in the url, such that ver1 would be ipAddress/ver1/index ver2 would be ipAddress/ver2/index and so forth and so on. is there a django setting that allows for this sort of pre-fix setting? I looked through the url dispatcher but I could find nothing there of benefit. I got it working for the most part by just manually pre-pending the urls in the html pages with a variable that I fill in the views.py file with the correct prefix, but I then noticed that if I am logged in and viewing the /admin page, the link for View Site goes to / and not the /ver1 like it should? -
How can i copy the contetnts from table to another after the validation of data by admin in django
there is a table called products where all the user posted data are stored.i want to copy the contents from products table to a table called approved only when the admin approves the data. -
Append a subset of a queryset to the same queryset (not logical union)
I have a model: class Person(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) if I do: all_queryset = Person.objects.all() all_queryset.count() # --> 8 subset_queryset = Person.object.filter(name = 'John') subset_queryset.count() # --> 1 Let's say I want to append the subset_queryset to the all_queryset (even keeping duplicates): result_qs = all_queryset.union(subset_queryset) result_qs.count() # STILL 8! # or all_queryset |= subset_queryset all_queryset.count() # STILL 8! I get it's really a LOGICAL union in a sense of: if it's a subset of a more global queryset, it keeps the global. (the opposite of logical intersection qith &). -
NameError - name 'UserProfileInfo' is not defined
While i created a model inside models.py file but it shows error while migration enter image description here enter image description here -
Passing files but django form not accepting them
I have a form: class MessageAttachmentForm(forms.ModelForm): class Meta: model = MessageAttachment fields = ("attachment",) And in my view, I have it receive some files with the incorrect names so I try to create a new MultiValueDict and submit the files one by one using the correct name like so: if request.FILES: files_dict = request.FILES.copy() files_dict.clear() for file in request.FILES: files_dict["attachment"] = request.FILES.get(file) attachment_form = MessageAttachmentForm(files_dict) if attachment_form.is_valid(): attachment = attachment_form.save() message_object.attachments.add(attachment) Where origininally, the request.FILES returns this: <MultiValueDict: {'attachment0': [<InMemoryUploadedFile: some_image.png (image/png)>], 'attachment1': [<InMemoryUploadedFile: report.pdf (application/pdf)>]}> And on every iteration of request.FILES, when I add the file to the files_dict, I get this: <MultiValueDict: {'attachment': [<InMemoryUploadedFile: some_image.png (image/png)>]}> #And <MultiValueDict: {'attachment': [<InMemoryUploadedFile: report.pdf (application/pdf)>]}> Which looks ok, but still doesn't work. I also tried using a regular dict but that was to no avail either. The attachment_form.errors says that the field attachment is required. Thank you for taking your time reading this any help is appreciated. -
What is the best solution for communicating of server and client in django framework without refreshing page?
I am making a web app to rent smart bicycles by smart phone through a Django server and in the bike side I want to use raspberry pi zero W .I need to establish a safe connection between server and raspberry by http .I have searched for socket programming but I do not know the limitations of server ports and I want to know if there is the better solution instead of socket? thanks anyway -
How to execute JavaScript and Django concurrently from a single HTML button?
My end-goal is to process my Django view when a button is clicked (to save database info), as well as executing some JavaScript (to display a bootstrap success alert). However, the bug or potential limitation I'm encountering is that I can only do one or the other. I confirmed this to true by simply removing the onclick="somefunction()" parameter from the button element. If it's removed, the response is "posted" successfully to my Django view. If it's kept, only the JavaScript function is executed. Here is my code: HTML: {% csrf_token %} <form method="POST" class="form_group"> <!-- ...some unrelated bootstrap stuff --> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal" id="cancel-button-id">Cancel</button> <button type="submit" class="btn btn-primary" onclick="indicate_if_successful()" id="save-customer-button-id" name="save_customer" value="save_customer">Save customer info</button> <!-- The button above is the one having issues --> </div> </form> Django view def add(response): # This function doesn't get executed if 'onclick' exists if response.method == "POST": if response.POST.get("save_customer"): pass # The code I want to execute So in order to execute both the JavaScript function and Django view, what are my options? Should I be doing all of this differently in the first place? I'm open to any alternative. -
Exception Value: __init__() got an unexpected keyword argument 'limit_choices_to'
class Account(models.Model): username = models.OneToOneField(User, on_delete=models.CASCADE) #email = models.EmailField(verbose_name="email", max_length=60, unique=True) contact = models.CharField(max_length=30, unique=True) fathers_name = models.CharField(max_length=30) date_of_birth = models.DateField(null=True) address = models.TextField(max_length=250) aadhar_number =models.CharField(max_length=14) pan_number = models.CharField(max_length=14) education = models.TextField(max_length=250) salary = models.IntegerField( default=0) department_id = models.IntegerField(default= 0) designation_id = models.IntegerField(default=0) GENDER_CHOICES = ((0, 'Male'), (1, 'Female')) gender = models.IntegerField(choices=GENDER_CHOICES) MARITAL_STATUS_CHOICES = ((0, 'Married'), (1, 'Unmarried')) marital_status = models.IntegerField(choices=MARITAL_STATUS_CHOICES) USERNAME_FIELD = 'username' I have extended mapped my Account class to User and now when I try to add new account, my app gives following two errors depending on whether I have USERNAME_FIELD in my Account model or not. When I don't have a USERNAME_FIELD: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/ems/account/add/ Django Version: 3.0.6 Python Version: 3.8.3 Installed Applications: ['ems', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\ACER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\ACER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\ACER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\ACER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\options.py", line 607, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\ACER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\ACER\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = … -
CSS file won't load - Django
I'm having trouble loading my CSS files. The browser that I'm using is Chrome. Here are my codes and file directories. Thanks! file directories • ecommerce/ecommerce/settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) .... # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store.apps.StoreConfig', ] .... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/') ] • ecommerce/ecommerce/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls')) ] • ecommerce/ecommerce/static/css/main.css body{ background-color:blue; } • ecommerce/ecommerce/store/templates/store/store.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <h3>store</h3> <img src="{% static 'images/cart.png' %}"> • ecommerce/ecommerce/store/urls.py from django.urls import path from . import views urlpatterns = [ #Leave as empty string for base url path('', views.store, name="store"), path('cart/', views.cart, name="cart"), path('checkout/', views.checkout, name="checkout"), ] • ecommerce/ecommerce/store/views.py from django.shortcuts import render # Create your views here. def store(request): context = {} return render(request, 'store/store.html', context) def cart(request): context = {} return render(request, 'store/cart.html', context) def checkout(request): context = {} return render(request, … -
How can you exclude fields in Django?
Hello I would like to do something like: Model.objects.all().values().exclude('id') where the results are turned into a dictionary but excluding field 'id'. I know I could list out all the fields to bring into the dictionary but my model has close to 50 fields. Is this possible in Django? I have tried the following but it does not work: Model.objects.all().defer('id').values() -
Ckeditor loading a different config file
I'm trying to integrate ckeditor on my admin panel of my site but the changes in the config.js file are not reflecting. I checked for the sources on my browser and found it loads config.js?t=JB9C instead of config.js. How do I either edit the config.js?t=JB9C or load just config.js? It's slightly urgent and I will keep refreshing this page, please help. -
How can I select distinct names and with their corresponding earliest detected time in django orm?
Im really having a difficult time querying my model in django orm. I need to create a query where it will select distinct names with their corresponding earliest time detected. Any help or advice would be very appreciated. Note that the real table has hundreds of entries this is only a simple representation.1 Ps. Im just new here, i dont know how to show the image properly. Sorry -
Immediately require credentials on landing page for access to entire site
I want to require credentials on the landing page for access to the entire website for a django app. I googled some stuff but can't find answers. Please point me in the right direction. Thanks