Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I change the Django dev server quit shortcut?
I'm really new to Django, so sorry for the dumb question, but I can't seem to find an answer online. When you start the Django dev server, it says "Quit the server with Ctrl-Break", but unfortunately, my keyboard does not have a break key. I found one solution here, but all they said was to detach the program and kill the process manually, which doesn't really feel like a clean solution to me. I also really don't want to have to rebind keys in my terminal, since I often switch between cmder, powershell, and the visual studio code integrated terminal, on several different computers. -
Getting "Exception: You cannot access body after reading from request's data stream" while working with DRF and django-revproxy
I'm using django-revproxy and Django REST Framework in my project. And I'm exposing an API where users get analytics about their chatbots, and it works as the following: The user send requests the analytics from the Django project Django project, checks if the user is authenticated and owns that chatbot if True it contacts another external service. My urls.py: # urls.py urlpatterns = ( url(r'^analytics/(?P<path>.*)$', api.AnalyticsFunctionsProxyView.as_view()), ) And in my view: # views.py from rest_framework.authentication import TokenAuthentication from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework.permissions import IsAuthenticated from revproxy.views import ProxyView from .permissions import HasChatBotPermission ... class AnalyticsFunctionsProxyView(ProxyView): upstream = settings.ANALYTICS_FAAS_URL def parse_body(self, request): if isinstance(request, rest_framework.request.Request): return request.data return super(AnalyticsFunctionsProxyView, self).parse_body(request) @classmethod def as_view(cls, *args, **kwargs): view = super(AnalyticsFunctionsProxyView, cls).as_view(*args, **kwargs) view = permission_classes((IsAuthenticated, HasChatBotPermission,))(view) view = authentication_classes([TokenAuthentication, JSONWebTokenAuthentication])(view) view = api_view(['GET', 'POST'])(view) return view And my HasChatBotPermission permissions #permissions.py class HasChatBotPermission(permissions.BasePermission): def has_permission(self, request, view): try: bot_name = request.data.get('name') user = request.user self.message = 'Permission denied for {}'.format(name) return ChatBot.objects.filter(user=user, project_name=project_id).exists() except Exception: self.message = 'Permission denied, no project_id was defined!' return False When the view is called it raises this exception: Traceback (most recent call last): File "/home/fcmam5/dela3a/env/lib/python3.6/site-packages/rest_framework/request.py", line 379, in __getattribute__ return super(Request, self).__getattribute__(attr) AttributeError: 'Request' object has … -
Optional test cases in Django
We have a moderately large test suite for business logic and this completes within a few seconds. We're running this as a condition to commit (a hook that must pass) and that has been working well to block the most stupid mistakes from making it off my machine. We've recently started adding end-to-end frontend tests with webdriver. Some of these tests pass over third party integrations. The tests are useful but they're really slow and require a network connection. We also have some logic tests that are extremely long that are commented out (yeah!) unless we suspect something wrong. Is there a sensible way to split these slow tests out so they only run when we specifically want them to and not every time you run ./manage.py test? -
Vote comments in Django
I want a Twitter-like app where anyone can put a comment and vote. I have a model "Comment" with 5 fields: class Comment(models.Model): date = models.DateTimeField(default = timezone.now) name = models.CharField(max_length = 500) text = models.CharField(max_length = 2000) votes = models.IntegerField(default = 0) ID = models.AutoField(primary_key = True) And a form to put the comments. Now I want to count the votes using a click in an image. So in template every comment has a like icon with href to its ID. Then in urls.py I have: urlpatterns = [ ..., url('<int:text_id>/', upvote, name='upvote'), ] In views.py: def upvote(request, text_id): comment = Comment.objects.get(pk = text_id) comment.votes += 1 comment.save() return HttpResponse('comments/index.html') But it's not working now. Every comment goes to its url but it doesn't recognize the vote. What can I do? -
Docusign Django Integration - Post Go-Live Code Not Working
I have been integrating Docusign's API with my code to make a document signing process faster for my company. I had a working version (after many questions posted on here, and many hours of work), and after purchasing a live version, my program no longer worked when I attempted to call the API. I believe I had made all of the necessary changes, yet my code is still not working. The following is my code: def Signview(request): loa = LOA.objects.filter().order_by('-id')[0] #This is how the document to be signed is retrieved from the database. localbillingname = loa.billingname.replace(" ", "_") username = "MyUserName" integrator_key = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" base_url = "https://docusign.net/restapi/" oauth_base_url = "account.docusign.com/" redirect_uri = "http://localhost:8000/path/to/redirectURI" #This has also been set in the admin page for the correct admin key. private_key_filename = "path/to/pkey.txt" user_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" #client_user_id = 'clientUserID # Add a recipient to sign the document signer = docusign.Signer() signer.email = loa.email signer.name = loa.ainame signer.recipient_id = '1' #signer.client_user_id = client_user_id sign_here = docusign.SignHere() sign_here.document_id = '1' sign_here.recipient_id = '1' sign_here.anchor_case_sensitive = 'true' sign_here.anchor_horizontal_alignment = 'left' sign_here.anchor_ignore_if_not_present = 'false' sign_here.anchor_match_whole_word = 'true' sign_here.anchor_string = 'Signature of individual authorized to act on behalf of customer:' sign_here.anchor_units = 'cms' sign_here.anchor_x_offset = '.2' sign_here.anchor_y_offset = … -
Load a variable on many pages without repeating myself
In Django, I have a sidebar navigation menu that has its own include file (let's call it sidebar.html). In sidebar.html, I sometimes load a special menu, depending on which page I am visiting. This special menu is generated from a database, so I need to run something like this in my views: menu = Menu.objects.all() Then I need to pass this variable to the template. However, there are some 30 pages where I need this menu. It seems like a repetitive solution to have the aforementioned line repeated 30 times in my views file. Is there a better way of doing it? I only need the menu variable in sidebar.html, so there is only 1 file where I need it. -
Customizing css file in django-oscar using less
i am fairly new to django oscar and really have basic understanding of website front end. I want to change the styles.css in django oscar. I have tried to change directly in styles.css but somehow when I refreshed the localhost detect no changes (default css). I've tried to change the less file, install the npm install less and change the setting into OSCAR_USE_LESS = True. The localhost even didn't render the css file at all. only the template. When I write the command make css in root directory. following error occured even though I've installed less. make: *** No rule to make target `css'. Stop. so I really don't know what is wrong with my setting or installed apps. Settings are import os import oscar # Path helper - going into /Users/dion/Dev/dioncoffee/x location = lambda x: os.path.join( os.path.dirname(os.path.dirname(os.path.realpath(__file__))), x) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '=%*t%wzzw^hs5l2o@oq2ae-*&wde0bko4!hxl%=uqb$!5po$tt' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition from oscar import get_core_apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.flatpages', 'django_extensions', … -
Sending the selected dropdown value from react js to django ORM
I have frontend code in react that gives the selected value from dropdown. I want to send this value to the django views.py file so that I can use it in ORM for filtering. The option values for dropdown are also coming from django backend. The value selected in the dropdown is one of the Customer_Id s used for filter in ORM. Following is the react code. import PropTypes from 'prop-types'; import React, { Component } from 'react'; import ReactSelect from 'react-select'; class Select extends React.Component { static propTypes = { onChange: PropTypes.func, name: PropTypes.string, value: PropTypes.string, }; constructor(props) { super(props); this.state = { error: false, value: props.default, }; this.handleChange = this.handleChange.bind(this); } handleChange(event) { this.setState({value: event.target.value}); } render() { let dropdowns = this.props.state.dropdowns; let optionitems = dropdowns.map((dropdown) => { return( <option key={dropdown.auto_increment_id} value={dropdown.auto_increment_id}> {dropdown.customerName} </option> ); } ); return ( <div> <select value={this.state.value} onChange={this.handleChange}> Select Customer Name {optionitems} </select> <p>{this.state.value}</p> // want to send this value to views.py </div> ); } } export default Select; Following is the views.py code: from psiApp.models import Proactive,CustomersName from psiApp.serializers import LogSerializer,CustSerializer from rest_framework import generics # Create your views here. The following class is for handling GET and POST requests class ListView(generics.ListCreateAPIView): … -
Python Django Create Worker Thread and Stop Worker Thread
I have a questions regarding threads in Django Python. I want to create a view with two buttons, the first one starts a simulation in the background and the second button can stop the simulation at any time in the background. But I already tried to work with threading.Threads() and also with background_tasks, but I did not managed it to stop the process at any time. Is it somehow possible? view-function: def change_calculating_status(request, component_id): try: obj = get_object_or_404(Component, pk=component_id) except ValueError as e: print(e) raise Http404 if(obj.calculation_running == True): obj.calculation_running = False elif(obj.calculation_running == False): obj.calculation_running = True if(obj.shortest_path == False): obj.shortest_path = True sp.run_simulation() obj.save() return HttpResponseRedirect(reverse('component',args=(component_id,))) HTML-Template: {% if component.calculation_running == True %} <form action="change_calculating_status"> {% csrf_token %} <input type="submit" id="start_calculation" onclick="disablestartenablestop()" value="Start Calculation" disabled=True /> <input type="submit" id="stop_calculation" onclick="enablestartdisablestop()" value="Stop Calculation" /> </form> {% else %} <form action="change_calculating_status"> {% csrf_token %} <input type="submit" id="start_calculation" onclick="disablestartenablestop()" value="Start Calculation"/> <input type="submit" id="stop_calculation" onclick="enablestartdisablestop()" value="Stop Calculation" disabled=True/> </form> {% endif %} Thank you a lot in advance! Best regards, Blacktiger800 -
Django filter class on many to many field
Hello i am pretty new to django and i am facing an issue. I have a user model that is linked to a group model through a many to many field. I want a custom filter class that would be able to return every instances of my user model that has a group with a group name containing a specific string. here is my group model containing the realation : class Group(models.Model): group_id = models.AutoField(primary_key=True) group_name = models.CharField(db_column='groupName', max_length=255) group_description = models.CharField( db_column='groupDescription', max_length=255, blank=True) created_by = models.EmailField(db_column='createdBy') created_date = models.DateField(db_column='creationDate', auto_now=True) group_users = models.ManyToManyField( User, blank=True, related_name='groups', through=UserGroup) i read the doc and did not found a way to do it. Has anyone ever done some thing comparable and give me a little help ? Thank you very much ! -
Django S3 minio
i currently try to implement minio as backend S3 storage for static and media files, this is working pretty well for the static files but not for the media files and i have no idea why. The joke on that is that the upload is working fine but if i do a get on the uploaded file django responses with the wrong port/404... django returns port 8000 for media files instead of 9000 the minio default port this is what i use for S3/Minio: https://django-minio-storage.readthedocs.io/en/latest/ this is what my config looks like: #S3 Storage STATIC_URL = '/static/' STATIC_ROOT = './static_files/' MEDIA_URL = '/media/' MEDIA_ROOT = './media/' DEFAULT_FILE_STORAGE = "minio_storage.storage.MinioMediaStorage" STATICFILES_STORAGE = "minio_storage.storage.MinioStaticStorage" MINIO_STORAGE_ENDPOINT = '127.0.0.1:9000' MINIO_STORAGE_ACCESS_KEY = 'ABCDEFG' MINIO_STORAGE_SECRET_KEY = 'HIJKLMNOPQRSTUVWXYZ' MINIO_STORAGE_USE_HTTPS = False MINIO_STORAGE_MEDIA_BUCKET_NAME = 'media' MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET = True MINIO_STORAGE_STATIC_BUCKET_NAME = 'static' MINIO_STORAGE_AUTO_CREATE_STATIC_BUCKET = True MINIO_STORAGE_STATIC_USE_PRESIGNED = True MINIO_STORAGE_MEDIA_USE_PRESIGNED = True If i remove MEDIA_URL and MEDIA_ROOT like on the Doc. example, i get the follwing error: django.core.exceptions.ImproperlyConfigured: Empty static prefix not permitted i first tought on that because of DEFAULT_FILE_STORAGE = "minio_storage.storage.MinioMediaStorage" Does smb. has an idea of how to handle media files with minio? what do i miss here? Seems to be an act of stupidity from … -
Trigger WebSocket server from http server
I use Nginx + uWSGI to deploy my Django app. Now I need use WebSocket to send message to connected client. So I use Nginx + Daphne to deploy WebSocket server which use Django Channels. The problem is I do not know how to trigger the web socket server to broadcast something to all clients. I searched the stackoverflow and just find one similar question Node js, Call WebSocket server from http server. But the solution is specific to NodeJS. So my question is: Should I call function of WebSocket server from HTTP Server? If so, How? And Whether has common method to implement the communication? If not, Should I just write all logic in WebSocket Server? Please help me. Thanks. -
invalid literal for int() with base 10: 'string'
I'm trying lookup the database that match specific campus_id. This works if I use integers, but doesn't work with strings. views.py def restaurants(request): query = request.GET.get('search', None) context = {} if query and request.method == 'GET': results = Restaurant.objects.filter(campus_id=query) context.update({'results':results}) return render(request, 'eatatdcu/restaurants.html', context) restaurants.html {% for x in results %} {{x.name}} , {{x.location}} <br> {% endfor %} -
Good practice to create accounts in django app
Question about architecture solutions / good practices I want to write an application where the user will be able to create an account. In addition, he will be able to add other users, with appropriate permissions. There will be teams in the application and no team can see what it is doing differently (it will not have access). Question - is it better to do it with a package like: Django Allauth? Is it a better idea to write it yourself and not worry that the package will not be updated to a specific version for Django? -
disable clean method in django admin inline model
I have a model which is OneToOne Related with another model. class Vehicle(models.Model): number = models.CharField(max_length=14) class Seat(models.Model): matierial = models.CharField(max_length=10) vehicle = models.OneToOneField(Vehicle, on_delete=models.PROTECT) def clean(self): """ This method is called before saving via admin panel """ if self.matierial == 'jute': raise ValidationError(_('Jute products are not allowed through admin panel')) Now, I am using inline model in admin panel like this class SeatInlineAdmin(admin.StackedInline): model = Seat extra = 0 class VehicleAdmin(admin.ModelAdmin): inlines = [SeatInlineAdmin] But I have one problem, If vehicle v1 is related to seat s1, and seat s1 is of jute matierial and I want to change the vehicle v1's number from admin panel, it throws me the error saying that 'Jute products are not allowed through admin panel' So, it means that it is attempting to save the Seat model through InlineAdmin when I'm trying to save the Vehicle. Is there any way I can bypass clean() method when calling from InlineAdmin? -
How to get the current URL linkable within a Django template?
Lets say my url is: /userpanel/send/sms I want to make option for user to get back to /userpanel/ once somebody click on /userpanel/send/sms . Or to userpanel/send/ once somebody click on userpanel/send/sms Is there a way to get all the possible separable urls? Im using {{ request.get_full_path }} But seems useless to archive my goal. -
DRF serializer return nullable fields
In a drf serializer, if a value is not in the post data, how do I still keep the field name with a null value? I'm using version 3.3.3 TYPES = [ ("abc", "abc"), ("def", "def"), ] class MySerializer(serializers.Serializer): choice = serializers.ChoiceField(choices=TYPES, required=True, initial=None) serializer = MySerializer(data={}) serializer.is_valid() print serializer.data Current output is {} Desired output is {'choice': None} -
logs inside django channels consumers not showing up
The following is my logging conf: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'debug.log', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } django_logger = logging.getLogger('django') logging.basicConfig() and the function to log as follows: def log_it(*args): try: django_logger.info(str(args).encode('utf-8')) return True except: django_logger.info('#### Exception in LOGGING!!!!!!') return False I am using this to log inside django consumers as follows: class EchoConsumer(SyncConsumer): def websocket_connect(self, event): try: log_it('inside EchoConsumer connect()', event) self.send({ "type": "websocket.accept", }) return True except: error = traceback.format_exc() write_error_log(error) return False def websocket_receive(self, event): try: log_it('inside EchoConsumer receive()', event) self.send({ "type": "websocket.send", "text": event["text"], }) return True except: error = traceback.format_exc() write_error_log(error) return False The log_it() used inside the consumers aren't being invoked. I checked if there was any problem in reaching the consumers in the daphne access logs. I also checked my nginx conf, but the connection requests were recorded as follows: 127.0.0.1:45100 - - [08/Oct/2018:19:00:58] "WSCONNECTING /ws/event/" - - 127.0.0.1:45100 - - [08/Oct/2018:19:00:58] "WSCONNECT /ws/event/" - - Note: I have linked /ws/event to EchoConsumer in routing.py Any … -
Wagtail PageQuerySet Querying
I have an NewsIndexPage and a NewsPage , on the Wagtail Admin using NewsIndexPage i have created a tree node where i have NewsIndexPage-->Corporate(this is NewsIndexPage) and i have Travel (NewsInndexPage) like this Corporate-->Travel--> News Stories I can query as so NewsPage.objects.live().order_by('-last_published_at') how can i query and display stories from Travel i have done so NewsPage.objects.live().filter(slug='corporate').order_by('-last_published_at') but how can i do that for Travel as NewsPage.objects.live().filter(slug='travel').order_by('-last_published_at') --- this doesnt work , how can i filter and get all pages on the Travel -->NewsPage(This holds the news stories) -
Forward and reverse query to ManyToMany relation Django
I have this model: class Task(MPTTModel, TimeStampedModel, StartFinishModel): name = models.CharField(max_length=256) start_after_end = models.ManyToManyField('self', related_name='s2e_relation', blank=True) #s2e means that task can't start before related tasks end How can I get all tasks, which can't start before this task ends and all tasks, which have to end before this task can start. Let's say 1 -> 2 -> 3 I have id 2. I want to find 3 and with another query 1. To find 3 I can use Task.objects.get(id = 2).start_after_end.all() How can I find 1? -
Django: Instanciation of a model using a hash of a ForeignKey
I'm currently trying to implement an API in Django Rest for a class project that's supposed to store data in a secure way. I have two different models: class Driver(models.Model): name = models.CharField(max_length=100, blank=False, null=False) and import Driver class Car(models.Model): name = models.CharField(max_length=100, blank=False, null=False) driver = models.ForeignKey(Driver, on_delete=models.CASCADE) Currently, there's a mapping between cars and their respective drivers. I'd like to map a car not to it's driver, but to the result of a hash function applied to it's driver name. Something like: import Driver import hashlib class Car(models.Model): name = models.CharField(max_length=100, blank=False, null=False) driver = hashlib.md5(models.ForeignKey(Driver, on_delete=models.CASCADE).name).hexdigest() I know what I wrote above is probably heretical in Django, it is just to convey the idea of what I want to do! I thought about overriding the Car model's init, save, create functions in order to do this, but have strictly no idea what is the good option. At the end of the process I'd like that there's no mapping between the Car and it's Driver, but a Driver's car could be found using the hash of his name. Let me know if this is unclear or if you need more precision! Any help would be appreciated, Thanks! -
How to show variable data for debugging in django
I still cant figure out, how to debug in django best way. For example, I created a dict and now I would like to check all the data that is arranged in that dict. How can I force django to show a debugging page in browser and print out the dict in a comfortable way? -
I have a dictionary sent by ajax and i want to get it into django view without getting them by key
I have sent a dictionary using ajax request in javascript and i want to get it without specifying "request.post['key1']" I have dine this in my view: def editPermission(request): array={} array = request.GET('data') But i'm getting this error : Query dict is not callable -
Multiple forms for Views.py
I have created a one to many relationship but yet I still get error. What could I be doing wrong.Is it okay to create multi forms also? I am new to python. Is it possible to create two modelforms with two models and put in the views.py file.How do I do that? forms.py from django import forms from .models import Diseases, Gender class GenderForm(forms.ModelForm): class Meta: model = Gender fields = 'Gender' class DiseaseForm(forms.ModelForm): class Meta: model = Diseases fields = ['Diseases'] Models.py from django.db import models from django.db.models import Count from itertools import groupby Gender_Choice = ( ('Male', 'MALE'), ('Female', 'FEMALE'), ) Diseases_Choice = ( ('Cholera', 'CHOLERA'), ('HIV', 'HIV'), ('Malaria', 'MALARIA'), ('Typhoid', 'TYPHOID'), ('Measles', 'MEASLES'), ) class Gender(models.Model): gender=models.CharField(max_length=19, choices=Gender_Choice , default='Male') def __str__(self): return self.gender class Diseases(models.Model): gender = models.ForeignKey(Gender, on_delete=models.CASCADE) diseases = models.CharField(max_length=19, choices=Diseases_Choice , default='Malaria') def __str__(self): return self.diseases Views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import NameForm from django.views.generic import ListView, CreateView, UpdateView from . models import Gender, Diseases from django.db.models import Count from django.views.generic.list import ListView class CreateMyModelView(CreateView): model = Gender, Diseases form_class = NameForm template_name = 'checkmate/name.html' success_url = 'result' context_object_name = 'name' class MyModelListView(ListView): template_name = 'checkmate/result.html' context_object_name … -
Django Admin: Link to Admin-Interface of ForeignKey beneath add and modify
I have a django model called Remote There is a model which has a ForeignKey to "Remote". This gets displayed like this in the django admin: There are two icons beneath the drop-down: "modify" and "add". It would be very cool if I could have a third icon: A link to the admin page of the given Remote instance. How could this be done? Some kind of re-usability would be nice, since I want this feature for several admin pages.