Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render Data when paginationg pages
I was making a blog app --web . I added some pagination and filtering. Now I will use JavaScript to render the posts i get from my API to the page. So, Do i have to create a specific div for every page and only show one div -- the page that is active-- so when user goes back to the page, i don't have to make API call again. Or when user visits the page he has already visited, do i have to get the data again and then render it, or if I have to cache it . If yes, please suggest the ways i have to do it . My API Code class HomePageAPIView(ListAPIView): queryset = Post.objects.all() serializer_class = PostSerilizer permission_classes = [IsAuthenticated,] pagination_class = PageNumberPagination filter_backends = [SearchFilter,OrderingFilter] ordering_fields = ['posted',] search_fields = ['key_words','author__username',] print(pagination_class) -
How to create a tenant from a django app to another (django-tenant-schemas)?
I have 2 Django projects. One is a CRM and another is a Main Website (on which you buy a subscription to use the CRM). So I came across Django-tenant-schemas https://django-tenant-schemas.readthedocs.io/en/latest/index.html, and I am looking forward to implementing it over the CRM. What is the Problem? If I do implement django-tenant-schemas, and deploy over my DigitalOcean VPC, how can I create a tenant from the Main Website app to the CRM. (Make a tenant for the subscriber once they do subscribe). The architecture I am thinking about is: For every user in the Main Website, a tenant is created. In my particular setup, I have Nginx and Uwsgi. -
Displaying data owned by the current logged in users
While creating API'S I'm using queryset on my model and trying to get only the data owned by the logged in users, but I'm getting some errors. Console Log from . import views File "F:\coding and stuff\finMSG\chatbot\chatbotapi\views.py", line 8, in <module> class queryViewSet(viewsets.ModelViewSet): File "F:\coding and stuff\finMSG\chatbot\chatbotapi\views.py", line 10, in queryViewSet queryset = query.objects.filter(user=self.request.user) NameError: name 'self' is not defined Models.py # Create your models here. # models.py from django.db import models from django.contrib.auth.models import User class query(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) referencetoken = models.CharField(max_length=60) question = models.CharField(max_length=60) def __str__(self): return self.referencetoken Views.py from rest_framework import viewsets from .serializers import querySerializer, BotSocialConfigSerializer, SkillsSerializer, BotsSerializer from .models import query, BotSocialConfig, Intents, Skills, Bots from rest_framework.permissions import IsAuthenticated # Create your views here. class queryViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = query.objects.filter(user=self.request.user) serializer_class = querySerializer How can I get data only for user that is currently logged in. -
Can't retrieve Token in Django model
I am trying to retrieve Token from rest_framework.authtoken.models as there is token created for user when he/she signs up. (It can be seen in my django admin panel in the picture below). I am facing issue as trying to get Token in my Django model to create profile for user. Error is: rest_framework.authtoken.models.DoesNotExist: Token matching query does not exist. What causes error? My models.py file is here: from django.contrib.auth.models import User from rest_framework.authtoken.models import Token class Profile(models.Model): user = Token.objects.get(key='token string').user bio = models.CharField('Bio', max_length=100) def __str__(self): return f'{self.user.username} Profile' Picture of Django admin panel and user Tokens: Screenshot -
Django relation with pivot table
I have three tables Product (Columns: Id, Name, Description, Price ...) Product Image (Id, Product Id, Image Id) Image (Id, Path) Product Image (Pivot table) Model: class ProductImage(models.Model): id = models.BigAutoField(primary_key=True) product = models.ForeignKey(Product, models.DO_NOTHING) image = models.ForeignKey(Image, models.DO_NOTHING) I want to make connection between Product and Image. In Laravel (php framework) it is simple to do it withPivot method. How i can do it with django? How can i take image data in Product model via pivot table. -
How to deploy Django project on Windows server?
It is required from me to deploy my Django application on local Windows server within company where I work with mssql database. I want to know is it possible ? Because all tutorials on web shows deploying on linux or debian server, and I don't know where to start, where to configure my project. Please help me if you know some sources. -
Django using VS2019 - inspectdb
So I have a simple Django project up and running in VS2019. I've right clicked on my project Environment --> Manage Python Packages and added django-pyodbc-azure I've updated my databases settings to: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': 'SQLServerName', 'NAME': 'DBName', 'USER': 'SQLUserName', 'PASSWORD': 'UserPassword', }, That works, I can run the project with no problems. So my next step is to try and use inspectdb so that I can update my models. If I open a command prompt and run: py --version it tells me I'm running python 3.7.8. If I create a simple python file that prints out 'hello world' and run it it works. If I navigate to my project where 'manage.py' is located and run: python manage.py inspectdb it doesn't work and I get the error: Traceback (most recent call last): File "manage.py", line 17, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 23, in ) from exc 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? if … -
Django_Filters :no need to show all items using object.all() at the first load
I am new for Django_Filter As I notice, django_filter always loads all objects on the firs loading despite not filtered yet. Due to a large amount of data in datable in the database so it results in poor performance for loading all objects. it is rather non-sense in my view. Thus the better way it should only filter a result whenever click button. How to set Django_Filter in order to show the result when only click the search button(I don't want to list all items by using objects.all()). These are my code related to this problem model.py from django.db import models class Product_Type(models.Model): productype_name=models.CharField(max_length=100) class Inventory(models.Model): serial_number=models.CharField('Serial Number',max_length=50) product_type=models.ForeignKey( Product_Type,on_delete=models.CASCADE,verbose_name='Product Type') filter.py import django_filters from django_filters import * from app.models import * class InventoriesForCopy_Filter(django_filters.FilterSet): class Meta: model=Inventory fields=['product_type','serial_number'] views.py def list_inventory_for_copy(request, proj_id): inventories_all = Inventory.objects.all() xfilter = InventoriesForCopy_Filter(request.GET, queryset=inventories_all) inventories = xfilter.qs context = {'project_id': proj_id, 'xfilter': xfilter, 'inventories': inventories} return render(request, 'app/inventory_add_copy.html', context) inventory_add_copy.html {% extends "app/layout.html" %} {% block content %} {% if messages %} <ul> {% for message in messages %} <li><strong>{{ message }}</strong></li> {% endfor %} </ul> {% endif %} <form method="get"> {{xfilter.form}} <button type="submit">Get Inventories</button> </form> Create Inventory for Project ID : {{ project_id }} … -
Find End Date If We Have Start Date and Interval . Excluding custom holiday list and weekends . In Python(Django)
So, What I am trying to achieve is. start_date = "2020-07-16" number_of_days = 15 holidays = ["2020-07-19",2020-07-21] Now I Want to calculate the end date i.e 16 Aug + 15 days excluding all custom holidays which I give in the list and all the weekend's(Sundays+Saturdays). Any suggestions on how could I achieve it. The solution I found till now is this using NumPy but it doesn't fulfill my requirements. -
How to create tables without creating an app in Django
When I am creating a new Django project and migrate it then there I found some following tables created Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying sessions.0001_initial... OK Is there any way to create extra tables by defining models.py file in the main root directory of Django?..Here I don't wanna create an app for some models class so. -
Access postgresql inside a docker compose using pgadmin4
I have a django project in a docker compose and it uses postgresql database. My django settings: DATABASES = { 'default': { 'ENGINE':'django.db.backends.postgresql', 'HOST':os.environ.get('DB_HOST'), 'NAME':os.environ.get('DB_NAME'), 'USER':os.environ.get('DB_USER'), 'PASSWORD':os.environ.get('DB_PASS'), } } how do I access the db set inside docker-compose in pgadmin4. or do I have to configure pgadmin4 inside docker. -
Incrementing model value at midnight in Django
I want to increment the value days_till_study with 1 everyday at midnight. My current approach is not very elegant. Is there a better way to do this? from django.db import models from django.utils import timezone class Card(models.Model): question = models.CharField(max_length=100) answer = models.TextField() date = models.DateTimeField(default=timezone.now) creator = models.ForeignKey(User, on_delete=models.CASCADE) decks = models.ManyToManyField(Deck) days_till_study = models.IntegerField(default=1) def __str__(self): return self.question def decrement_days_till_study(self): if days_till_study < 1: x = str(datetime.datetime.now()) if x[x[11:26]] == '00:00:00.000000': days_till_study += 1 Thanks for reading this. -
Operational error at / no such table: tasks_task even after creating a table
Here is my html file of landing page. {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/base.css' %}"> </head> <body> <div class="center-column"> <form method="POST" action="/"> {% csrf_token %} {{form.title}} <input class="btn btn-info" type="submit" name="Create Task"> </form> <div class="todo-list"> {% for task in tasks %} <div class="item-row"> <a class="btn btn-sm btn-info" href="{% url 'update_task' task.id %}">Update</a> <a class="btn btn-sm btn-danger" href="{% url 'delete' task.id %}">Delete</a> {% if task.complete == True %} <strike>{{task}}</strike> {% else %} <span>{{task}}</span> {% endif %} </div> {% endfor %} </div> </div> </body> </html> Here is Models.py file where a table is created class Task(models.Model): title = models.CharField(max_length=200) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title Error i am getting OperationalError at / no such table: tasks_task C:\Users\91870\Desktop\Django\todo\tasks\templates\tasks\list.html, error at line 15 line 15 is {% for task in tasks %} here is views.py file def index(request): tasks = Task.objects.all() form = TaskForm() if request.method =='POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') return render(request, 'tasks/list.html', {'tasks':tasks, 'form':form}) It was working when i haven't applied the css but now it isn't. Can someone please help me with this -
How to use JSONField with react from django rest api?
I'm using django rest api with PostgreSQL as a backend for my react app. The problem is I can't read JSONField properly. For example, I have the following field { "id": 4, "tag": "h1", "text": "test styling", "src": "", "style": "{color:'red'}", "main": null, "sub": [] } and when I try to read it in my react app as showing here {data.map(i=> <div style={i.style} > {i.text} </div> )} that cause an error says Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. See fb.me/react-crossorigin-error for more information. I also i tried style={JSON.parse(i.style)} and I tried to reformat my field to be {'color':'red'}, but that didn't work. So how can I read my such data as a json? or how can I convert it to json? -
Permission denied Python installing using pip
ERROR: Error [Errno 13] Permission denied: '/vagrant/.venv/bin/python' while executing command python setup.py egg_info ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/vagrant/.venv/bin/python' Consider using the `--user` option or check the permissions. I get this error when I try to install a package, but if I use --user, I get a different error saying: ERROR: Can not perform a '--user' install. User site-packages are not visible in this virtualenv. My venv is activated -
matchlist listings by a player
I am using riot api to gather information about players matches to do that I get matchlist from an id of a player then I get like 600 played matches from a player and then save those 600 played matches as an object of a model in django The problem is after I get other matchlist from another player and save those matches from the second player how do I reach out the first player matches since both matchlist matches are saved as objects. -
how to unique id generator in django
i want to generate an unique id code in my model for example id want to generate i did not understand how to do it actually i am not from it industry, yet i am trying to make a software can anyone explain me or give me a link where i could find / read all this? class parameter(models.Model) name=models.models.CharField(max_length=50) type=model.#should come from another table subtype=model.#should come from another table id= # should compile all the above as in picture thanks -
Deploy Django/VueJs App on Heroku keeps failing with error main.js module not found
I am trying to deploy an app i built with django backend serving API's to a Vue.js frontend to Heroku. Everything works well locally. On Heroku, i have done the setup by adding heroku/nodejs and heroku/python buildpacks. I have also added my app Config Var secret key on heroku settings. My vuejs frontend package.js script looks like this; "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": "vue-cli-service lint", "postinstall": "npm run build", "heroku-prebuild": "export NPM_CONFIG_PRODUCTION=false; export NODE_ENV=; NPM_CONFIG_PRODUCTION=false NODE_ENV=development npm install --only=dev --dev", "heroku-postbuild": "npm run prod", "start": "npm run dev" }, When i try to push to heroku with git push heroku master, the build fails with error that the main.js module was not found. However, there is main.js file in my frontend. While googling about this issue, i saw a similar issue which turned out to be that the entry in webpack config file was not set, but in my own case, in webpack.js i have entry set like so; entry: { app: [ './src/main.js' ] } I have also re-installed all my modules as suggested in one of the help resources, still it doesn't resolve the issue. Here is a full trace of the build error; … -
User has no customer in Django?
I am getting this error User has no customer, i am getting this error when i am creating the order, and if i logout and create new user account with different mail id, then this error comes. Please let me know what is the mistake. here is my code.. def cartData(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: cookieData = cookieCart(request) cartItems = cookieData['cartItems'] order = cookieData['order'] items = cookieData['items'] return{'cartItems':cartItems, 'order':order, 'items':items} -
DRF how to create dublicate(copy) of instance endpoint?
My models: class Book(models.Model): user = models.ForeignKey(User, models.CASCADE, related_name="books") name = models.CharField(max_length=255) My view: class BooksViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): permission_classes = (IsAuthenticated,) serializer_class = BookSerializer def get_queryset(self): return Book.objects.filter(user=self.request.user) @action(methods=['POST'], detail=False) def dublicate(self, *args, **kwargs): serializer = serializers.BookSerializer(data=self.request.data) serializer.is_valid(raise_exception=True) My idea is I want to use @action to dublicate some Book objects by id, with all info that Book model have just copy it. How to do it in a right way? -
Getting a typeError error in django project [closed]
I created a virtual environment for my new project, installed django and started the new project. However, whenever i run a line of code with manage.py i get this long error. PS D:\My stuff\Website development\Isow website\isow> python manage.py makemigrations No changes detected 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:\Users\rahma\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\rahma\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\rahma\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 336, in run_from_argv connections.close_all() File "C:\Users\rahma\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\utils.py", line 224, in close_all connection.close() File "C:\Users\rahma\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 248, in close if not self.is_in_memory_db(): File "C:\Users\rahma\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 367, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\rahma\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable -
Django detail view, without parameter in url
i am trying to use session parameters for detail, list, delete views instead pass parameter throught URL. Now i have problem when I am in list view i need to find which object is clicked and get that object id. Is ir possile in django list view to find which object is clicked and pass id througt session variable? class TripDetailView(LoginRequiredMixin, DetailView): def get_object(self): return get_object_or_404(Trip, pk=self.request.session['trip_id']) class TripListView(LoginRequiredMixin, ListView): model = Trip paginate_by = 10 def get_context_data(self, **kwargs): global user_id a = self.request.session.get('user_id') # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books user_id = a context['user'] = user_id context['usertrips'] = Trip.objects.filter(user_id=a) self.request.session['trip_id'] = '????????' return context List view and I need to find in list view which is clicked and get id -
Exclude a QuerySet from a QuerySet in many to many relationship
I have these models: class Word(models.Model): word = models.CharField(max_length=64, primary_key=True) class Pack(models.Model): pack_name = models.CharField(max_length=64, primary_key=True, default='Repository') words = models.ManyToManyField(Word) number_of_words = models.IntegerField(default=0) I have several Pack within which there are several words added. I want to make a list of all words except ones that are added inside a specific Pack, namely "Others"; i.e. I want do something like this: otherPackModel = Pack.objects.get(pack_name="Others") wordModels = Word.objects.all().exclude(otherPackModel.words) wordlist = wordModels.values_list('word', flat=True) -
Djongo nested document serializer problem
i want to store json files in mogodb, create and get with django rest framework. i share my code below. this code insert posted data into mongo. but when i 'get' data, nested object represent as string. i create nested model's serializer and define in Root serializer but i get error "Cannot use ModelSerializer with Abstract Models." i want to get object as json.enter image description here i reseached a lot but i haven't found anything about this. /*Djongo nested document serializer problem*/ i want to store json files in mogodb and create and get with django rest framework. i share my code below. this code insert posted data into mongo. but when i 'get' data, nested object represent as string. i want to get object as json. i reseached a lot but i haven't found anything about this. ###########################models.py######################## from djongo import models class Nest(models.Model): name = models.CharField(max_length=150, blank=True, null=True) icon = models.CharField(max_length=150, blank=True, null=True) class Meta: abstract = True class Root(models.Model): #_id = models.ObjectIdField() country = models.CharField(max_length=200, blank=True, null=True) country_code = models.CharField(max_length=5, blank=True, null=True) nested = models.EmbeddedField( model_container=Nest, null=True) ###########################serializers.py##################### from rest_framework import serializers from .models import Root class RootSerializer(serializers.ModelSerializer): class Meta: model = Root fields = '__all__' … -
'detail' is not a valid view function or pattern name. Ref: The easy way 3rd edition
https://paste.artemix.org/-/dkFbxg is the error I am getting. I am new in django so pardon me if I was not able to follow already available suggestions on stackoverflow.com mysite/urls.py from django.contrib import admin from django.urls import path, include # < here import blog.views # < here urlpatterns = [ path('', blog.views.home, name='home'), # < here path('admin/', admin.site.urls), path('blog/', include('blog.urls')), # < here ] views.py from django.shortcuts import render from django.shortcuts import render, get_object_or_404 # < here from .models import Post # < here def home(request): # < here posts = Post.objects.all() # < here return render(request, 'home.html', { 'section': 'home', 'posts': posts, # < here }) # < here def detail(request, slug=None): # < here post = get_object_or_404(Post, slug=slug) return render(request, 'blog/detail.html', {'section': 'blog_detail', 'post': post, }) home.html {% extends "base.html" %} {% block content %} {% for post in posts %} <a href="{{ post.get_absolute_url }}"> <!-- here --> {{ post.pk }} : {{ post }} </a> <br> {% endfor %} {% endblock %} base.html <!doctype html> {% load static %} <!-- here --> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="{% static 'css/base.css' %}"> <!-- here --> <title>Site</title> </head> <body> <ul class="menu"> <li> <a class="{% if section == 'home' %}active{% …