Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
create help text for a field dynamically
I have my response form and view like this class ResponseForm(ModelForm): class Meta: model = ResponseModel exclude = ('author', 'title','submit_count') # help_texts = { # 'ans1': user.q1.value, # } @login_required def ResponseFormView(request): if request.method == "POST": form = ResponseForm(request.POST) if form.is_valid(): submission = form.save(commit=False) submission.author = request.user submission.save() return render(request, 'thanks.html', {}) else: form = ResponseForm() return render(request, 'response_tem.html', {'form': form}) I want the help text for 'ans1' field to be the value of q1 field of request.user. How do I do it? -
TypeError: create() got multiple values for keyword argument 'user'
I'm sending post request from reactJS to Django rest to create post, but I'm getting this error. TypeError: create() got multiple values for keyword argument 'user' Everything is working fine except when i send user to project serializer. I'm saving my user in localstorage to get userId. Please someone help me to solve this issue. This is my data formate post.js class PostProject extends Component { state = { controls: { title: { elementType: 'input', elementConfig: { type: 'text', placeholder: 'Cafe Management System' }, value: '' }, price: { elementType: 'input', elementConfig: { type: 'text', placeholder: '100' }, value: '' }, description: { elementType: 'input', elementConfig: { type: 'text', placeholder: 'Description about your project' }, value: '' }, }, user: null, modules: [], technologies: [], requirements: [], tags: [] }; submitHandler = (event) => { event.preventDefault(); const user = localStorage.getItem('userId'); this.setState({ user: user }) //Get data from state for (let el = 0; el < this.props.modules.length; el++) { const obj = { project: this.state.controls.title.value, name: this.props.modules[el] } this.setState({ modules: this.state.modules.push(obj) }) } for (let el = 0; el < this.props.technologies.length; el++) { const obj = { project: this.state.controls.title.value, name: this.props.technologies[el] } this.setState({ technologies: this.state.technologies.push(obj) }) } for (let el = … -
django-import-export - incorrect xls output file format
django-import-export 1.1.0 I'm trying to export data in .xls format but output file format is incorrect, it looks like this: Here is my view: class ExportItemReportsAPIView(APIView): authentication_classes = (SessionAuthentication, ) permission_classes = (IsAuthenticated, ) def get(self, request, *args, **kwargs): reports = ItemReport.objects.all() reports_resource = ItemReportResource() dataset = reports_resource.export(queryset=reports).xls response = HttpResponse(dataset, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="item_reports.{}"'.format(xls) return response For .csv all is fine. Any suggestions how to fix it? -
AttributeError: 'AppConfig' object has no attribute 'urls'
Issue Summary Installed django-oscar sandbox app successfully but getting a small error in django-oscar/sandbox/urls.py at the line url(r'^', include(apps.get_app_config('oscar').urls[0])), Error Message: AttributeError: 'AppConfig' object has no attribute 'urls' The 'apps' above is comming from django package: from django.apps import apps and using it in url(r'^', include(apps.get_app_config('oscar').urls[0])), I googled it but didn't find the solution. I am following the instuructions available on your official django-oscar website: https://django-oscar.readthedocs.io/en/releases-1.6/internals/sandbox.html to make the sandbox app up and running locally. Technical details Python version: 3.5.2 Django version:2.1.7 Oscar version: 1.6.7(django-oscar) -
Validate Upload files based on its content
I was trying to verify uploading file. First I tried to check the extension. but if malicious file with a following extension will also be passed the check. def validate_file_extension(value): ext = os.path.splitext(value.name)[1] valid_extensions = ['.pdf', '.doc', '.docx', '.jpg', '.png', '.xlsx', '.xls', 'ppt'] if not ext.lower() in valid_extensions: raise ValidationError(u'Unsupported file extension.') Then I tried to use python magic, this would looks in to the file and decide the actual type. def validate_file_type(value): file_type = magic.from_buffer(value.read(1024), mime=True) valid_file_types = ['image/png', 'image/jpg','text/plain', 'application/pdf', 'application/ms-excel',] if not file_type.lower() in valid_file_types: raise ValidationError(u'Unsupported file.') But Excel, Word, and ppt files are recognized as 'application/zip'. So cannot use this approach for MS documents. Is there any better way to validate upload files? -
Django queryset reverse foreign key for json link
I using python and Django framework and have two tables with foreign key relationship and I want to create a some query where the result includes fields from second table using foreign key to export that result in some JSON api. models.py class work(models.Model): field_0 = models.CharField(max_length=100,blank=True, null=True) field_1=models.CharField(max_length=100,blank=True, null=True) class abilities(models.Model): field_3 = models.CharField(max_length=100,blank=True, null=True) field_4=models.CharField(max_length=100,blank=True, null=True) field_5=models.CharField(max_length=254,blank=True, null=True) field_fk= models.ForeignKey('work', blank=True, null=True) views.py def work_json(request): work_se=serialize('json',work.objects.all()) return HttpResponse(work_se,content_type='json') json result where I take from my view : [ { "model": "mymodel", "pk": 1, "fields": { "field_0": "some value", "field_1": "some value field 1", } } ……… next object ] json result where I need(with fields from table where have field_fk 1) [ { "model": "mymodel", "pk": 1, "fields": { "field_0": "some value", "field_1": "some value field 1", "field_3": "some value field 3", "field_4": "some value field 4", "field_5": "some value field 5", } ……… next object ] any idea how to do that ? thanks -
Generic relation in Django rest
Problem I want to create Student With Address. How can I write REST API in Django for same. Address & Student class Address(models.Model): address = models.CharField(max_length=100, null=False, blank=False) land_mark = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) state = models.CharField(max_length=100, null=True, blank=True) pin_code = models.CharField(max_length=100, null=True, blank=True) latitude = models.FloatField(default=0.0) longitude = models.FloatField(default=0.0) geo_code = models.CharField(max_length=100, null=True, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Student(models.Model): name = model.CharField(max_length=100, null=False, blank=False) address = GenericRelation(Address) def __str__(self): return self.name Serializers class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = "__all__" class StuddentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = "__all__" API View class AddressApiView(ListCreateAPIView): queryset = Address.objects.all() serializer_class = AddressSerializer class StudentApiView(ListCreateAPIView): queryset = Student.objects.all() serializer_class = StuddentSerializer How do I get my create/view student? -
Django annotate count in JSONField with Postgres
Using Django I have a field which is of type JSONField. I am wanting to get a distinct count on a nested key/value in the json. With a normal field you can just do soemthing like the following model.objects.values('field_name')\ .annotate(total=Count('field_name')).order_by('-total') This does not work for a JSONField. Example Model class Pet(models.Model): data = JSONField() Example of data { 'name':'sparky', 'animal':'dog', 'diet':{ 'breakfast':'biscuits', 'dinner':'meat', } } Trying Pet.objects.values('data__diet__dinner')\ .annotate(total=Count('data__diet__dinner')).order_by('-total') Exception of TypeError: unhashable type: 'list' What is the correct way to execute this? -
502: Bad gateway in nginx/gunicorn/Django/Lightsail
I am setting up a Django app on Lightsail and came across a 502 error: bad gateway from Ningx and in its error.log (/var/log/nginx/error.log), there is no .sock so it cannot be communicated. There is no socket file in the root directory. How can I fix this? gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/django_project ExecStart=/home/ubuntu/django_project/env/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/django_project/django_project.sock django_project.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-available/django_project server { listen 80; server_name YOUR_AMAZON_LIGHTSAIL_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/django_project; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/django_project/django_project.sock; } } -
django-imagekit model save in custom action not working
I am trying to user django-imagekit to upload and optimise images in DRF. I am trying to setup a separate endpoint for image upload Model field: profile_image = ProcessedImageField(help_text="User profile image", upload_to='assets/profile_images/', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}, blank=True, null=True) Serializer: class ProfileImageSerializer(serializers.Serializer): """ Serializer for profile image upload """ profile_image = serializers.ImageField(required = True) Viewset action: @action(detail=True, methods=['post'], name = 'Upload Profile Image', permission_classes = [permissions.isLoggedInPermission,]) def upload_profile_image(self, request, pk=None): """ Upload profile Image """ serializer = serializers.ProfileImageSerializer(data=request.data) #check if a valid image passed if serializer.is_valid(): user = request.user image = serializer.data.get("profile_image") user.profile_image = image user.save() return Response(serializer.errors, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) When I upload the image I do get a 201 CREATED response but the image has not been saved. What is going wrong here? -
Django-file-browser How to upload to a unique folder each time
So I recently added the django-file-browser extension to upload files to my website. With my previous solution, I uploaded every file into their own folder. With this extension, I can't seem to figure out how to do it. Previous solution: def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>u return '{0}/{1}'.format(instance.group , filename) root = 'Main/templates/Students/' class new_students(models.Model): student_name = models.CharField(max_length=100) group = models.CharField(max_length=100) document = models.FileField(upload_to=user_directory_path I now want to do the same using the django-file-browser. -
Django packages for User Properties? (tagging++)
I'm aware of django-taggit (and similar) but I'm wondering if there's a package for tagging Users with properties that have values of different types, such as strings, ints, datetimes, etc. For example, one might tag a user with "power-user", add a property for "last-visited-on" as datetime(2019, 02, 13), or add a property for "favorite-color" with the value "purple". These would be open-ended property/tag names where admin-users may be creating these ad-hoc. Thanks. -
How to create view from http request json and Internal Database using Django Rest Framework
I need to combine external json using request and Internal Database, But the condition is when someone call API we need to get empidlong from Model for call external API from specific URL, Then external API will return JSON and i need to merge this JSON with my json that create by Django REST API Framework Here is my code models.py : from django.db import models import requests from django.core.files import File from urllib import request import os # Create your models here. class getData(models.Model): company = models.CharField(max_length=150) description = models.CharField(max_length=150) period = models.CharField(max_length=150) plate_no = models.CharField(max_length=150, primary_key=True) project_code = models.CharField(max_length=150) costcenter = models.CharField(max_length=150) empidlong = models.CharField(max_length=150) class Meta: db_table = 'car_information' serializers.py from rest_framework import serializers from .models import getData class CarSerializer(serializers.ModelSerializer): class Meta: model = getData fields = "__all__" views.py from django.shortcuts import render from rest_framework import viewsets, filters from .models import getData from .serializers import CarSerializer import requests class CarViewSet(viewsets.ModelViewSet): queryset = getData.objects.all() serializer_class = CarSerializer filter_backends = (filters.SearchFilter,) #search_fields = ('plate_no') __basic_fields = ('plate_no',) search_fields = __basic_fields serializer = CarSerializer(queryset, many=True) data = serializer.data for a in data: empid= a['empidlong'] r = requests.get('http://192.168.10.32/Employees/'+empid) def get_queryset(self): queryset = getData.objects.all() emp = self.request.query_params.get('emp', None) if emp is not … -
Django glob media image files and use it on srcs
I have successfully returned every image files inside "media/particular_user/" directory using glob.iglob(). The problem is I can't use it directly on <img src="" /> since it is returned from the root directory '/home/auser/django-apps/blogproject/media/blogs/1/images/' instead of 'media/blogs/1/images/' . I was thinking of looping each result from the view and remove the '/home/auser/django-apps/blogproject/' in each strings to return 'media/blogs/1/images/' only. But is there any other easier way or more proper way to do this? Here's my codes: views.py: def blog(request, blog_slug): """ Blog view page :param request: :return: """ context = dict() file_extensions = ('*.png', '*.jpg', "*.gif") image_files = [] for file_extension in file_extensions: image_files.extend(glob.iglob(settings.MEDIA_ROOT+"/blogs/1/images/"+file_extension, recursive=True)) context['image_files'] = image_files context['slug'] = blog_slug return render(request, "app_plan/plan.html", context) blog_view.html: <ul> {% for image_file in image_files %} <li class="inline"> <img src="{{image_file}}"/> </li> {% endfor %} </ul> When showing the image_files using {{image_files}} in the html will show these records: [ '/home/auser/django-apps/blogproject/media/blogs/1/images/5.png', '/home/auser/django-apps/blogproject/media/blogs/1/images/4.png', '/home/auser/django-apps/blogproject/media/blogs/1/images/3.png', '/home/auser/django-apps/blogproject/media/blogs/1/images/2.png', '/home/auser/django-apps/blogproject/media/blogs/1/images/1.png', ] The problem is I can't use each of these directly on my <img src="{{image_file}}"/> since it is accessing from the root instead of from "media/" -
Displaying the values of enums on a template
How do I display the enumerations value from my models.py onto the templates. Duplicate posts not sure why my situation does not work. Django: Display Choice Value I used obj.get_privacy_display but it does not list them. If I use obj.privacy. The value is 0 for public and it's not displayed, I can only see it when I inspect element. It does not list all the choices. {% for obj in object_list %} <div class="dropdown show"> <a class="btn btn-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Privacy Setting </a> <div class="dropdown-menu" aria-labelledby="dropdownMenuLink"> <a class="dropdown-item" href="#">{{ obj.get_privacy_display }}</a> </div> </div> {% endfor %} class PostManager(models.Manager): def all(self): pass def filter_by_public(self): pass def filter_by_private(self): pass def filter_by_friends(self): pass def filter_by_foaf(self): pass def filter_by_only_server(self): pass def filter_by_only_me(self, *args, **kwargs): query_set = super(PostManager, self).filter(privacy=ONLY_ME, user=user) return query_set class Post(models.Model): PUBLIC = 0 PRIVATE = 1 FRIENDS = 2 FOAF = 3 ONLY_SERVER = 4 ONLY_ME = 5 Privacy = ( (PUBLIC, 'Public'), (PRIVATE, 'Only certain friends'), (FRIENDS, 'Only friends'), (FOAF, 'Friend of a friend'), (ONLY_SERVER, 'Server wide'), (ONLY_ME, 'Only me') ) privacy = models.IntegerField(choices=Privacy, default=PUBLIC) -
Django server connection error with Docker Toolbox in OS X Yosemite
I run the following yml file with $docker-compose up command. I'm developing a REST API with django (Udemy "Build a Backend REST API with Python & Django - Advanced"). system: OS X 10.10.5 Docker version 18.03.0-ce docker-compose version 1.20.1 Q:I am unable to access localhost with 127.0.0.1 Some suggest to add CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] in Dockerfile; didn't work in this case. In django settings.py, ALLOWED_HOSTS = ['192.168.99.100'] Console output (part of: see bold) app_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection app_1 | connection = Database.connect(conn_params) app_1 | File "/usr/local/lib/python3.7/site-packages/psycopg2/__init__.py", line 130, in connect app_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) app_1 | django.db.utils.OperationalError: **could not connect to server: Connection refused app_1 | Is the server running on host "db" (172.19.0.2) and accepting app_1 | TCP/IP connections on port 5432? I'm super new to this stuff, appreciate your help and suggestions. -
Django debugging Test Server
I am working on a Django project and I use VSCode for an editor. More so, I've found the IDE capabilities very useful. So now I'm trying to debug the tests that have failed before. In the debugging configuration I have the following: { "name" : "Django: TestServer", "type" : "python", "request" : "launch", "program" : "${workspaceFolder}/manage.py test ${file}", "console" : "integratedTerminal", "env" : {"STAGING_SERVER": "staging.my_server.com"}, // "args" : ["test", ], "django" : true } On starting the debugger I get a message that says: File does not exist "/home/diego/project/manage.py test /home/diego/project/func_tests/test_login.py" When I run that test on my own, I do: .../project$ python manage.py test func_tests.test_login That is, writing the test address as Python modules instead of folders. I've read the documentation on VSCode about Django debugging and didn't find anything on this. Does anyone know how to fix this? Thanks. -
Django truncatewords and shows the searched word
I have a variable sentences contains: "Page's web crawler began exploring the web in March 1996, with Page's own Stanford home page serving as the only starting point. To convert the backlink data that it gathered for a given web page into a measure of importance, Brin and Page developed the PageRank algorithm. While analyzing BackRub's output which, for a given URL, consisted of a list of backlinks ranked by importance the pair realized that a search engine based on PageRank would produce better results than existing techniques (existing search engines at the time essentially ranked results according to how many times the search term appeared on a page)." Then, I use truncatewords in Django HTML to short the view of the sentences. {{ sentences|truncatewords:30 }} So, the result shows this: "Page's web crawler began exploring the web in March 1996, with Page's own Stanford home page serving as the only starting point. To convert the backlink data that it . . ." Actually, I want to show the truncatewords result with a specific word, for example, "BackRub", so the result supposed to be: "While analyzing BackRub's output which, for a given URL, consisted of a list of backlinks ranked … -
Django - URLS not rendering view in root homepage
So for some reason when I try to render the create_view_two view to the root of my app which is called home.html, the page will not render the view. However if I have the create_view_two view pointing to a different page it works. Example below: user_profile/urls.py urlpatterns = [ path("test/", create_view_two, name='home'), ] user_profile/views.py return render(request, "test.html", context) I would like to point this view to the root of my app and not something different. How can I do that? Any help is gladly appreciated. Cheers user_profile/views.py from django.http import HttpResponse, HttpResponseRedirect from django.http import HttpResponseNotFound from django.shortcuts import get_object_or_404 from django.shortcuts import render, redirect from django.conf import settings from .forms import HomeForm from .models import Listing from users.models import CustomUser def create_view_two(request): form = HomeForm(request.POST or None, request.FILES or None,) user_profile = Listing.objects.all() user = request.user context = { 'form': form, 'user_profile': user_profile } return render(request, "home.html", context) main.urls from django.conf.urls import url from django.contrib import admin from django.urls import path from django.urls import path, include from django.views.generic.base import TemplateView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home'), path('admin/', admin.site.urls), path('', include('user_profile.urls')), path('', include('users.urls')), path('', include('django.contrib.auth.urls')), path('users/', include('users.urls')), path('users/', include('django.contrib.auth.urls')), path('', include('myapp.urls')), ] … -
Django Structures: Many apps VS one large app
I hope this is not a opinion based question but more like a solutions to a complicated django website. fyi, i am quite a beginner in django. first of all, i am doing a complicated accounting django website where there are features like: purchases (purchase order, quotation request, quotation, invoice, do) Custom user roles and permissions, because we want user to setup their own roles and permissions system sales (POS, stocks, too many to mentions) user and registrations incomes & expenses tracking and reporting. There are articles and SO's answers about 'many apps vs 1 large app'. My confusion started. I figured out django allows seperating views.py and models.py into multiple file in app/views and app/models with init.py imports. I personally do not like large app file as it is hard to locate things. I prefer neat structures. But the confusion keeps attacking. I want to do one thing and do it well but it seem like having one large app makes more sense because all the mentioned features are ForeignKey dependent. So, according to your experience. what's your ideal folder structures and solutions to deal with this? If you could provide performance difference that would be helpful. -
Creating posts that filter by a privacy setting
Problem: I am trying to create a posts section that filters based different privacy settings. My intuition is to make a PostManager that contains the various functions that filter based on privacy setting. I'm not sure how to go about doing this.Is that the most efficient way to go about doing this. Provide below is snippets of code that I have my posts app. Background information: This is the structure of my application. --Home_app --_views.py --Posts_app --_views.py --Templates --home.html Snippet of my posts.views. Not the complete file class PostManager(models.Manager): def all(self): pass def filter_by_public(self): pass def filter_by_private(self): pass def filter_by_friends(self): pass def filter_by_foaf(self): pass def filter_by_only_server(self): pass def filter_by_only_me(self): pass class Post(models.Model): PUBLIC = 0 PRIVATE = 1 FRIENDS = 2 FOAF = 3 ONLY_SERVER = 4 ONLY_ME = 5 Privacy = ( (PUBLIC, 'Public'), (PRIVATE, 'Only certain friends'), (FRIENDS, 'Only friends'), (FOAF, 'Friend of a friend'), (ONLY_SERVER, 'Server wide'), (ONLY_ME, 'Only me') ) privacy = models.IntegerField(choices=Privacy, default=PUBLIC) # posts = PostManager() This is a sinpet of my home.html file. Not completed <div class="dropdown show"> <a class="btn btn-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" > Privacy Setting </a> <div class="dropdown-menu" aria-labelledby="dropdownMenuLink"> <a class="dropdown-item" href="#">{{ posts.privacy }}</a> </div> </div> -
Django 1.11 - Adding Permissions to existing users in production
Problem I have a database in production with users and I'm creating new permissions in some models. Now I need to add these permissions to some users depending on a condition. How should I do this? Should I add code to the migration to check all users and add permissions to them accordingly? -
How to configure Django url to point to a specific section in the page?
I'm trying to configure a url in Django to let it point to a specific section in certain page. Let's say I have this in my urls.py: urlpatterns = [ path("", mywebsite.views.home, name="home"),] I'm already awared of that I can use "{% url 'home' %}" in my templates to go to this page. However, I'm wondering that is it possible to go to the #experience section in my homepage with modifications on this url configuration? Many thanks in advance! -
How to remove MSSQL decimal declaration from QuerySet list?
I have a sorting algorithm that orders a list with parents and their children. Here is a working example: Tutorials Point Coding Ground. This working example, however, has a predefined "cleaned" list. The only difference however with this predefined list is that I have removed the "Decimal Declarations" (or whatever they are called) from the list. Here is an example of both dirty and clean lists. Dirty list: item_list = [ {...}, {'qmaQuoteAssemblyID': 0, 'qmaLevel': Decimal('1'), 'qmaParentAssemblyID': 0, 'qmaPartShortDescription': '12U x 600 x 650 Professional Rack', 'qmaPartID': 'RACK S9', 'qmaQuantityPerParent': Decimal('1.00000')}, {...}] Clean List: item_list = [ {...}, {'qmaQuoteAssemblyID': 0, 'qmaLevel': 1, 'qmaParentAssemblyID': 0, 'qmaPartShortDescription': '12U x 600 x 650 Professional Rack', 'qmaPartID': 'RACK S9', 'qmaQuantityPerParent': 1.00000}, {...}] As you can see from both the examples that the dirty list has Decimal('somevalue') surrounding it's DecimalField value. However with the clean list it has that removed allowing it to go through the algorithm without a problem. When I run the dirty list through the algorithm I get this error: Traceback (most recent call last): File "<stdin>", line 2, in <module> NameError: name 'Decimal' is not defined And within my Django project the list is simply considered empty. This makes sense because … -
Django template tags filter with multiple arguments
Django template tags filter with multiple arguments @register.filter def customTag(value, first, second): ... return result Template {{ valor|customTag:first|customTag:second }}