Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can we get gps data of user's mobile and tablets in our django application?
In my django application I need to store the GPS data of all users to track them especially mobile and tablets how can I do so? -
How to create instance of class during django startup
I am developing MQTT dashboard application with django. I have a table in database which contains list of devices, and one of its parameters is poll_interval_ms. I want to create MqttChannel object (class I created for mqtt connection with devices) for every device which has poll_interval greater than 0. What I already learned is that any startup operations should be placed in ready method in class ApplicationConfig. So I am thinking about something like this: class DashboardConfig(AppConfig): name = 'dashboard' client_list = [] def ready(self): from .models import Device devices_set = Device.objects.all() for device in devices_set: if device.poll_interval_ms > 0: client = MqttChannel(device.id, is_server=True) self.client_list.append(client) Now my question is how to do it properly to access client_list later in code? Should I leave it as it is and access it as dashboard.apps.DashboardConfig.client_list (I'm not even sure if this will work) or is there some better way to do it? -
scripting error in django template creation
Im developing a code that performs multiple functions in the template and i have used scripts to check the functions using if else and for loops, but i am getting these kinds of errors, please help me know the reasons, thank you in advance if you see at the end of the code inside the script tag the declaration of if else tag must be somewhat like the code below, but as soon as i save the code it gets unformatted and gives me errors {% if messages %} {% for message in messages %} alert('{{message}}') {% endfor %} {% endif %} Upload.html file {% extends 'base.html' %} {% block content %} <div class="form-group"> <label for="name" class="col-md-3 col-sm-3 col-xs-12 control-label">Select : </label> <div class="col-md-8"> <select name="cars" id="cars"> <option value="">Select</option> <option value="WithTime">AmpandFreq</option> <option value="WithoutTime">Amplitude</option> </select> </div> </div> <div id="withtime" style="display:none"> <form action="/csvapp/upload/" method="POST" enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %} <div class="form-group"> <label for="name" class="col-md-3 col-sm-3 col-xs-12 control-label">File: </label> <div class="col-md-8"> <input type="file" name="csv_file" id="csv_file" required="True" class="form-control"> </div> </div> <div class="form-group"> <div class="col-md-3 col-sm-3 col-xs-12 col-md-offset-3" style="margin-bottom:10px;"> <button class="btn btn-primary"> <span class="glyphicon glyphicon-upload" style="margin-right:5px;"></span>Upload </button> </div> </div> </form> </div> <div id="withouttime" style="display:none"> <form name="form" action="/csvapp/upload_withouttime/" method="POST" enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %} <div class="form-group"> … -
how to use "prefetch related" to get many to many field in DRF serialzers
In the below code , I need badge_color and badge_text should be shown under user_detail method Models.py class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) user_name = models.CharField(max_length=50, unique=True) user_badges = models.ManyToManyField(Badges,related_name='badges', null=True,blank=True,) class Badges(models.Model): badge_text = models.CharField(max_length=50) badge_color = models.CharField(max_length=50) class Comments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, max_length=50, unique=False) date = models.DateTimeField("date of comment", default=timezone.now) comment_text = models.CharField(max_length=2500) Serializer for comments Class class CommentsSerializer(serializers.ModelSerializer): user_detail = serializers.SerializerMethodField() class Meta: model = Comments fields =[date,comment_text,user_detail] def get_user_detail(self, obj): if obj.user: return { "id": obj.user.id, "user_name": obj.user.user_name, "profile_pic": profile_pic, } else: return None Views.py .......... ............. qs=Comments.objects.all() comments=CommentsSerializer(qs, many=True) -
Django Inspectdb on MSSql error while trying to inspect a table
I've got this error while trying inspecting a MsSql database: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models # Unable to inspect table 'test_table' # The error was: __new__() missing 1 required positional argument: 'collation' This is the command that I've used: python manage.py inspectdb test_table --database=some_db --verbosity=3 This is the connection in settings.py: 'some_db':{ 'ENGINE': 'sql_server.pyodbc', 'NAME': os.environ['name'], 'USER': os.environ['user'], 'PASSWORD': os.environ['pw'], 'HOST': os.environ['db'], 'PORT': os.environ['port'], 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'unicode_results': True }, } -
How to organize Django API
I'm creating an API using Django Rest Framework for a project. I'm fairly new to Django and to DRF, and really to the development of APIs in general, so I'm having some doubts on how to organize my project. I have an app for the API, and for the purpose of organization I separated the views and serializers by files for each resource, sort of like this: |- api |- views |- resource1.py |- resource2.py ... |- serializers |- resource1.py |- resource2.py ... Meanwhile I was told that the APIs for each resource would probably be reused in other contexts, so it would be beneficial if these "modules" were independent. How should I structure this project so that the APIs for each resource can be reused easily in the future, independently from each other? My first instinct would be to create and App inside this project for each resource. Does this make sense? Thank you! -
Platformio-Ide-Terminal does not activate virtual environments
I am running windows machine. My atom is version is 1.56 and the platformio-ide-terminal version is 2.10.1. I have created a virtual environment named Bardia but when I activate it nothing happens. Can you please help? I have tried installing/uninstalling platformio-ide-terminal several times. see code below. After I activate the 'PS' remains and does not change. PS C:\Users\bkamalal> activate Bardia PS C:\Users\bkamalal> -
Django many to many relationship additional fields in forms
This question follows this question: Django's ManyToMany Relationship with Additional Fields What if I want to create a model form for Group, display the many to many relationship with checkboxes and add additional fields to set the values of date_joined and the invite_reason? I thought of creating a formset for the many to many relationship but because the equivalent model of Group will be displayed in a formset, I don't know how to handle that (nested formset). Any tips on how to start? -
Azure blob Storage gives internal server error(500) while uploading files with Django web app
Iam working with Django and Azure.but while uploading media files to azure storage it's giving me internal error 500. Project/settings.py DEFAULT_FILE_STORAGE = os.path.join(BASE_DIR, 'custom_storage.custom_azure.PublicAzureStorage') AZURE_STORAGE_KEY = 'key_1' AZURE_ACCOUNT_NAME = "name" AZURE_MEDIA_CONTAINER = 'blob' AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{AZURE_MEDIA_CONTAINER}/' custom_storage/custom_azure.py from django.conf import settings from storages.backends.azure_storage import AzureStorage class AzureMediaStorage(AzureStorage): account_name = settings.AZURE_ACCOUNT_NAME account_key = settings.AZURE_STORAGE_KEY azure_container = settings.AZURE_MEDIA_CONTAINER expiration_secs = None overwrite_files = True post/views.py class PostCreate(APIView): permission_required = IsAuthenticated parser_classes = [MultiPartParser, FormParser, JSONParser] def post(self, request): images = dict(request.data.lists())["post_image"] task = Post.objects.create(text=request.data['text'], author=request.user) for image_data in images: PostImage.objects.create(post=task, files=image_data) else: return Response(status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) Response : "POST /api/post/create/ HTTP/1.1" 500 145 Response Image -
Access values from model manager
I am trying to simplify a view with a manager but cannot access the values that I return in said manager, can someone help me understand how this works ? Many thanks Manager class CategoryManager(models.Manager): def get_by_cat_name(self, category): categories = Category.objects.all() if self.filter(name=category).exists(): instance = self.filter(name=category) if instance : return instance, categories else : raise Http404("Category does not exists") View : def category_view(request, category): qs = Category.objects.get_by_cat_name(category) context = {'qs': qs #would like to use "instance" and "categories" in context } return render(request, 'store/category.html',context) Model : class Category(models.Model): name=models.CharField(max_length=200) objects = CategoryManager() def __str__(self): return self.name -
Why is django test client throwing away my extra headers
I'm trying to test a view that makes use of some headers. In my test code I have something like this: headers = {'X-Github-Event': 'pull_request'} body = {useful stuff} url = reverse(my_view) I've tried making requests to my view using all possible combinations of the following clients and post calls: client = Client(extra=headers) client = APIClient(headers=headers) client = APIClient(extra=headers) response = client.post(url, data=body, format="json", headers=headers) response = client.post(url, data=body, format="json", extra=headers) My view effectively looks like this: @api_view(["POST", "GET"]) def github_webhook(request): print(request.headers) My X-Github-Event header is never printed out by my test code. If I run runserver and send a request to that endpoint then the headers work perfectlty fine. It's just the test code that is broken. What am I missing here? How can I set the headers for my tests? -
Dajngo - how set index page as http://127.0.0.1:8000/
I would like to set in Django a URL that will point to my index.html. Now I could see at http://127.0.0.1:8000/micromundos but I would like to configure the url to show micromundos at http://127.0.0.1:8000/ This is my current myapp/urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('micromundos/', include("myapp.urls")), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is myapp/myapp/urls.py: from django.urls import path from . import views app_name = "micromundos" urlpatterns = [ path("", views.index, name="index"), ] Any help is appreciated. Thank you -
No module geopandas when running docker-compose up
I am using geopandas in my python code. When i run my code using docker-compose up, i am getting the following error ModuleNotFoundError: No module named 'geopandas' requirements.txt is as follows: codegen==1.0 Django==3.1.1 django-cors-headers==3.5.0 djangorestframework==3.12.2 django-rest-multiple-models==2.1.3 django-enumfield==2.0.2 django-tinymce==3.1.0 django-geo==0.8 geopandas==0.8.2 gunicorn==20.0.4 mysqlclient==2.0.1 patterns==0.3 pandas==1.2.4 pytz==2020.1 requests==2.25.1 timezones==2.0.8 six==1.15.0 sqlparse==0.3.1 waitress==1.4.4 whitenoise==5.2.0 when i installed geopandas with pip, i had to install it with pip install python3-geopandas. changing the requirements.txt to python3-geopandas==0.8.2 doesn't fix it base of the image is: FROM python:3.8 i also tried adding: numpy pandas shapely fiona pyproj to requirements.txt because of the dependencies. Also this doesn't fix the problem. Someone who can help me fixing this problem? -
django ForeignKey field should only select by category
I have a ForeignKey field in my model and in Django admin and Django forms` when I display that field or in Django admin, I get all the field that in that model However, I only want to display selected fields in that dropdown, for example class Area(models.Model): area_type_options = (('cc', 'Cost Center'), ('pc', 'Profit Center'),) name = models.CharField(max_length=100) area_type = models.CharField(max_length=100, choices=area_type_options) class Item(models.Model): name = models.CharField(max_length=150, null=True, unique=True) profit_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='profit_center') cost_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='cost_center') I get to see all the records in the cost_center and all the records in the profit_center however I only want to see where area_type is cc to cost_center and where area type pc to profit_center Please Help -
Pylint doesn't report wrong import order when using Django
Pylint doesn't report wrong import order when using Django. I have a file such as: from feature_one.models import Area from django.shortcuts import render The import order is obviously wrong alphabetically and because django is a 3rd party, feature_one is my own code. Isort output: $ isort --check app/feature_one/views.py ERROR: pylint-wrong-import-order/app/feature_one/views.py Imports are incorrectly sorted and/or formatted. $ isort --diff app/feature_one/views.py --- pylint-wrong-import-order/app/feature_one/views.py:before 2021-04-19 11:08:35.849230 +++ pylint-wrong-import-order/app/feature_one/views.py:after 2021-04-19 11:08:50.015937 @@ -1,4 +1,4 @@ +from django.shortcuts import render from feature_one.models import Area -from django.shortcuts import render # Create your views here. So why doesn't Pylint complain? Here's a repo which I created to demonstrate this: https://github.com/Gilwyad/pylint-wrong-import-order -
Rest api without serializer in dajngo
Can we able to create an API without a serializer in Django? How to do that? What is the use of serializers and can we customize the error response of serializers? For example serializers error response will be as follow : { "first_name":["This field is required"], "last_name":["This field is required"], "email":"["This field is required"], } but I want to return a custom error response .suppose any of the fields is not validate then I want to display an error response in the following format { "status":"Error", "text":"Email not provided" } -
Django says pillow is not instaled while it is
after upgrading python 3.8 to 3.9 this error has happened and says pillow is not installed. I tried to uninstall and reinstall pillow, but it did not worked. the image is attached to see the detail. I'm using Django 3.1 on a windows 10 pro. -
Unable to use python dictionary as JSON in Django template html script
I am passing a python dictionary to a Django template html script as:- def create_dict(request): #creating the dictionary and storing it in py_dict py_dict = json.dumps(py_dict) context = { "py_dict": py_dict } In the Django template, I am retrieving the dictionary as follows:- <script language='javascript'> $(document).ready(function(){ var dict = "{{py_dict}}"; console.log(dict); }); </script> If I try to assign the variable dict directly the Django variable(py_dict) without the double qoutes(var dict = {{py_dict};) then it shows Not found & error The actual python dictionary looks like this:- {"19.2.000/": {"19.2.000/dataconversion/": {}, "19.2.000/reim/": {}, "19.2.000/resa/": {}, "19.2.000/rms/": {}}, "19.2.001/": {"19.2.001/dataconversion/": {}}, "19.2/": {"19.2/alloc/": {}, "19.2/rpm/": {}}, "RESA/": {"RESA/folder1/": {}}, "RMS/": {}, "RPM/": {}, "/": {}, "apc/": {"apc/apc_inner/": {}}, "dataconversion/": {}, "folder2/": {}, "merch/": {"merch/19.0.x/": {"merch/19.0.x/19.0.000.1/": {"merch/19.0.x/19.0.000.1/dataconversion/": {}}, "merch/19.0.x/19.0.001/": {"merch/19.0.x/19.0.001/alloc/": {}, "merch/19.0.x/19.0.001/reim/": {}, "merch/19.0.x/19.0.001/resa/": {}, "merch/19.0.x/19.0.001/rms/": {"merch/19.0.x/19.0.001/rms/reports/": {}}, "merch/19.0.x/19.0.001/rpm/": {}}, "merch/19.0.x/19.0.002.1/": {"merch/19.0.x/19.0.002.1/Merged_RC/": {"merch/19.0.x/19.0.002.1/Merged_RC/rms/": {}}, "merch/19.0.x/19.0.002.1/hotfix/": {"merch/19.0.x/19.0.002.1/hotfix/rms/": {}}}, "merch/19.0.x/19.0.002/": {"merch/19.0.x/19.0.002/alloc/": {}, "merch/19.0.x/19.0.002/dataconversion/": {}, "merch/19.0.x/19.0.002/jos_merch/": {}, "merch/19.0.x/19.0.002/reim/": {}, "merch/19.0.x/19.0.002/resa/": {}, "merch/19.0.x/19.0.002/rms/": {"merch/19.0.x/19.0.002/rms/rms19installer.zip": {}}}}}} but when I console.log it in the script tag, the output is this:- {&quot;19.2.000/&quot;: {&quot;19.2.000/dataconversion/&quot;: {}, &quot;19.2.000/reim/&quot;: {}, &quot;19.2.000/resa/&quot;: {}, &quot;19.2.000/rms/&quot;: {}}, &quot;19.2.001/&quot;: {&quot;19.2.001/dataconversion/&quot;: {}}, &quot;19.2/&quot;: {&quot;19.2/alloc/&quot;: {}, &quot;19.2/rpm/&quot;: {}}, &quot;RESA/&quot;: {&quot;RESA/folder1/&quot;: {}}, &quot;RMS/&quot;: {}, &quot;RPM/&quot;: {}, &quot;/&quot;: {}, &quot;apc/&quot;: {&quot;apc/apc_inner/&quot;: {}}, &quot;dataconversion/&quot;: … -
how to identify and set User model foreign keys in User details database on submitting my User Registration form
As I mentioned above I want to automatically identify the User's id from the User model and set it in my User details model as foreign key on Submitting Registration form curenty I am making changes manully to testing purpose which is not a practice for standalone website models.py class Student_Details(models.Model): u_id=models.ForeignKey(User,null=True,on_delete=models.SET_NULL) field=models.CharField(max_length=400,null=True) class Institute_Details(models.Model): I_id=models.ForeignKey(User,null=True,on_delete=models.SET_NULL) name=models.CharField(max_length=400,null=True) zipcode=models.CharField(max_length=6,null=True) def __str__(self):return str(self.name) class Staff_Details(models.Model): s_id=models.ForeignKey(User,null=True,on_delete=models.SET_NULL) Institute_from=models.ForeignKey(Institute_Details,null=True,on_delete=models.SET_NULL) def __str__(self):return str(self.s_id) form.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['id','username','first_name','last_name','email', 'password1', 'password2'] class Institute_form(ModelForm): class Meta: model = Institute_Details fields=['name','zipcode'] viewspy @unauthenticated_user def registerPage(request): form = CreateUserForm() form2 = Institute_form(request.POST) if request.method == 'POST': form = CreateUserForm(request.POST) form2 = Institute_form(request.POST) if form.is_valid(): if request.POST.get('user_type') == 'User': user1 = form.save() group1 = Group.objects.get(name='Student') user1.groups.add(group1) elif request.POST.get('user_type') == 'Institute': user2 = form.save() form2.save() group2 = Group.objects.get(name='Institute') user2.groups.add(group2) return redirect('default') context = {'form': form,'Iform':form2} return render(request, "htmls/signup.html", context) def logoutUser(request): logout(request) return redirect('default') -
why are my static files not getting detected in django?
I want to add a static file to my django project app. My app is named "core" Hence inside the app where I need the static file (called main.css) , I made a directory named static/core/main.css So after that my directory looks like this core .... -static |_core |_main.css ......... And in the settings.py file , I wrote this STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' And in the html file where I want the static css I wrote this {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{% block title %} Welcome | Ecommerce {% endblock %}</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css"> <link rel="stylesheet" href="{% static '' %}"> This HTML file is located in a global project level template folder where I dump the templates from all the apps in the project . But my static file is not getting loaded for some reason -
Python manage.py makemigrations gives me this error
You are trying to add a non-nullable field 'id' to department without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py Select an option: 1 Please enter the default value now, as valid Python The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now Type 'exit' to exit this prompt -
Object of type 'Request' is not JSON serializable
I'm trying to pass a few arguments form my view to my additional function, but I get error "Object of type 'Request' is not JSON serializable", I don't why is occured with me, cause I didn't pass request object to Response. @api_view(['POST', ]) @permission_classes([IsAuthenticated]) def users_upload(request): if request.user.type != 't': logger.warning(f'Users upload ERROR: -{request.user.username}- not a teacher') return Response({'message': 'Not a teacher'}, status=403) try: user_file = request.FILES['data'] file_format = user_file.name.split('.')[-1] if file_format not in ['csv', 'xls', 'xlsx']: logging.error('User upload ERROR: incorrect file format') return Response({'message': 'Incorrect file format'}, status=400) auto_file = AutoFile.objects.create( description='Temp file for user upload', file=user_file ) upload_users_from_file.delay(request, auto_file.pk, file_format) return Response({'message': 'Task created'}, status=200) except Exception as e: logging.error(f'User upload ERROR: unable to evaluate file format: {e}') return Response({'message': 'Error during file check'}, status=400) What happened? -
DRF: How to store an entity with a given primary_key at data. Serializer doesn´t use the given primary_key
I´m confused at a certain problem. I have two different approches and only one works properly. I´m describing the one that doesn´t work. The other approach that works has a different primary_key-setting. Model: from django.db import models from ..amc import CreationDate from ...api.lib.modelfield import create_datetime class ConfigurationParameterList(CreationDate): modificationDate = models.DateTimeField("modification_date", default=create_datetime) class ConfigurationParameter(CreationDate): name = models.CharField(verbose_name="name", max_length=256) value = models.FloatField(verbose_name="value") unit = models.CharField(verbose_name="unit", max_length=256) description = models.CharField(verbose_name="description", max_length=256) context = models.CharField(verbose_name="context", max_length=256) fk_configuration_parameter_list = models.ForeignKey(ConfigurationParameterList, verbose_name="fk_configuration_parameter_list", on_delete=models.CASCADE) Serializer: from rest_framework import serializers from ..base_serializer import CustomModelSerializer, CustomWritableNestedModelSerializer from ....models import ConfigurationParameterList, ConfigurationParameter class ConfigurationParameterSerializer(serializers.ModelSerializer): class Meta: model = ConfigurationParameter exclude = ['id', 'creationDate', 'fk_configuration_parameter_list'] class ConfigurationParameterListSerializer(CustomWritableNestedModelSerializer): KEYS_DATETIME_CONVERT = ['modificationDate'] parameter = ConfigurationParameterSerializer(many=True, source='configurationparameter_set') class Meta: model = ConfigurationParameterList # fields = ['modificationDate', 'parameter'] exclude = ['creationDate'] CustomWritableNestedModelSerializer uses drf-writable-nested POST at view.py def post(self, request): data = request.data.get(self.STATIC_ATTRIBUTES.DATA) data['id'] = 1 serializer = self.serializer_class(data=data) if serializer.is_valid(): serializer.save() self.resp.status_code = HTTP_201_CREATED else: self.resp.status_code = HTTP_400_BAD_REQUEST logger.info(serializer.errors) return self.resp I would like to store only one entity at ConfigurationParameterList with its nested ConfigurationParameter data. Like you can see, ConfigurationParameterList uses Djangos id-field. I know that id is read_only at ConfigurationParameterListSerializer. However, I want to use a specific id-value when I post data. … -
how can I attach a telegram chat to the layout of the site?
the site is written in django. I need to make a modal window with a chat bot. now faced a problem, how to embed telegram chat into the site code -
Class missing "Meta.model" attribute but it's there?
Currently following this tutorial on youtube. and I am getting this error from the serializers.py file with the code he has finished writing at 32:24 This is the code I have written class ArticleSerializer(serializers.ModelSerializer): class Meta: model: Article fields: ['id', 'title', 'author'] If I change it to use serializers.Serializer then it works class ArticleSerializer(serializers.Serializer): title = serializers.CharField(max_length=100) author = serializers.CharField(max_length=100) email = serializers.EmailField(max_length=100) date = serializers.DateField() def create(self, validated_data): return Article.objects.create(validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.author = validated_data.get('author', instance.author) instance.email = validated_data.get('email', instance.email) instance.date = validated_data.get('date', instance.date) instance.save() return instance