Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to represent multiple routes on Google Maps API with GPS Coordiates
I've looked at similar questions, and they all refer to Google Maps API DirectionsRenderer(). I have a set of GPS coordinates, and each set has a flight_id. Instead of Point A to Point B directions, I have every GPS coordinate I want to plot, connecting the lines from each distinct flight_id start and end points together with a provided timestamp. For example: [{ "flight_id": "2220", "first": { "lat": 41.9554, "lng": -87.888, "timestamp": "2019-07-15T22:32:50" }, "last": { "lat": 41.9554, "lng": -87.888, "timestamp": "2019-07-23T17:45:33" } }, { "flight_id": "2365", "first": { "lat": 41.9469, "lng": -87.8651, "timestamp": "2019-08-11T13:31:20" }, "last": { "lat": 36.844, "lng": -76.288, "timestamp": "2019-08-13T14:15:40" } }] I'm able to get one set of GPS coords first and last points to display on a map, but not multiple. What am I missing? -
PiCar Configuration Exception in thread django-main-thread
I tried to setup the (PiCar) from SunFounder and got following error: mjpg_streamer -i "/usr/local/lib/input_uvc.so" -o "/usr/local/lib/output_http.so -w /usr/local/www" & None Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.7/dist-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 436, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application. System check identified 3 issues (0 silenced). I executed following command: ~/SunFounder_PiCar-V/remote_control $ sudo ./start Here the manual from the PiCar. The error occured on page 42. Maybe the pages 40 and 41 are relevant for this error. Sorry I am new to Python and Django. Maybe there is a person who can explain me this error. The OS is raspbian jessie. Thank you very much. -
Django annotate: sum of max of foreign objects
class CashEvent(models.Model): date = models.DateField() profit = models.FloatField() damage = models.FloatField() seller = models.ForeignKey(Seller) class Seller(models.Model): name = models.CharField() store = models.ForeignKey(Store) class Store(models.Model): name = models.CharField() country = models.ForeignKey(Country) From the models above, given that in ids I have a list of ids of Sellers, I need to annotate this list so that I have the sum of each highest damage of each single Seller in my list. Is this possible to do in annotate? ids = [4, 5, 6] Store.objects.filter( seller__cashevent__date__gte=date(2018, 1, 1), seller__id__in=ids ).annotate( sum_of_highest_damage_of_each_seller=? ) I have tried with Sum(Max('seller__cashevent__damage')) but you can't put an aggregation function inside of another. -
How to use pypy with Django along with postgresql backend?
Is there a way to install psycopg2 with pypy. I am trying to run Django with pypy and the main problem I am facing is psycopg2 library. pypy documentation says that I can install psycopg2cffi library instead, but I don't know how to tell Django postgresql backend to use psycopg2cffi instead of psycopg2. Is there any way I can do that? Is there a way to install psycopg2 with pypy. or more broadly, is there any advantage of using pypy than normal Cpython compiler with Django? I tried running various python programs using both Cpython and pypy and shockingly pypy was much faster. So, I thought using pypy can actually increase the throughput of APIs by reducing the time of each API, but I haven't found any documentation for the same? Any leads are welcome!! Thanks in advance. -
Automatically import custom files in Django
I have a Django project containing some files which are, obviously, not automatically discovered by Django. My workaround is to import them in urls.py so that Django can see them. This is how my urls.py looks like: from django.contrib import admin from django.urls import path from custom_file_1 import * # "unused" import from custom_file_2 import * # "unused" import urlpatterns = [ ... ] My IDE considers the commented imports unused, since they are not used, but they are vital so that Django can process those files. And the question: is there any nice way to let Django see those files? And how to do that? -
Django Cron job to update database Entry django python
I have search and found that it can be done using several ways . I am doing using django_cron like this from django_cron import CronJobBase, Schedule from FrontEnd.views import UpdateField class UpdateFiledJob(CronJobBase): RUN_EVERY_MINS = 2 MIN_NUM_FAILURES = 2 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = def do(self): UpdateField() First this is what is code field for ? 2nd Can I run this my view function like this ? And in which folder I should keep my taskautomation.py file currently I put it with my manage.py file? my -
How to define URLs only once for server and client?
everyone! I am building a web application, i.e. a server-client application. For the interaction between the two, I have to define the URLs twice (hard-coded strings), both on the backend and the frontend, which makes future changes hard, because it would require changing the code in two places, rather than just one. I am using Django and Angular and so I am looking for a way to specify the back end endpoints once, then ideally read them and use them for the Angular production build. Therefore changes to the endpoints will only require a new build, but no further changes. Should these be defined in some .cfg file and be read by the back end on server startup and maybe somehow add them to the Angular's build process? Any suggestion would help because this redundancy comes in almost every webapp project and there has to be a more clever solution! Thanks for the help in advance! -
Passing an object to redirect()
I need to pass an object to redirect function. Is this the way to go about it ? redirect('/view', kwargs={'obj': obj}) def view(request, obj): do something How do I implement it so url dispatcher accepts it ? I would use: url(r'view/.+', view, name='whatever'), Since I'm passing an object I'm not using url converters (str, int, slug, etc) but using regular expression that tells url dispatcher to accept anything I pass to it, however this is throwing me an error. What is the right way to go about it ? -
Impossible to create a WS connection Handshake not working
I'am trying to make channel working and I have an error. When I am trying to connect to a websocket: var chatSocket = new WebSocket('ws://' + window.location.host + '/ws/chat/' + roomName + '/'); consumer.py:- from channels.generic.websocket import WebsocketConsumer import json class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) It gives error: (index):16 WebSocket connection to'ws://127.0.0.1:8000/ws/chat/loby/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET -
What algorithm does tinyUrl, YouTube, imgur etc used to generate random url that is unique?
How YouTube, imgur, bitly etc generate short url. How do they check for uniqueness. What hashing algorithm do they use. I'm learning to implement it in my django project. -
Javascript backtick string interpolation creates a URL with blank spaces
When using string interpolation with backticks to create an URL which posts to a django endpoint, the created url adds unnecessary whitespace and a new line. The faulty js in question: (function (window, document, undefined){ // Upvote / Downvote selectors: const upvote = document.getElementById('upvote'); const downvote = document.getElementById('downvote'); const object_id = document.getElementById('object_id').textContent; // const object_id = document.getElementById('object_id').innerHTML; // csrftoken getter function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); // Voting function const vote = ($route) => { fetch(`/${$route}/${object_id}/`, { method:'post', headers:{ 'X-CSRFToken':csrftoken, 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With':'XMLHttpRequest' }, }) .then((response) => response.json()) .then((responseData) => { console.log(responseData); return responseData; }) .catch(error => console.warn(error)); } // Event listener adder const add = ($element, $route) => { $element.addEventListener('click', vote.bind(null, $route)) } add(upvote, "upvote") add(downvote, "downvote") })(window, document); When I hardcode the URL, it completes successfully: function vote_up(){ fetch(`/upvote/3/`, { method:'post', headers:{ 'X-CSRFToken':csrftoken, 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With':'XMLHttpRequest' }, }) .then((response) => response.json()) .then((responseData) => { console.log(responseData); return … -
Django search bar not getting to the right page
My page has two ways to search services - one is a search bar and the other is clickable categories. The clickable category go to a page that has a category primary key attached to the view and the search bar results do not have a category pk attached. Thus, I created two separate views for this reason. The problem is that both views go to the same page the index.html. I want the search bar to go to the index_search.html. I think I set-up everything correctly, but it still does not work. Two views: search view, clickable items view: #search form view def service_finder(request): model = Service if ('s' in request.GET) and request.GET['s'].strip(): query_string = request.GET['s'] #get query is just searching for search terms in those fields of the query set entry_query = get_query(query_string,['description', 'tags', 'category']) table = Service.objects.filter(entry_query)[:60] return render(request, 'index_search.html', {'table': table}) #clickable items view def servicesListView(request, category): model = Service table = Service.objects.filter(category=category)[:60] return render(request, 'index.html', {'table': table}) Here is the html template with both the search bar and clickable items: {% block content %} <main class="category"> {% include "search_form.html" %} <section class="category-list"> <div class="container"> <div class="row"> {% for service in service_cat %} <div class="col-sm-12 col-lg-6"> … -
Passing dynamic parameter to urlpatterns or DefaultRouter
I have several categories that I want to create distinct views for in rest_framework. But all the categories pull from the same Model. It strikes me that these categories could be passed to urlpatterns as a keyword (or DefaultRouter). Then you can use the keyword to filter the Model as required. Here's my view: class CategoryRankedViewSet(ModelViewSet): serializer_class = CategoriesSerializer def get_queryset(self): return Categories.objects.all().order_by(self.kwargs['category']) One way I was able to make this work was: urlpatterns = [path('<' + category + '>/', CategoryRankedViewSet.as_view({'get': 'list'}), name=category) for category in CATEGORIES] But its not perfect because the key for the parameter is set to the value of first item in CATEGORIES, rather than a more generic term like 'category'. Has anyone ever tried this and is there a more effective method? I was considering DefaultRouter but it is not obvious if parameters can be passed to DefaultRouter I was also looking for ways that the literal url could be accessed and accessing the category that way. Does not appear this is possible in a ViewSet in DRF -
No module named 'django.contrib.auto'
the site is working OK after "python manage.py runserver" im getting the pages as i should , the problem is that when im trying to submit the registration form / or trying to login to the admin page im getting No module named 'django.contrib.auto' even though i haven't had any code issues , went over my code and checked several answers but none of them solved the issue . 1. tried to modify the url.py file - no 2. added to the "INSTALLED_APPS = django.contrib.auto" - no 3. added to the views.py - no 4. checked my code for errors - no INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'basic_app', ] urls.py: from django.contrib import admin from django.urls import path from django.conf.urls import url from django.conf.urls import include from basic_app import views urlpatterns = [ path('admin/', admin.site.urls), url (r'^$',views.index,name='index'), url (r'^basic_app/',include('basic_app.urls')), ] forms.py : from django import forms from django.contrib.auth.models import User from basic_app.models import UserProfileInfo class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username','email','password') class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('portfolio_site','profile_pic') models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) … -
How get GitHub username in django-allauth after authentication?
I added django-allauth to the Django project and I can authentication with GitHub on website. After user authentication, I want to get GitHub username(a user who logged in). How to do it? -
Connecting the elastic beanstalk environment with existing RDS instance
I have an existing RDS MYSQL instance which is in default VPC. I want to connect to this instance through app running on Elastic beanstalk env, which i am not able to do. Beanstalk env and RDS instance are in same VPC and the security groups allow access to port 3306 for all the IPs. Can someone please help? Opened all the security groups for accessing port 3306. -
Django files location
My project structure is: main settings.py and etc. app1 views.py and etc. app2 views.py and etc. manage.py I have decorators that i use in views at app1 and app2. Where should locate file decorators.py? Options in my opinion: create decorators.py in app1 folder and import this to at app1.views and app2.views create decorators.py in app1 folder and import this to app1.views and create decorators.py in app2 folder and import this to app2.views.py (decorators.py will contains the same code, not so good) create decorators.py in main folder and import this to at app1.views and app2.views Your opinion? -
How can I overcome to OrderedDict' object has no attribute 'register' in django?
OrderedDict' object has no attribute 'register' I creating api on django I used register in urls to register defaultrouter() but got this specified error using python anywhere as a server -
Building Bar Chart from data retrieved from Django Database
I'm trying to build a django app where the data is stored in a database (like Sqlite3 or Postgres) then retrieve it in the views and plot the data into a bar chart in the template to show it for the user. what's the easiest way to achieve that? -
How to create a finite state machine with a dynamic number of steps
I have a simple linear workflow where a single task will have a list of approvers that it must pass through (linearly, each in turn) for confirmation before being completed. I have designed this to use the User model for approver, with 2 additional models: A Task model to govern details of individual tasks in a workflow; and a TaskStep model to explicitly manage the relationship between the Tasks and Approvers (rather than relying on Django to autopopulate). class Task(models.Model): title = models.CharField(max_length=30) approvers = models.ManyToManyField( get_user_model(), related_name='approvers_taskstep_set', through='TaskStep' ) class TaskStep(models.Model): approver = models.ForeignKey( get_user_model(), null=True, on_delete=models.SET_NULL ) task = models.ForeignKey(Task, null=True, on_delete=models.SET_NULL) I would like to use django-fsm to create a finite state machine to track the status of each task in the workflow. I know I can do this easily if I pre-define the number of approvers in each workflow. E.g. if it were 3 I could simply put this in an integerfield and then create associated functions each approver would call: // in Task(models.Model): STATUS_APPROVER_1 = 0 STATUS_APPROVER_2 = 1 STATUS_APPROVER_3 = 2 STATUS_CHOICES = ( (STATUS_APPROVER_1 , 'With approver 1'), (STATUS_APPROVER_2 , 'With approver 2'), (STATUS_APPROVER_3 , 'With approver 3'), ) status = FSMIntegerField( choices=STATUS_CHOICES, … -
In DRF, can we use other field than the primary field for a related model?
I am using Django Rest Framework for a small REST API. It's my first interaction with DRF and is pretty much all clear. But: I have an Category model, for which I have an ID and an UUID field. The UUID field I want to use it for public exposed API. What I basically want to achieve, is to be able to use Category.uuid instead of Category.id when I expose the API endpoint to the public (for all CRUD actions): class CategoryModel(models.Model): uuid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) class ArticleModel(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, unique=False, related_name='articles') category = models.ForeignKey(CategoryModel, on_delete=models.CASCADE, related_name='articles') # This serializer won't work as expected: class ArticleSerializer(serializers.ModelSerializer): user = serializers.HiddenField( default=serializers.CurrentUserDefault() ) category = serializers.CharField(source="category.uuid") class Meta: model = ArticleModel fields = ('category', 'user') validators = [ UniqueTogetherValidator( queryset=ArticleModel.objects.all(), fields=('category', 'user'), message=_('You have already added an article in this category') ) ] I have also tried to use a custom serializer, exposing only the uuid field, but without success. Please do not suggest to use uuid as primary key in CategoryModel. I don't want to do that! Test post data: { category: "328d9185-02ae-4963-88a5-03ef67421697" } Posting the above data, I would expect to create an article having the category.uuid … -
How can i capture an image in an android app then send that image to my django rest api?
So i wanted to create an image that will be used to capture an image using the camera app, then that image will be send to the django rest api for image processing. I am currently using retrofit2. I have already made an app that allows a user to choose an image from gallery and then send it to the api, however i can not achieve this if the user wants to capture an image. btnChooseFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*"); startActivityForResult(intent,0); } }); upload the image to api btnUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { File file = new File(imagePath); System.out.print(imagePath); RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),file); MultipartBody.Part body = MultipartBody.Part.createFormData("image",file.getName(),requestBody); Call<FileInfo> call = fileService.upload(body); call.enqueue(new Callback<FileInfo>() { @Override public void onResponse(Call<FileInfo> call, Response<FileInfo> response) { if(response.isSuccessful()){ Toast.makeText(AttendanceActivity.this,"Image Uploaded",Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<FileInfo> call, Throwable t) { Toast.makeText(AttendanceActivity.this,"Error"+t.getMessage(),Toast.LENGTH_SHORT).show(); } }); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (data == null) { Toast.makeText(this, "Unable to choose image", Toast.LENGTH_SHORT).show(); return; } Uri imageUri = data.getData(); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri); imageview.setImageBitmap(bitmap); } … -
Django second signal not saving user
Django 2.4Python 3.7 I am implementing a badge system located on github here. Currently I have a Checkin model and a Badge model, the Checkin model sends a signal to my signals.py file each time a form is saved which then triggers either of two functions (or both) in utils.py to create the badge or add a user if the badge already exists. This flow generates both test badges and the first badge is assigned to a user when the condition is met but 2nd badge (although created) is not assigned the instance.user. I thought that the issue was using 1 util function like in the github link to generate both badges so I created two unique functions to trigger each respective receiver. I am also using a function based view instead of a class CreateView (like the github link). But I strongly doubt there is an issue there since both badges are being created, just not saving. If I move the signal functions to Checkin models I get "can't import Checkin from checkin.models" error which is probably due to a circular import issue (I need to clean up my files a little bit). I've confirmed that the ORM returns … -
Create a re-usable question template in Django
In Django, I want to create a model for a Questionnaire that can be created and used as a template by the user. To do this, my thought is to create a Question class with the desired attributes, then create a QuestionTemplate class that will group the questions together into one, re-usable template. However, I'm not sure how to create a class with an unknown number of attributes. class Question(models.Model): group = None name = models.CharField(max_length=264) question = models.CharField(max_length=264) response = models.TextField() rating = Rating(min_value=0, max_value=5) class QuestionTemplate(models.Model): pass I'd like to have the ability to group these user created questions into a template that the user can apply. -
Is there any open sourced django abac(Attribute Based Permission Control) system
I'm implementing a django app. And I'm searching for any open sourced ABAC system I can use. Do you have any recommendations for ABAC system I can directly use for django? Background: For my app, I will need access control for database entries(using MySQL) After investigation, I think it's better to use Attribute based instead of role based access control. django provides role based access control, but seems no ABAC available. I only found pycasbin (https://github.com/casbin/pycasbin) for the use case. I'm hoping to know if there's any other abac system I can use or read through? Thanks