Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to append data in django import?
I am uploading excel files through Django import. Whenever I import new files the existing rows are replaced with the new imported data. But I need the existing data as it is and the I want the new rows to be appended to the existing rows. How can we achieve this? Thanks -
Login through iframe on multiple websites
Suppose there is a master site A with the domain www.a.com. Two other websites B (domain: www.b.com) & C (domain: www.c.com ) are accessing a particular resource from A via iframe. Now one of my requirement is that, Case 1: The user logs in through website A he is automatically signed in on every iframe of A if the user visits site B or C. Case 2: The user logs in through one iFrame of either B or C, then the user is automatically logged in every iframe and also website A. Example - Disqus Login How can I go about it? Some answers suggested I look at OAuth, but in OAuth user still has to authorize every time they visit a new website. Unfortunately I am not allowed to do that. Another thing I looked at was Single Sign On but I don't know how to get it to use. My stack is Python-Django in the backend, Vanilla JS in the front-end. -
Error loading image filepath from the database in django
i am starting to use django and i have a little mistake in some of my code but i dont know where is it. I am trying to load a image from my database in a filepath. This a part from my models.py that i am using to load the image: class Articulo(models.Model): ... nombre_imagen=models.CharField(max_length=64) As you can see, i am loading the image from a filepath in my database. And this is the part of the code that i am trying to do that: {% if articulo %} {% for articulo in articulo %} .... <a href="#"><img class="card-img-top" img src="{% static '{{articulo.nombre_imagen}}'}" alt=""></a> ..... {% endif %} The image is located in the static files: STATIC_URL = '/static/' I think there is a stupid problem, but as i said before. I am new at django. I hope that anyone can help me, thank you!. -
How to take all the values in a list and group by year and place 0 in list if there is no value for that specific year using group by in Django ORM?
I have two models. One is Branch with branch_id and branch_name fields and Another is Sales with sales_amount and year field. Branch and Sales have a ForeignKey relationship. A Branch can have multiple Sales. What I'm trying to achieve is to group by with year where each year has its sales value. And get the dictionary of key(Branch name) and values(sales_list) If there are no sales for that year then there should be value '0'. models.py import datetime from django.db import models class Branch(models.Model): branch_id = models.IntegerField() name = models.CharField(max_length=50) def __str__(self): return self.name class Sales(models.Model): branch = models.ForeignKey('Branch', on_delete = models.CASCADE) sales_amount = models.IntegerField() year = models.CharField(max_length=4) class Meta: unique_together = (('year', 'branch'),) def __str__(self): return self.branch.name views.py from django.shortcuts import render import json from .models import Branch, Sales def index(request): branches = Branch.objects.all() sales = Sales.objects.all() sales_list = [] branch_list = [] year_set = set() for sale in sales: year_set.add(sale.year) year_list = list(sorted(year_set)) for branch in branches: sales_list.append(branch.sales_set.all().order_by('year')) branch_list.append(branch.name) sales_list = [[j.sales_amount for j in i] for i in sales_list] branch_dict = dict(zip(branch_list, sales_list)) return render(request, 'index.html', { 'year_list': year_list, 'branch_dict': branch_dict }) I've BRANCH001 with the year 2011 has 5000 sales, BRANCH001 with the year 2012 has … -
I want to upload a image from web page ,it does not go to media directory
When I upload the image from admin panel it goes to http://127.0.0.1:8000/media/shop/images/Digital_India_empower_youth.jpg but when I upload from web page it shows uploaded with name in admin panel and no directory displayed and does not show in directory of project models.py class Product(models.Model): product_id = models.AutoField product_name = models.CharField(max_length=50) category = models.CharField(max_length=50,default="") price = models.IntegerField(default=0) desc = models.CharField(max_length=300,default="") image = models.ImageField(upload_to='shop/images', default="") def __str__(self): return self.product_name views.py def product(request): if request.method=="POST": name=request.POST.get('name','') category=request.POST.get('category','') price=request.POST.get('price','') desc=request.POST.get('desc','') image=request.POST.get('image','') product= Product(product_name=name,category=category,price=price, desc=desc,image=image) product.save() #chk=True return render(request,'shop/sell.html') sell.html <div class="form-group"> <label for="price">Price</label> <input type="text" class="form-control" id="price" name="price"placeholder="100"> </div> <div class="form-group"> <label for="desc">Description</label> <input type="text" class="form-control" id="desc" name="desc" placeholder="Write few things about books"> </div> <div class="form-group"> <label for="image">Upload Image</label> <input type="file"id="image" name="image"> </div> <button type="submit" class="btn btn-primary">Sell</button> </div> -
Django Template Date filter not working on Pandas Datetime Index in Table
I am not able to format a date using the Django filter. Anything I add results in nothing, example: month|date:"M-Y" I am passing in a dataframe after doing a groupby. df2 = df.groupby(pd.Grouper(freq="M"))[["gross", "net"]].sum() gross net month 2013-02-28 2570.33 1105.20 2013-03-31 8964.05 2041.51 2013-04-30 4763.38 2048.15 The context being passed. context = { 'title' : '{} Analysis'.format ( p.name ), 'data' : df2.to_records () } It is a simple table, but if I add any date filter to the i.month - I get nothing. {% for i in data %} <tr> <td>{{ i.month }}</td> <td>{{ i.gross|floatformat:"0"|intcomma }}</td> <td>{{ i.net|floatformat:"0"|intcomma }}</td> </tr> {% endfor %} This is the none filtered output. I have never had such a problem before formatting a date. is it because it is the index value? Thanks so much. -
Django, find rows that references to same id via foreign key multiple times? [duplicate]
This question already has an answer here: Find Django model records that have more than one 'child' objects? 1 answer Suppose order has foreign key to user. I want list all users that have more than 1 order pointing to him -
How can I add users to different groups without using the AdminDjango
How can I add users to different groups without using the Admin, I understand I have three types of users who choose what type they want to be at the time of registration, I already have the groups created with the different permissions, my question is as when I create the users through the registration plate, I also add them to the group that corresponds to it ??? -
Is using prefetch_related to retrieve related (parents, children pages) possible?
The problem I am facing is duplicate number of queries which makes the app slow when using get_parent() or get_children() on Page model. which also increase if the parent page has an image file that is used in the template. so I am looking for a way to prefetch_related pages without making a foriegn key relation. let us say I have a TvSeries Page model and an Episode Page model: class TvSeries(Page): name = models.CharField() producer = models.CharField() subpage_types = ['Episode'] class Episode(Page): title = models.CharField() number = models.CharField() parent_page_types = ['TvSeries'] How to reduce the database calls? Is it possible to use prefetch and select related ? if yes how?. and if not, what is the solution to the increased number of queries? -
How to perform calculation on a model attribute with input for form in django
I'm new to Python/ Django here, but working hard To train myself, I'm working on a simple View that would -take input through a form (DecimalField) -Pass it to the View, where it perform calculation based on my Class Method -Display it on my template, below to the InputForm itself and next to my other Class/Object attributes So far, I've manage to create a ModelForm that build Objects with attributes , save them into sqlite3 and display them in a template with a {for in} loop in the end, my template would look like : {% for list in list %} {{ list.price }} {{ list.newprice}} with the css I'm already using of course Models: class Product(models.Model): cost = models.DecimalField(decimal_places=2, max_digits=5) price = models.DecimalField(decimal_places=2, max_digits=5) def __str__(self): return self.sku def newprice(self, input): newprice = self.price * input return newprice Form: class MultiplierForm(forms.Form): multiplier = forms.IntegerField(label='Your cost') View: (this is where I'm confused) def index(request): form = MultiplierForm(request.POST or None) list = Product.objects.all() if request.method == "POST": <insert code here> return render(request, 'inventory/template.html', {'form': form, 'list': list,},) What would be the most simplistic code you could think about ? thanks -
"Permission denied" Error in Django Application Deployed on Amazon Elastic Beanstalk
I have deployed a Django project (MyProj) to Amazon beanstalk using the eb CLI. This project is physically located at ~/MyProj. It has an app, named myapp, which needs to execute external python scripts. For this purpose, I have my_launcher.py in ~/MyProj/myapp directory. A code snippet in my_launcher.py is: import os import importlib PROJECTS_DIR = os.path.join(os.path.expanduser(os.environ.get('LOCATION')), 'app/python/') MY_MODULE = os.path.join(PROJECTS_DIR, 'MyModule/my_script.py') spec = importlib.util.spec_from_file_location('my_script', My_MODULE) MyModule = importlib.util.module_from_spec(spec) spec.loader.exec_module(MyModule) The reason for using the environment variable LOCATION is to dynamically set the location of external python scripts. I have defined this environment variable and some others through the AWS admin console under the Elastic Beanstalk section. In my example, I have: LOCATION = '/home/ec2-user/company/' This script fails at the last line with the error: PermissionError at /myapp [Errno 13] Permission denied: '/home/ec2-user/company/app/python/MyModule/my_script.py' The things I have done so far to no avail: After reading many online pages (e.g., Django [Errno 13] Permission denied: '/var/www/media/animals/user_uploads'), I thought the issue is Linux permissions on the location where the executable python scripts are (i.e., /home/ec2-user/company/app/python/). For the sake of testing this hypothesis (even though I know it is a bad approach for production), I ran the command sudo chmod -R 777 company while … -
Multiple database on login Django
i have an App that using a DB(default) now the problem is the client need multiple Factory. One DB for one Factory, The idea is when the client login select the Factory write the user and password and redirect to the data of the factory selected. The problem is how switch the respective DB as principal when the user login. i read the Documentation but dont talk about this topic, please any suggest i don't know by where start..!! -
Issue with Herioku and Weasyprint
I have read old post about compatibility issues with weasyprint on Heroku. I am using Weasyprint with Django application. Are there any current issues with using Django Weasyprint application deployed on Herouk? -
Django Rest Framework ListSerializer Child AssertionError
I am trying to do an a multiple update on a model and got the following error: Serializers with many=True do not support multiple update by default, only multiple create. For updates it is unclear how to deal with insertions and deletions. If you need to support multiple update, use a ListSerializer class and override .update() so you can specify the behavior exactly. So I wrote the following code to test this out: class TypeSerializer(serializers.ModelSerializer): class Meta: model = Type fields = ('name',) class LabelSerializer(serializers.ListSerializer): type = TypeSerializer() uuid = serializers.UUIDField() is_active = serializers.BooleanField() entity = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Label fields = ('uuid', 'type', 'is_active', 'entity') class ClothingSerializer(serializers.Serializer): clothing_items = ClothingItemDetailSerializer(many=True) labels = LabelSerializer(many=True) When I run this I get the following error: assert self.child is not None, 'child is a required argument.' AssertionError: child is a required argument. I looked through the documentation and source code for ListSerializer and can't seem to figure out why this error is happening. It seems to be triggered by the call to the ListSerializer in the ClothingSerializer class. In the source code to ListSerializer, it expects a variable called "child" to exist (possibly by being passed during instantiation) but I'm not … -
Django Rest Framework, token authentication: request.user returns AnonymousUser
I am trying to use Token Authentication from Django Rest Framework. I followed all the instruction such as: 1. Adding these lines into installed apps: 'rest_framework', 'rest_framework.authtoken', 2. Adding statement into settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } I am sending HTTP request with header 'Authorization': 'Token token_name', where token_name is token of corresponding user which I can see in a database. On a server, request.user still returns AnonymousUser and request.user.is_authenticated is False. What can be the issue ? -
Why does NGINX not find new static django files when putting up a new build?
I'm running a Django application in Docker with NGINX, and Gunicorn on Ubuntu Server. It is a fairly large 'legacy' project so I am not the one who configured it. Why do I have to run docker-compose down before running docker-compose up -d to reflect the changes I have made to Django's static files? The docker file runs django's CLI command to collect the static files across project directories. In both cases I ran docker-compose build before putting up or taking down. Stopping the NGINX container first, and then putting up the container seemed to allow NGINX to find static files but why was NGINX unable to serve files added to another container? Thanks! -
How to use django-ckeditor to specify different image upload paths for different models ?
The usual practice is to define CKEDITOR_UPLOAD_PATH = 'uploads/' in settings.py.But this will save the images in all models in a unique path.Is it possible to assign a different image path to each model? ‘’‘python class BlogModel(models.Model): ...... content = RichTextUploadingField() # image upload to /media/blog/ class NewsModel(models.Model): ...... content = RichTextUploadingField() # image upload to /media/news/ ’‘’ -
what are django channels InMemoryChannelLayer limitations
i'm learning to use channels (Django channels), and i don't want to install Redis or any other tool. can i just use InMemoryChannelLayer in production ? what are the limitations when using InMemoryChannelLayer ? is there a way to use a Django model for saving channel layers ? -
Given a queryset of objects, for each one, how can I find the set of all objects that ForeignKey to that object?
I have: class Teacher(models.Model): name = models.CharField(...) ... class Student(models.Model): age = models.IntegerField(...) teacher = models.ForeignKey(Teacher, ...) ... I have a queryset of teachers: teachers = Teacher.objects.filter(name="Betty") I want to find all of the students related to each teacher in that queryset, and I need the result to be grouped by teacher. Something like: { <Teacher: 1>: [<Student: 1>, <Student: 2>], <Teacher: 2>: [<Student: 3>, <Student: 4>] } I could accomplish this by just looping over every object in the teachers queryset and filtering Students by students that ForeignKey to that teacher, but that seems really slow and would require an additional DB call for each object. Is there any way to accomplish this in just one or a few DB calls, ideally while staying Python-only and not resorting to SQL? -
“viewed” attribute in Django Rest framework
I use below solution to check is the user viewed the post or not. Best way to make "viewed" attribute for messages inside user group? and in django-rest-framework, i create a ListApiView to get all posts: class PostListView(ListAPIView): serializer_class = PostSerializer permission_classes = (IsAuthenticated, ) pagination_class = PostListPagination def get_queryset(self): return Post.objects.filter(state='published').order_by('-created') and the serializers: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields= '__all__' now i want a boolean field named "viewed" for each post in PostListView to show that is the authenticated user viewed this post or not. something like this: class PostSerializer(serializers.ModelSerializer): viewed = serializers.BooleanField(read_only=True) class Meta: model = Post fields= '__all__' def check_is_viewed(current_user, post_instance): # if user viewed this post: viewed.value = True # else: viewed.value = False -
Converting a dynamic (more specifically a Django) application to become a static website
So I need to create a static copy of of a web application! More specifically I have to flatten a Django web application to become static. The worst possible scenario in my case would be for me to manually make the entire web application static... I was wondering if anyone could give me any advice/resources/articles on how I could tackle this before I dive right into the doing. Thank you so much! -
In Django how can I influence the connection process to the DB?
What is the best method to change the way how django connects to the DB (i.e. MySQL)? For instance what should I do if I needed django to connect to the db via ssh tunnel, whose settings may change dynamically? I understand I should sub-class the django.db.backends.mysql.base and probably modify the get_new_connection(self, conn_params)? But then how would I submit this custom class in the settings, as it seems that the settings expect path to the module, rather than the class? -
Security Failure on django_language cookie
I ran a Pentest-Tools security audit on my website and am getting a warning that the "django_language" is missing flags "Secure, HttpOnly". I'm not really even sure what this cookie is or where it's set, but would like to clear these errors. I set the following in the Settings.py file, but to no affect SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True Is there a way to set this in the Django project? -
What does the "context" argument to the render() function in Django do?
I am working through the basic Blog tutorial on Django and After creating an app I have to add it to the veiw, What I don't understand is what the render functions' argument CONTEXT is for, and why are we using a dictionary. I have already been through the official documentation but I couldn't understand it. Here's what I am doing. render(request,'users/register.html', { 'form': form}) -
Errors when creating django project in pycharm
I am a beginner in python and pycharm, I want to create a Django project under pycharm but when I click on the create button I got this errors: knowing that I am using the latest version of pycharm (2019.1) Error creating Django application: Error on python side. Exit code: 1, err: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "E:\django_app\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "E:\django_app\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "E:\django_app\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "E:\django_app\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "E:\django_app\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\hanan\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "E:\django_app\venv\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "E:\django_app\venv\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "E:\django_app\venv\lib\site-packages\django\db\models\base.py", line 117, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "E:\django_app\venv\lib\site-packages\django\db\models\base.py", line 321, in add_to_class value.contribute_to_class(cls, name) File "E:\django_app\venv\lib\site-packages\django\db\models\options.py", line 204, …