Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
How to serialize a list of data in ManyToMany relantionship in Django RESTful API and properly create nested objects?
i think is a silly question but for few days I cann't hadle with it... I've go a a two models: Book and Authors. Book can have many Authors, and Authors can have many Book(s). I;m POST-ing a new Book, and i'm passing a "title" and a list of Authors (i'm passing a list of dictionaries like in example below). I want to create new Authors from this list but wihout overwriting old ones. models.py: class Authors(models.Model): name = models.CharField(max_length=50, blank=True) class Book(models.Model): title = models.CharField(max_length=60, blank=False, null=False) authors = models.ManyToManyField(Authors) serielizers.py: class AuthorsSerializer(serializers.ModelSerializer): class Meta: model = Authors fields = '__all__' class BookSerializer(serializers.ModelSerializer): authors = AuthorsSerializer(many=True) class Meta: model = Book fields = ['id', 'title', 'authors'] depth = 1 def create(self, validated_data): authors_data = validated_data.pop('authors') book = Book.objects.create(**validated_data) for autor in authors_data: Authors.objects.create(book=book, **autor) return book views.py: class BooksList(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer urls.py: book_list = BooksList.as_view({ 'get': 'list', 'post': 'create', }) book_detail = BookDetails.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'}) authors_list = AuthorsList.as_view({ 'get': 'list', 'post': 'create'}) urlpatterns = format_suffix_patterns([ path('books/', book_list, name='book_list'), path('books/<int:pk>', book_detail, name='book_detail'), path('authors/', authors_list, name='authors_list'), ]) When I'm POST-ing a new object in webrowser in RESTful API like this: { … -
I got an error in my project when I want start django
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> Any Idea? -
Saving to values to model that extends the user model when creating a new record
I have a model that extends the default Django User model. It is intended to store user information pulled from an API, particularly the UUID associated with the user. This is the model: # Django dependencies from django.contrib.auth.models import User from django.db import models class Oid(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) oid = models.UUIDField() class Meta: db_table = 'auth_user_oid' constraints = [ models.UniqueConstraint(fields=['oid'], name='unique_oid') ] This is where to record is being created: # serializers.py email = user_validations['graph_response']['mail'].lower() first_name = user_validations['graph_response']['givenName'] last_name = user_validations['graph_response']['surname'] oid = user_validations['graph_response']['id'] obj, created = models.User.objects.get_or_create( username = email, first_name = first_name, last_name = last_name, email = email, is_staff = True, oid = oid ) The oid = oid is just one of a number of different things I've tried. This iteration in particular just says: ValueError: Field 'id' expected a number but got 'UUID'. I'm just wondering: how an I'm supposed to be saving records to the extended model when a new User record is being created? -
Filtering Datetime field by date not working in Django
I'm trying to filter a Datetime model field by date only and have tried: Content.objects.filter(created_at__date=params.get("event_date")) The event_date parameter is formed like 2021-04-07. I've tried creating a datetime object and have also tried this: search_params["created_at__lte"] = datetime.datetime(int(date[0]), int(date[1]), int(date[2]), 0, 0, 0) search_params["created_at__gte"] = datetime.datetime(int(date[0]), int(date[1])+1, int(date[2]), 0, 0, 0) However, all of these methods return an empty query set and they should return one result. The result has a Datetime field (2021-04-07 23:00).