Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> -
Django Channels App Websocket Connection Failing
I believe I have a similar issue to the one found here and here. The gist is that I'm running a Django app with channels on an Amazon-ec2 instance and the websockets are failing to connect. Most of my code regarding the websockets comes from the django-channels tutorial here. Traffic is being directed though secured dns name behind an application load balancer. I'm running this entirely on Daphne (handling both https and websocket traffic) with pretty minimal configurations: daphne -b <server_url> -p <port> test_app.asgi:application I'm also authenticating with openID-connect using the mozilla-django-oidc module. However for the websocket test I'm not expecting authentication. I feel it's worth pointing out if the issue is related to websocket authentication in any way. In development I'm running a local redis cluster as my channel layer. My dev app (all http:// and ws://) has no issues connecting to websockets. The chat app works as expected. I can connect to my websockets and is confirmed with a 127.0.0.1:60779 - - [07/Apr/2021:12:06:05] "WSCONNECTING /ws/chat/lobby/" In production I'm using an elasticache redis cluster as my channel layer. I can test this in the django shell and it connects/sends/receives. However in the production chat I am unable to reach … -
Tracking date/time of page hits on a Wagtail site
Is there a best practice for tracking page hits in Wagtail (or Django)? I've seen some installable Django modules that track a simple hit count per page, but what I'm looking for is something more like a log of individual hits with the date/time and page URL for each (and possibly other information such as the user's IP address). I could probably build this myself and customize it to meet my app's needs; I'm just unsure of how to set up the model for the hit records in a way that Wagtail doesn't register it as a "page" and make all those individual records editable in the admin, which would be a nightmare. I figure once it's set up, I can build some custom admin logic to generate reports by querying from the database; it's just matter of setting up the data structure properly in the first place. -
url issues with django
I can't get my urls to work for django no matter what I try from django.contrib import admin from django.urls import include, re_path from django.conf.urls import url from catalog import views urlpatterns = [ re_path(r'^admin/', admin.site.urls), re_path(r'^fruit/?$', views.fruit_catalogue, name='fruit_catalogue'), re_path(r'^fruit/?$', views.fruit_details), re_path(r'^fruit/(?P<fruit_id>[1-7]{1})/?$', views.fruit_details), ] -
Grouping and counting Item in my database
I am creating an app that keeps track of stock data. How can I write a query to group any items stored in a column? (ie the name column). Also, I would like to count the grouped items. Any help would be appreciated. class Stock (models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length= 100) quantity = models.IntegerField(defualt=0) price = models.IntegerField(default = 0) -
Extending with plugins remotely -at least from a frontend
Hi guys I have a question just one, but it houses a series of smaller questions for clarity. So I'm building a django app that creates virtual organizations, I'm planning on hosting with digitalocean for reasons. My app just creates a droplet and host a site ( already done that) Now I want my users ( mainly people with zero coding knowledge or ability) to be able to install plugins to their django site using the frontend. How do I get this working without users tampering with the settings.py file is it possible? what packages would I need? how would I setup the installation process? an example would be how shopify handles its plugins and installation from the frontend remotely - if shopify were built on django. Cheers! -
Django admin: custom action template, button to redirect to another admin action
I have a custom action on one of my admin models which renders a view, the 'check' action. This view has two buttons that should call two different actions: 'Approve' and 'Reject'. How do I register these two actions 'Reject' and 'Approve' to be able to redirect from the view to it? When trying to render the html I get the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'reject' not found. 'reject' is not a valid view function or pattern name. template.html <div class="flex" style="justify-content: center"> <button> <a href="{% url 'reject' %}">Reject</a> </button> <button> <a href="{% url 'approve' %}">Approve</a> </button> </div> admin.py @admin.register(Model) class Model(admin.ModelAdmin): def get_urls(self): urls = super().get_urls() my_urls = [ url(r'^(?P<user_id>.+)/check/$', self.admin_site.admin_view(self.check), name='check'), url(r'^(?P<user_id>.+)/approve/$', self.admin_site.admin_view(self.approve), name='approve'), url(r'^(?P<user_id>.+)/reject/$', self.admin_site.admin_view(self.reject), name='reject'), ] return my_urls + urls -
How to Access Data Within Django ManytoMany with SQL Query
I have two models in a Django site as follows, one of which is a many to many relationship: class Seller(models.Model): account = models.ForeignKey(Account, related_name='sellers',null=True, on_delete=models.SET_NULL) bio = models.TextField(null=True, blank=True) city = models.CharField(max_length=50, null=True, blank=True) and class Account(models.Model): username = models.CharField(max_length=50, blank=True, null=True, unique=True) password = models.CharField(max_length=64) name = models.CharField(max_length=50, blank=True, null=True) I am trying to run an SQL query on my Postgresql database, but I cannot find a clear way to to write an SQL query to access information within the many to many relationship. I have the seller ID, and I want to get the username within Account. If I try the following, which clearly is not correct, it won't work but I'm stumped as what to do next: SELECT seller_seller.bio, seller_seller.account.id FROM seller_seller, admin_account WHERE ...no clue! Can someone point me in the right direction? Thank you!