Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
append to request.sessions[list] in Django
Something is bugging me. I'm following along with this beginner tutorial for django (cs50) and at some point we receive a string back from a form submission and want to add it to a list: https://www.youtube.com/watch?v=w8q0C-C1js4&list=PLhQjrBD2T380xvFSUmToMMzERZ3qB5Ueu&t=5777s def add(request): if 'tasklist' not in request.session: request.session['tasklist'] = [] if request.method == 'POST': form_data = NewTaskForm(request.POST) if form_data.is_valid(): task = form_data.cleaned_data['task'] request.session['tasklist'] += [task] return HttpResponseRedirect(reverse('tasks:index')) I've checked the type of request.session['tasklist']and python shows it's a list. The task variable is a string. So why doesn't request.session['tasklist'].append(task) work properly? I can see it being added to the list via some print statements but then it is 'forgotten again' - it doesn't seem to be permanently added to the tasklist. Why do we use this request.session['tasklist'] += [task] instead? The only thing I could find is https://ogirardot.wordpress.com/2010/09/17/append-objects-in-request-session-in-django/ but that refers to a site that no longer exists. The code works fine, but I'm trying to understand why you need to use a different operation and can't / shouldn't use the append method. Thanks. -
O365 API, python sendmail:: Throttle Error: Application is over its IncomingBytes limit
I'm receiving this throttling error and there is no mention anywhere regarding why this error occurs. Error Message: Application is over its IncomingBytes limit. Can someone please help me. -
DRF copy object with FK
My model class Book(models.Model): user = models.ForeignKey(User, models.CASCADE, related_name="books") name = models.CharField(max_length=255) shop = models.ForeignKey(Shop, models.CASCADE, related_name="shops") My view: @action(methods=['POST'], detail=True) def dublicate(self, request, *args, **kwargs): book_instance = self.get_object() book_instance.pk = book_instance.id = None book_instance.save() return Response(self.serializer_class(book_instance).data) How can I also copy all FK that my current model have , like shops? -
problem with django form when set instance parameter and has file field - django form
my django form has a logo_path fields that is image field. when i want edit my object i have this problem : if i don't get request.FILES to form form = CompanyForm(request.POST,request.FILES or None,instance = company) image field doesn't edited. and if else i get request.FILES to form class form = CompanyForm(request.POST or None,instance = company) other fields become empty in my html form. this my code in view: company = Company.objects.get(id=id) form = CompanyForm(request.POST,request.FILES or None,instance = company) if form.is_valid(): form.save() messages.success(request, 'ویرایش با موفقیت انجام شد.') return redirect('./') context = { 'form' : form } return render(request,"staff/companies/store.html",context) and this is my code in django form : class CompanyForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'عنوان'})) commission = forms.DecimalField(widget=forms.TextInput(attrs={'placeholder':'کارمزد'})) class Meta: model = Company fields = [ 'title', 'commission', 'type', 'logo_path', 'is_active' ] def __init__(self, *args, **kwargs): super(CompanyForm, self).__init__(*args, **kwargs) self.fields['logo_path'] = "http://app.fara-ertebat.ir/static/%s"%(self.fields['logo_path']) -
query top seller products in django
i have two models like this class Product(models.Model): title = models.CharField(max_length=100) class Order_item(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) quantity = models.PositiveSmallIntegerField(default=0) order = models.ForeignKey(Order, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True) now i want to query "top 10 most seller products between date x and y" from Order_item. how should i do? -
Auto-generated field 'contactinformation_ptr' clashes with declared field of the same name
django.core.exceptions.FieldError: Auto-generated field ‘contactinformation_ptr' in class 'ContactEmail' for parent_link to base class 'ContactInformation' clashes with declared field of the same name. enter image description here ..I have followed all the steps from this article.. https://www.kidstrythisathome.com/2016/10/wtf-django-moving-models-part1.html.. ..also tried deleting all migrations and creating new migrations...but still facing same error -
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}