Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Query data optimization
Recently, I watched Django and discovered the teaching videos of select_related and prefetch_related. So I installed debug_toolbar and took a look at my website I searched the database too many times on one page. I must convert it to json and send it back to the front end Can I still optimize? Is this the only way to go? Below is my model . models.py def get_upload_path(instance, filename): return f'register/{instance.owner.job_number}/{filename}' def image_upload_path(instance, filename): date = datetime.datetime.strptime(instance.date, '%Y-%m-%d %H:%M:%S') return f'image/{date.year}/{date.month}/{date.day}/{filename}' class UserProfile(models.Model): name = models.CharField(max_length=64) department = models.CharField(max_length=32) job_number = models.CharField(max_length=32, unique=True) card_number = models.CharField(max_length=32, unique=True) location = models.CharField(max_length=32) date = models.DateTimeField() class UserRegister(models.Model): owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE) date = models.DateTimeField() feature = ArrayField(models.FloatField(null=True, blank=True), null=True, blank=True, size=512) image = models.ImageField(upload_to=get_upload_path) class Meta: db_table = 'UserRegister' class UserImage(models.Model): owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE) heat = models.CharField(max_length=8, blank=True, null=True) date = models.DateTimeField() image = models.ImageField(upload_to=image_upload_path) punch_in = models.CharField(max_length=8, blank=True, null=True) class Meta: db_table = 'UserImage' views.py def get_db_data(db, page, limit, model): data = [] paginator = Paginator(db, limit) try: page_object = paginator.page(page) all_page = paginator.num_pages for db_data in page_object: images = [] for image in db_data.userregister_set.all(): try: url = f'/static/uploads{image.image.url}' except ValueError: url = '/static/imgs/assets/none.jpg' images.append({'id': image.id, 'url': url}) _ = { … -
Django 'attempt to write a readonly database' even if db file has read and write permissions
I am using SQLite3, Ubuntu server. I have checked the read and write permissions of the database file. It is: -rw-r--r-- Doesn't this mean that the file has read and write access? So why is Django error saying attempt to write a readonly database? Thanks in advance! -
Load Datatable after passing parameter on form submit to Django View
Unable to pass parameters at view side from the template and based on that want to load Datatable in my Django project I have a simple form created in a template dateForm.html with date fields <form method="POST"> <div class="row justify-content-center"> <div class="col-md-auto"> Start Date: <input type="text" name="startDate" id="startDate"> </div> <div class="col-md-auto"> End Date: <input type="text" name="endDate" id="endDate"> </div> <div class="col-md-auto"> <button name="search" value="search" type="submit">Search</button> </div> </div> </form> On Form submit want to pass the selected date to studentView.py Issue: This form is inside a different python app 'admin' and Datatable Url is redirecting to a different python app 'student' View. So, Confused about how can I get this submitted date to the view the same as my Datatable view(Datatable is inside the dateForm.html only and dateForm.html is rendering from Adminview.py) -
how to fix error Koa Native Open edX platform Ubuntu 20.04 64 bit Installation error?
i am installing Koa Native Open edX platform Ubuntu 20.04 64 bit through followed by https://openedx.atlassian.net/ documentation but last moment i getting this error how to fix it error: 7184 bytes of body are still expected fetch-pack: unexpected disconnect while reading sideband packet fatal: early EOF fatal: index-pack failed bash: line 155: cd: configuration: No such file or directory fatal: not a git repository (or any of the parent directories): .git fatal: not a git repository (or any of the parent directories): .git bash: line 162: cd: /var/tmp/configuration: No such file or directory ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' bash: line 168: cd: /var/tmp/configuration/playbooks: No such file or directory ============================================================ Ansible failed! ------------------------------------------------------------ Decoded error: python3: can't open file '/var/tmp/configuration/util/ansible_msg.py': [Errno 2] No such file or directory ============================================================ Installation failed! -
Django: OperationalError at /api/v1/ no such table: leads_followup
models.py class Followup(models.Model): FOLLOWUP_CHOICES = ( (0, 'Not Finished'), (1, 'Finished') ) lead = models.ForeignKey( Lead, on_delete=models.CASCADE, related_name='followups' ) response = models.CharField( max_length=150, blank=True, null=True ) response_number = models.SmallIntegerField( 'Number of given followup response (eg. 1)', default=1 ) date = models.DateField(auto_now_add=True) action = models.SmallIntegerField( choices=FOLLOWUP_CHOICES, default=FOLLOWUP_CHOICES[0][0] # not finished item's index. ) recorded_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='recorded_followups' ) def __str__(self): return self.lead.name I have run all migrations locally. Whenever I make some change in my model and I try to run migrations, django complains about this error. There's another case, when I mention this model in the loop of the viewset, Django will raise this exception. views.py class FollowupViewSet(viewsets.ModelViewSet): # I comment from here followups = Followup.objects.all() expected_followup_ids = [] lead_names = [] for followup in followups: if followup.lead.name not in lead_names: lead_names.append(followup.lead.name) expected_followup_ids.append( Followup.objects.filter(lead=followup.lead).last().id ) else: continue queryset = Followup.objects.filter(id__in=expected_followup_ids) # to here serializer_class = FollowupSerializer filter_backends = [DjangoFilterBackend, ] filterset_fields = ['date', 'recorded_by', 'response'] What's wrong here? How can I run migrations without having caused the error and without commenting on my views.py file's code block? -
You must set settings.ALLOWED_HOSTS if DEBUG is False. Django-r-f
I want to prepare the server for deployment and this is the setup. settings.py is split into dev.py and prod.py in settings.py at the bottom ALLOWED_HOSTS = [] I also have tried ALLOWED_HOSTS = ['*'] dev.py from ..settings.settings import * DEBUG = True wsgy.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'movie_api.settings.dev') CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. When I import settings in the manage.py shell, the settings.DEBUG = False .. why? How to make wsgi.py read the correct file? -
Dependencies are not being installed Elastic Beansalk + Django
I am currently running Django 3.1.2 and Python 3.7 running on 64bit Amazon Linux 2 From the elastic beanstalk logs its telling me that there is no django module. 2021-04-08 05:09:30,592 P3788 [INFO] ============================================================ 2021-04-08 05:09:30,593 P3788 [INFO] Test for Command 01_migrate 2021-04-08 05:09:30,596 P3788 [INFO] Completed successfully. 2021-04-08 05:09:30,596 P3788 [INFO] ============================================================ 2021-04-08 05:09:30,596 P3788 [INFO] Command 01_migrate 2021-04-08 05:09:30,622 P3788 [INFO] -----------------------Command Output----------------------- 2021-04-08 05:09:30,623 P3788 [INFO] Traceback (most recent call last): 2021-04-08 05:09:30,623 P3788 [INFO] File "manage.py", line 11, in main 2021-04-08 05:09:30,623 P3788 [INFO] from django.core.management import execute_from_command_line 2021-04-08 05:09:30,623 P3788 [INFO] ModuleNotFoundError: No module named 'django' 2021-04-08 05:09:30,623 P3788 [INFO] 2021-04-08 05:09:30,623 P3788 [INFO] The above exception was the direct cause of the following exception: 2021-04-08 05:09:30,623 P3788 [INFO] 2021-04-08 05:09:30,623 P3788 [INFO] Traceback (most recent call last): 2021-04-08 05:09:30,623 P3788 [INFO] File "manage.py", line 22, in <module> 2021-04-08 05:09:30,623 P3788 [INFO] main() 2021-04-08 05:09:30,623 P3788 [INFO] File "manage.py", line 17, in main 2021-04-08 05:09:30,623 P3788 [INFO] ) from exc 2021-04-08 05:09:30,623 P3788 [INFO] ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? 2021-04-08 05:09:30,623 P3788 [INFO] ------------------------------------------------------------ I have … -
Transferring data between Django projects
I have two Django projects with similar apps, and I need to transfer/transform data from one app (@djangoproject1) to another (@djangoproject2). My script to access both projects/databases (inspired by this post) looks like this import os import sys from django.apps import apps sys.path.append('/django/djangoproject1') sys.path.append('/django/djangoproject2') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoproject1.settings") from djangoproject1 import settings apps.populate(settings.INSTALLED_APPS) from app1.models import Page mypage = Page.objects.get(id=1234) print(mypage.title) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoproject2.settings") from djangoproject2 import settings apps.populate(settings.INSTALLED_APPS) from app2.models import Page mypage = Page.objects.get(id=3421) print(mypage.title) It fails importing the model Page from app2, referring to the first model in models.py: RuntimeError: Model class app2.models.FirstModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. If the configuration for one project (either djangoproject1 or djangoproject2) is commented out, the script works fine (printing the respective page's title). How can I load the database content from one project/app, then switch to the other project/app properly? -
Django Fetch Data from multiple models connected using Foreign Keys
I am new to Django and currently working on my first project. I have my models designed liked this: class BasketProductMapping(models.Model): product_reference = models.ForeignKey(Product, default=1, null=True, blank=True, on_delete=models.CASCADE) mapped_basket_name = models.CharField(max_length=5,null=False, blank=False) mapped_product_name = models.CharField(max_length=30, null=False, blank=False) def __str__(self): return self.mapped_basket_name class ShelfBasketMapping(models.Model): mapped_basket_name_reference= models.ForeignKey(BasketProductMapping, on_delete=models.CASCADE, default=1) mapped_name_shelf = models.CharField(max_length=15, null=False, blank=False, default='default') mapped_name_basket = models.CharField(max_length=15, blank=False, null=False, default="default") def __str__(self): return self.mapped_name_shelf class KioskShelfMapping(models.Model): mapped_shelf_basket_name_reference = models.ForeignKey(ShelfBasketMapping, on_delete=models.CASCADE, default=1) mapped_shelf_name = models.CharField(max_length=15, null=False, blank=False, default="default") mapped_kiosk_name = models.CharField(max_length=15, blank=False, null=False, default="default") def __str__(self): return self.mapped_shelf_name Say for my first model I have my Data like this: B1 - P1 B1 - P2 B2 - P1 B3 - P1 and for my second models I have my data like this: S1 - B1 S2 - B2 S1 - B3 and finally for my third model, I have my data like this: K1 - S1 K2 - S2 Here is my serializers.py: class KioskShelfMappingGetSerializer(serializers.ModelSerializer): class Meta: model = KioskShelfMapping fields = ['id', 'mapped_shelf_basket_name_reference', 'mapped_shelf_name', 'mapped_kiosk_name', 'shelf_position'] depth = 2 and this is my views.py file: class ShelfBasketViewSet(APIView): def get(self, request): shelfBasketMappingData = ShelfBasketMapping.objects.all().select_related("mapped_basket_name_reference") print(shelfBasketMappingData) serializer = ShelfBasketMappingSerializer(shelfBasketMappingData, many=True) response = {'status':1, 'message':"Shelf Basket Mapping List", 'data':serializer.data} return JsonResponse(response, safe=False) I am … -
django - [is_superuser, is_staff] Django Admin Category permission options
I have given [is_staff] access to only a few models and cannot access models that have not. But [is_staff] can see the total list of models. I hope [is_staff] cannot see the categories of models that are not accessible. Is there a way? -
Get the type of polymorphic model
I have this model that extends Polymorphic Model models.py class Orders(PolymorphicModel): def get_cat(self): // if self.category == food class Food(Orders) class Item(Orders) I have to identify the type of the polymorphic model. I can't find any way. -
DRF APIview with authentication
I have a class someAPI(APIView). I would like this one to be accessed by only authorised users. I tried this link How to use login_required in django rest view and https://www.django-rest-framework.org/api-guide/authentication/ but none of them seem work. My current authentication protocol is logging in with username and password. I guess a reason is because I implement this authentication with basic django (https://docs.djangoproject.com/en/3.1/topics/auth/default/) but not DRF. from rest_framework.views import APIView from rest_framework import authentication, permissions from django.http import JsonResponse class APICostAnalysisController(APIView): permission_classes = [permissions.IsAuthenticated] def get(self, request): """ Initiate get API for getting cost analysis """ return JsonResponse(APICostAnalysisImpl().get(), safe=False,json_dumps_params={'indent': 2}) -
Django add custom header in the shorthand render method
To add in a CORS settings I can do something like this on a particular function: def clear(request): # ... something response = HttpResponse('OK') response["Access-Control-Allow-Origin"] = "*" return response However, I'm having difficulty adding it on the shortform render method: def function(request): # how to modify the response header here? return render(request, 'page.html', data) How would I update some of the headers in the render response? -
While choosing the file in django Its showing Object of type FieldFile is not JSON serializable error
ypeError at /web/ticketcreation/ Object of type FieldFile is not JSON serializable This is My models.py class Ticket(models.Model): Email=models.CharField(max_length=60) to=models.CharField(max_length=60) cc=models.CharField(max_length=60) subject=models.CharField(max_length=25) module = models.CharField(max_length=25) priority = models.CharField(max_length=25,null=True) message = models.CharField(max_length=70) choosefile = models.FileField(null=True, blank=True) can any one help me -
Django - How to QuerySet Distinct on field?
I have a Model like below (Mysql). For some reasons, we have duplicated data on this Table. I tried to get distinct records based on Phone, but I couldn't make it done. Can someone help me out, many thanks in advance. class Sale(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) name = models.CharField(max_length=200, null=True, default='') phone = models.CharField(max_length=15, null=True) product = models.ForeignKey('generals.Product', on_delete=models.SET_NULL, null=True) -
Can not install mysqlclient in a OFFLINE CentOS7 server with ERROR message "not a supported wheel on this platform"
I am trying to install mysqlclient in a offline CentOS7 server, so that I can connect my Django site to a MariaDB What I did was to download .wheel package "mysqlclient-2.0.3-cp37-cp37m-win_amd64.whl" from PyPI. Then I run the code pip install mysqlclient-2.0.3-cp37-cp37m-win_amd64.whl But received the following message mysqlclient-2.0.3-cp37-cp37m-win_amd64.whl is not a supported wheel on this platform. [error message][1] [1]: https://i.stack.imgur.com/bhqUD.png I looked through all available answers and internet questions but did not able to find a similar problem. Could someone give me help? Thank you very much -
Implementing image stories in js
I am building Social Media webapp and I am stuck on a Problem. I am trying to implement image stories ( like in :- instagram in my Django WebApp and I am following Zuck.js Repo to implement stories. BUT failed many times. I have made a models named Story and built a story using admin and imported all the css and js BUT nothing is showing. models.py class Story(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default='',null=True) photo = models.ImageField(upload_to='stories',null=True) This is the template where i am showing stories this is the code i have copied from Zuck.js Repo story.html <div id="stories"> <!-- story --> <div class="story {{ story.seen ? 'seen' : '' }}" data-id="{{storyId}}" data-last-updated=" {{story.lastUpdated}}" data-photo="{{story.photo}}"> <a class="item-link" href="{{story.link}}"> <span class="item-preview"> <img src="{{story.photo}}" /> </span> <span class="info" itemProp="author" itemScope="" itemType="http://schema.org/Person"> <strong class="name" itemProp="name">{{story.name}}</strong> <span class="time">{{story.lastUpdated}}</span> </span> </a> <ul class="items"> <!-- story item --> <li data-id="{{storyItemId}}" data-time="{{storyItem.time}}" class="{{storyItem.seen}}"> <a href="{{storyItem.src}}" data-type="{{storyItem.type}}" data-length="{{storyItem.length}}" data-link="{{storyItem.link}}" data-linkText="{{storyItem.linkText}}" data-custom-key="{{storyItem.custom-key}}" data-another-custom-key="{{storyItem.another-custom-key}}"> <img src="{{storyItem.preview}}" /> </a> </li> <!--/ story item --> </ul> </div> <!--/ story --> </div> I never tried js, I have no idea how can i use my model instance in js code to show stories. Any help would be Appreciated. Thank You in Advance. -
My button does not save the form to the database. Help please
I am trying to save this form for an attendance website. But whenever I clicked the clock in button it does not save the data to the database. code: if response.method == "POST": form = CreateNewList(response.POST) if response.POST.get("clockIn"): if form.is_valid(): n = form.cleaned_data["name"] t = Name(name = n, timeIn=datetime.now()) t.save() else: form = CreateNewList() return render(response, "main/home.html", {"form":form}) html button code: <button type="submit" ,name="clockIn", value="time In" class="btn-success">Clock In</button> I have also tried using this: if 'clockIn' in response.POST: if form.is_valid(): n = form.cleaned_data["name"] t = Name(name = n, timeIn=datetime.now()) t.save() It still does not work. Help please. -
Form select field that refreshes page with post data
I want to add a select field that is populated via a queryset, and when a choice is made refresh the template page (home.html) so that a variable inside my view changes and refreshes the JSON data being passed through to the template. Right now, I can manually change the value inside the view & manually refresh, but want the user to be able to select which value they want based on table object values. The range_chart(request) feeds home.html which loads a chartjs line chart with multiple series. I want the form to display all unique values from the rrSec field, and be ordered. models.py: from django.db import models from datetime import datetime class rr_values(models.Model): rrDate=models.DateField(default=datetime.now) rrSec=models.CharField(max_length=30) rrTrend=models.CharField(max_length=30) rrLow=models.FloatField() rrHigh=models.FloatField() rrClose=models.FloatField() class Meta: db_table='rr_values' views.py: thisSec = "COMPQ" def home(request): return render(request, 'home.html', {'rrSymbol': thisSec}) class SymbolForm(forms.Form): formqs = forms.ModelChoiceField(queryset=rr_values.objects.all().values_list('rrSec', flat=True).distinct()) def range_chart(request): labels = [] data = [] data1 = [] data2 = [] rrSymbol = thisSec qs = rr_values.objects.all().filter(rrSec=rrSymbol).order_by("rrDate") for entry in qs: labels.append(entry.rrDate) data.append(entry.rrClose) data1.append(entry.rrLow) data2.append(entry.rrHigh) return JsonResponse(data={ 'labels': labels, 'data': data, 'data1': data1, 'data2': data2, }) -
Applying custom model manager to Django Admin (for proxy models)
I have two proxy models that inherit from a base. These proxy models each have their own validation rules. class FooManager(models.Manager): def create(self, **kwargs): if "bar" in kwargs: raise ValidationError("Foo object should not have bar field") return super(FooManager, self).create(**kwargs) class BarManager(models.Manager): def create(self, **kwargs): if "foo" in kwargs: raise ValidationError("Bar object should not have foo field") return super(BarManager, self).create(**kwargs) class Base(models.Model): foo = CharField() bar = CharField() class Foo(Base): objects = FooManager() class Meta: proxy = True class Bar(Base): objects = BarManager() class Meta: proxy = True So in the shell, everything works as intended: # These are created Foo.objects.create(foo="foo") Bar.objects.create(bar="bar") # These will raise the correct ValidationErrors Foo.objects.create(bar="bar") Bar.objects.create(foo="foo") But if I try to create an object via Django's Admin, the validation no longer works. I can create a Foo object with a bar field and a Bar object with a foo field. Is it possible to apply my Custom Managers to Django's Model Admin? Edit: I am using Single Table Inheritance -
How do I get row from django database?
Hello I am trying to create a clockIn clockOut website and I do not know how to get a row filtered by a persons name to add in the clock out time. Here is the code. The first if statement is working fine but the else statement is where I am having trouble doing: if response.POST.get("clockIn"): if form.is_valid(): n = form.cleaned_data["name"] t = Name(name = n, timeIn=datetime.now(), timeOut=NULL) t.save() else: if form.is_valid(): n = form.cleaned_data["name"] t = Name.objects t = t.filter(name = n) s = t(timeOut = datetime.now()) s.save() -
How do I illiterate in Django template
''' {% for j in listOfStoresUsed %} <div class="col-sm-8" style="display: none; margin-left: 6em;" id = "store-{{j}}"> {% for i in itemsOrganizedByStore %} <img width="200em" height="200em" src={{i.item.imgURL}}> <p>{{i.item.name}} Q:{{i.quantity}}</p><br> {% endfor %} {% endfor %} ''' itemsOrganizedByStore is a list, and I want to do for i in itemsOrganizedByStore[x] x being an index that would be declared in a for loop above. How can I use a number for x in Django -
Django filter with replace
Let's say I have the following model which have a method variants(): class Example(models.Model): text = models.CharField(max_length=255) def variants(self): return Example.objects.filter(text=remove('xy', self.text)) The idea is to get all objects where texts are the same after certain characters are removed from the text. For example, if self.text is 'axxyy', it should match with the object which have text 'a'. Function remove() doesn't touch to the database, it returns a new string which have given characters removed. This works fine. However, I have a need to perform the same operation on both sides of the comparison, so that variants() would behave like following: def variants(self): return Example.objects.filter(remove('xy', text)=remove('xy', self.text)) In that case, if self.txt is 'axxyy' it should match with 'a', 'ax, 'axx', 'xayy', etc. but shouldn't match with 'aa' for example, since 'a' != 'aa' after removals. Once again, I don't want to remove 'xy' from the database, only for the comparison. I could do this with Python, but I'm wondering if there is a way to do this on database level? I've been reading docs about Func() expressions, for example Replace, but haven't found a solution yet. -
Django Error "django.db.utils.ProgrammingError: subquery has too many columns "
The raw query itself is correct and I am able to get retrieve the rawqueryset from the db. I need to convert this into queryset for further processing and I am facing below error. Creating corresponding django query was hard for me and that is why I created SQL query, got the raw query set and now attempting to convert it to query set for further processing. I have changed django model names and table names for anonymity. Here is the output of what I tried in django shell. I was able to execute the below query but getting the error "django.db.utils.ProgrammingError: subquery has too many columns" when I try to access "queryset" below. from django.db.models.expressions import RawSQL from xyz.models import * value = '1.2.3.4' queryset = Test1.objects.filter(id__in=RawSQL("SELECT DISTINCT ON (test1.start_time, test1.id) test1.id, test1.name, test1.start_time FROM test1 WHERE EXISTS (SELECT * FROM test2 JOIN test3 ON test2.test3_id = test3.id AND test3.value = %s JOIN test4 ON test2.test4_id = test4.id AND test4.test1_id = test1.id) ORDER BY test1.start_time DESC", params=[value])) For readability I have formatted the query used below. SELECT DISTINCT ON (test1.start_time, test1.id) test1.id, test1.name, test1.start_time FROM test1 WHERE EXISTS ( SELECT * FROM test2 JOIN test3 ON test2.test3_id = test3.id … -
ModuleNotFoundError: No module named 'admin_interface
I'm making a project in my school and works well in the school pc, but today when I'm pass the project to my pc and type: python manage.py runservice This appears: (venv) PS C:\> cd MiColegio (venv) PS C:\MiColegio> python manage.py runservice Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\venv\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\DANIEL\AppData\Local\Programs\Python\Python38\lib\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 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'admin_interface' (venv) PS C:\MiColegio>