Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run flask javascript basis on python condition?
I want to show a graph but my issue is i want to show graph basis on some if-else condition , I am new in flask and javascript so please guide me : This is my flask app: from flask import Flask, render_template import pandas as pd import json app = Flask(__name__,static_url_path="/static") @app.route('/message', methods=['POST']) user_input=input('Do You want to see graph?') def reply(): if input=='Yes': #how to show graph in this conditon? else: print("data is not available") @app.route("/") def index(): df = pd.read_csv('data.csv').drop('Open', axis=1) chart_data = df.to_dict(orient='records') chart_data = json.dumps(chart_data, indent=2) data = {'chart_data': chart_data} return render_template("index.html", data=data) I want if user input is 'Yes' then it show the graph otherwise don't show the graph. But currently its showing graph all the time. graph function is function draw in javascript : <!DOCTYPE html> <html > <head> <style>#content { position: absolute; bottom: 230px; margin-left: 200px; } /* set the CSS */ #content1{ position: absolute; bottom: 0px; right: 0px; } path { stroke-width: 2; fill: none; } .axis path, .axis line { fill: none; stroke: grey; stroke-width: 1; shape-rendering: crispEdges; } .area { fill: #F0F8FF; stroke-width: 0; } </style> <meta charset="UTF-8"> <title>Information</title> <link rel="stylesheet" href="static/css/normalize.css"> <link rel='stylesheet prefetch' href='https://fonts.googleapis.com/css?family=Open+Sans'> <link rel='stylesheet prefetch' href='/static/js/jquery.mCustomScrollbar.min.css'> … -
Django model.. calculate the sum of horus fields
I'm new to this and I need some help on designing a Django model. i got tow columns (total_delivered_hrs and total_no_show_hrs) i need to calculate the sum of thsoe columns... the format is HH:MM -
Django: can't access OneToOneField after rendering TemplateView
I am new to Django and don't understand what really is causing this: I have a Model Company which has an OneToOneField, creator. # models.py class Company(models.Model): class Meta: verbose_name = 'Company' verbose_name_plural = 'Companies' creator = models.OneToOneField(User, related_name="company", on_delete=models.CASCADE, unique=False, null=True) name = models.CharField(max_length=50) I have a TemplateView class to handle get and post requests for creating a Company model: # views.py class create_company(TemplateView): def get(self, request): form = CompanyCreateForm() title = "Some form" return render(request, "form.html", {"form": form, "title": title}) def post(self, request): form = CompanyCreateForm(request.POST) if form.is_valid(): comp = form.save(commit=False) comp.creator = request.user comp.save() return redirect('index') The form is showing correctly also storing when I submit, the problem I am facing is with base.html where I show {% user.company %}; the form template extends it like: {% extends "account/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <form method="post" action=""> {% csrf_token %} {{form|crispy}} <button class="btn btn-success" type="submit">Save</button> </form> <br> </div> <br> {% endblock %} and in base.html I access {% if user.is_authenticated %} {% user.company %} {% endif %} But user.company is not showing even it is set; it shows only when I redirect to index but not when I render the form. … -
Gulp unhandled error 182
I have a django blog project, and am trying to use bower to manage my packages. When running 'gulp' from my console, I get the following error : (py3) ➜ nomadpad git:(master) ✗ gulp [15:16:15] Using gulpfile ~/code/nomadpad/gulpfile.js [15:16:15] Starting 'css'... [15:16:16] Finished 'css' after 1.23 s [15:16:16] Starting 'html'... [15:16:16] Finished 'html' after 3.38 ms [15:16:16] Starting 'scripts'... [15:16:16] Finished 'scripts' after 4.43 ms [15:16:16] Starting 'default'... [15:16:16] Finished 'default' after 38 μs events.js:182 throw er; // Unhandled 'error' event ^ CssSyntaxError: /Users/davidmellor/code/nomadpad/bower_components/jquery/dist/jquery.js:756:9: Unknown word at Input.error (/Users/davidmellor/code/nomadpad/node_modules/postcss/lib/input.js:119:22) at Parser.unknownWord (/Users/davidmellor/code/nomadpad/node_modules/postcss/lib/parser.js:506:26) at Parser.other (/Users/davidmellor/code/nomadpad/node_modules/postcss/lib/parser.js:171:18) at Parser.parse (/Users/davidmellor/code/nomadpad/node_modules/postcss/lib/parser.js:84:26) at parse (/Users/davidmellor/code/nomadpad/node_modules/postcss/lib/parse.js:24:16) at new LazyResult (/Users/davidmellor/code/nomadpad/node_modules/postcss/lib/lazy-result.js:70:24) at Processor.process (/Users/davidmellor/code/nomadpad/node_modules/postcss/lib/processor.js:117:12) at /Users/davidmellor/code/nomadpad/node_modules/gulp-postcss/index.js:51:12 at <anonymous> at process._tickCallback (internal/process/next_tick.js:169:7) My bower.json in the root folder looks like this : { "name": "blog_postcssgulp", "description": "", "main": "gulpfile.js", "authors": [ "DMells <dave@davemellor.com>" ], "license": "ISC", "homepage": "https://github.com/DMells/nomadpad", "ignore": [ "**/.*", "node_modules", "bower_components", "test", "tests" ], "dependencies": { "jquery": "^3.3.1", "modernizr": "^3.5.0" } } I'm not sure what to do here, please can anyone assist? Many thanks -
django url error: ImportError: cannot import name patterns are not running
Python Version: 3.6 Django Version: 2.0 When I type python manage.py runserver it shows me -
How to correctly create a POST method for nested serializers in django rest framework
I have a serializerclass which is like this: class EmployeeSerializer(serializers.ModelSerializer): bio = BioSerializer() # designation = GroupListSerializer() # department = GroupListSerializer() class Meta: model = Employee fields = ['user','bio','tax_id_number','account_number','joining_date','designation','department'] How do I make a POST method for this in django correctly: So far this is what I have: class EmployeeCreateView(generics.CreateAPIView): queryset=Employee.objects.all() serializer_class=EmployeeSerializer def post(self, request, format=None): designation = Group.objects.get(id=request.data['designation'],) department = Group.objects.get(id=request.data['department'],) user =User.objects.get(id=request.data['user'],) bio =Bio.objects.get(id=request.data['bio'],) # user=User.objects.get(id=request.data['user'],) employee = Employee.objects.create( tax_id_number=request.data['tax_id_number'], account_number=request.data['account_number'], joining_date=request.data['joining_date'], designation =designation, department =department, user=user, bio=bio, ) return Response(status=status.HTTP_201_CREATE D) But when i make a post request I get the following in my logs: MultiValueDictKeyError at /hr/employee_create/ "'bio'" -
django-channels/websockets: WebSocketBadStatusException: Handshake status 500
I am following this tutorial: https://gearheart.io/blog/creating-a-chat-with-django-channels/ And I get this error with the following code while running manage.py runserver File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.6/dist-packages/websocket/_core.py", line 220, in connect self.handshake_response = handshake(self.sock, *addrs, **options) File "/usr/local/lib/python3.6/dist-packages/websocket/_handshake.py", line 69, in handshake status, resp = _get_resp_headers(sock) File "/usr/local/lib/python3.6/dist-packages/websocket/_handshake.py", line 135, in _get_resp_headers raise WebSocketBadStatusException("Handshake status %d %s", status, status_message) websocket._exceptions.WebSocketBadStatusException: Handshake status 500 Internal server error: No route found for path ''. -
Assign users to group in django via HTML template and not via admin
I have created a django app in which users can register via SignUp Form.I have created two groups Admin Users and Staff Users.When any user signs up he is not allocated to any of the group.I want to create a webpage where all the users will be displayed and there should be a dropdown in front of user names which will let the logged in user( a member of Admin User group,I will restrict this page to Admin Users group only) to select the group among the available groups.In simple words any member of group Admin User should be able to add any other member who is not assigned to any group. I need a basic help on how the views.py and HTML page should be look like -
Autocomplete on multile fileds from Api -DRF
I am trying to filter on the api list using auto-completion.I am able to filter on single field but not on multiple fields. In html file- <div class="form-group"> <b>Player</b> <input resource="{% url 'api:player-list'%}" id="search_player_autocomplete" class="form-control" placeholder="-type player-"> </div> In js file - function attachplayerAutoCompleteList(plasListInput, hiddenPlasIdInput){ $(plasListInput).autocomplete({ source: function( request, response ) { $.ajax({ url: $(plasListInput).attr('resource'), dataType: 'json', data: { first_name: request.term, ordering: 'last_name' }, success: function(data) { response($.map( data, function( item ) { return { ---- } }); In above code..data: { first_name: request.term, ordering: 'last_name' }, The request.term searches in first name of the list.but I want to use auto-complete on one more field named last_name from the fields. Please help. -
Django REST api offline synchronization with PouchDB
I am developing an application which is used by multiple clients and the main goal of the app is to be used online. But a specific requirement is, it should be able to work offline too (only for a single client(s) in an emergency situation and for short time - 24 hours maximum). now I am using Django REST framework for backend and Jquery/AJAX frontend for GET and PUT etc. requests which update PostgreSQL DB on the backend. Now little research on the internet suggests the I should use PouchDB on the frontend and/or CouchDB on the backend. But my questions are: Is it really possible? If yes, then which DB should be used for the backend database? When the offline client become available online, how we can synchronize the data generated online? Can we cache some data on clients machine for offline availability purpose? Is it still possible to use PostgreSQL for the backend? (I really want to use it !) -
raising 403 forbidden in django-rest-framework doesn't work
I am using django rest framework to make user submit their works.I am restricting the user submissions according to their subscribed plan. I am doing that by raising 403 forbidden with a message whenever user tries to add more than his quota. This is what I wanted and it works perfectly in localmachine. but it shows a weird "OOPs something went wrong" message on my staging.In preview it shows "Failed to load reponse Data". I don't know why. I used the same staging database on local machine. Even then it worked. The code I used for the both places are same. please help me out. Thanks -
Which chart technique is best to implement live charts
I have a chart which is loaded with previously collected data.I am using High-chart to display it. $.getJSON('https://coincap.io/history/365day/'+coin.toUpperCase(), function (data) { console.log(data) // Create the chart Highcharts.stockChart('chart', { rangeSelector: { selected: 1 }, title: { text: name.toUpperCase()+' - '+coin.toUpperCase() }, series: [{ name: name.toUpperCase()+' price in USD', data: data.price, type: 'spline', tooltip: { valueDecimals: 2 } }] }); }); } I would like to modify this chart with a live data(ie, which is served from a web socket). But I dint know which chart is used for it. Currently there is a small delay for showing it.I would like to avoid the time delay in each time. Please suggest some techniques for it. -
How to Invoke external services with slash commands in python/django?
I'm working in this Slack app, where my coworkers created an Slack command that does several things, for example: /command laugh /command repeat /command read etc, right now I need to create a subcommand (i.e like laugh, read, etc) which is going to return to us all the details from an API that we're working with. Let me show o¡you my code, and the explain my consternation: This is the Django Rest API structure: [ { "title": "Project 1", "description": "Projects for x", "members": [ { "minutes_last_week": 0, "latest_activity": "1514", "id": 7, "minutes_today": 0, "minutes_total": 300, "last_name": "OLAJS", "first_name": "XXXX" }, { "minutes_last_week": 0, "latest_activity": "1516645564", "id": 23, "minutes_today": 0, "minutes_total": 1620, "last_name": "XJKD", "first_name": "SKDJND" }, ] And this is how I'm consuming it through my Django project: class NewCommand(CommandMixin, slack.Command): def execute(self, request): response = requests.get('http://project.herokuapp.com/api/v1/activities/?format=json', auth=('xxxx','xxxx')) apiresponse = response.json() self.send_response('newcommand') If I add a print statement in my apiresponse I'm able to obtain my entire JSON with all the required information, but right now I have to big doubts: How can I return this information through my slack subcommand? I know that I need to filter the information accordingly which clients is typing the command and subcommand, … -
How to require only one of two fields at the form level
Users only have to fill out one of two fields. How would I require this? And where would it be? I'm trying to put it in the save, but I believe it belongs elsewhere since the validationerror pops up as a Django error screen, and not a field validation error. Here's what I've tried: class SignupForm(forms.Form): learn1 = forms.CharField(max_length=50, label='Learn', required=False) teach1 = forms.CharField(max_length=50, label='Teach', required=False) class Meta: model = Profile def save(self, user): if not self.cleaned_data['learn1'] or self.cleaned_data['teach1']: raise forms.ValidationError("Specify at least one") user.is_profile_to.learn1 = self.cleaned_data['learn1'] user.is_profile_to.teach1 = self.cleaned_data['teach1'] user.save() user.is_profile_to.save() -
Is OAuth2 TokenScope similar to Django Permissions?
I'm building a dedicated OAuth2 as a service for my application, where users will be both authenticating and authorizing themselves. I've the following concerns 1) Is OAuth2 TokenScope similar to Django Permissions? 2) If there are some application-specific permission, do I need to replicate the permissions on both my Resource server and Auth Server? -
When is ValueError triggered in django both in create and update and how can I fix it?
class Company(models.Model): name = models.CharField(max_length=200, help_text="Enter Company name") class Product(models.Model): company = models.ForeignKey('Company', on_delete=models.SET_NULL, null=True) class Inventory(models.Model): product = models.ForeignKey('Product', on_delete=models.SET_NULL, null=True) class InventoryForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(InventoryForm, self).__init__(*args, **kwargs) self.fields['product'] = forms.ChoiceField( choices = self.grouped_products ) def grouped_products(self): grouped_list = list() grouped_list.append(("","-- select product --")) for company in Company.objects.all(): grouped_list.append( ( company.name, list( (p.id, p.name) for p in Product.objects.filter(company=company).order_by('name') ) ) ) return grouped_list def clean_product(self): product_id = self.cleaned_data['product'] product = Product.objects.filter(pk=product_id) return product I updated the product field in InventoryForm so I can display a grouped selection based on company, but now when I tried to save or update inventory I get this error Exception Type: ValueError at /admin/catalog/inventory/7/change/ Exception Value: Cannot assign "'5'": "Inventory.product" must be a "Product" instance. I understand that the selected product has an id of 5 and it cannot assign that value to Inventory.product so I added a def clean_product(self) method to return the real product object based on id but it's not working. -
400 Error when visiting Django domain in production
I have a Django app that I've deployed to production on Heroku. I have a settings package with different settings for local and production. In my local settings, I have DEBUG set to True and I'm able to both run the server and load the homepage. In my production settings module, everything is identical except for DEBUG being set to False and the addition of hostnames to ALLOWED_HOSTS. For some reason, when I try to access the site (either locally or on heroku) with the production settings, I'm getting a 400 Bad Request. I think there might be something wrong with the format of my hostnames but I'm not sure: ALLOWED_HOSTS = ['https://test_app.herokuapp.com/','http://127.0.0.1:8000/'] What could be causing the 400 error? Should the urls be formatted differently? -
Form not Displaying fields (Not seeing a forms.Forms object) - Django 1.11.8
I am trying to display a simple form (3 fields) on a webpage using Django but no fields are displaying - see code below. I've gone through the Django doc, MDN doc, most of the StackOverflow posts here, but it's still not working. I was able to see, using {% debug %}, that there is no object EmailInput on the page. At this point, I am not sure what is causing this issue. Any help would be very much appreciated. Thanks forms.py from django import forms class EmailInput(forms.Form): email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() views.py from django.shortcuts import render from .models import journalEntry from django.http import HttpResponseRedirect from django.urls import reverse from journal.forms import EmailInput def index(request): post = journalEntry.objects.filter(status__exact='f') latest_post = journalEntry.objects.filter(status__exact='f').order_by('-created')[:5] return render(request, 'journal_index.html', context = {'post':post,'latest_post':latest_post}) def email_input(request): if request.method == 'POST': form = EmailInput(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('journal-index')) else: form = EmailInput() return render(request, 'journal_index.html',{'form':form}) journal_index.html {% extends "base_generic.html" %} {% block content %} <form action="" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"/> </form> {% endblock content %} urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='journal-index'), ] -
Avoid Multiple submits in Django
I am using auto submit in my forms. Form gets automatically submitted when 10 digits are entered in the number field. This actually comes from USB RFID card reader upon scannig the card (It works as keyboard emulator). I compare the number with the existing numbers in the database and then identify the user and perform some database transactions. What happens is that the card reader reads the number multiple times, and due to that before all the database transactions complete for that input, another input is accepted (same number) within 1s and the consistency is lost before the first transaction is fully completed. Kindly advise. VIEWS.PY File: @login_required def markattdview(request): # for val in studmst.objects.filter(ccownerid=request.user.id) # TO DOooo # select studid from attddetail where studentID= (select student ID from studmst where ccownerid = currentuser.ID) # lastattd=attddetail.objects.filter() # Showing last 10 users whose attendance have been marked by the logged in user # form_attd = markattdform() attdsuccess = "" identified_user = "" identified_studname="" loggedin_userid=request.user.id loggedinuser=request.user.username print("Logged in User : " + loggedinuser) if request.method == 'POST': studmstobj = studentmaster() attdform = markattdform(request.POST) unknown_cardno = request.POST.get('cardno') if attdform.is_valid(): # form_attd.punchtime = datetime.datetime.now() # attdform.save(commit=True) obj = attdform.save(commit=False) obj.punchtime = datetime.datetime.now() attdsuccess … -
Creating/Copying/Removing DBs dynamically
I know that I can employ using() to select a DB that is defined in settings.py for operations such as: User.objects.using('users_db').get(id=5).delete() The problem is that I need to dynamically create/copy/delete several different DBs while the server is running (without restarting the server). So it's not possible to define all the DB's in settings.py before running the server and select the active DB in my code by using(). -
Serving static content from subdomain
I do not find information to serve static file from cookie free domain. I thought that the variable STATIC_URL was used like this: Setting.py: STATIC URL = 'http://media.staticfiles/testsite/static/ Template: <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css" media="screen" /> But I have read that this practice is really bad... so I do not know how to do it. -
Reverse django admin custom url with reverse
I have model admin view to which I added custom view like below. Then I'm using jQuery to upload a csv file. def get_urls(self): urls = super(MyAdminView, self).get_urls() my_urls = [ path('upload_csv/', self.upload_csv, name='upload_csv'), ] return my_urls + urls My problem is that I don't know how to reverse url to that view in tests. -
How to Integrate My React native app with Django?
Could you please tell me the Integration process of React native with django Is there any integrated Repositories on Github? Please suggest me... -
Is django serializer use select for update internally when I use it for update the records?
If I use django serializer for update the record can serilizr internally use select_for_update() example: task = Demo.objects.get(id=1) serilizer = DemoSrilizer(task, data=request.data) serilizer.save() task is object and in request.data sending the updated data can DemoSrilizer use select_for_update() internally or I need to override update method of serilizer. -
DJANGO Generic views to update model/delete model
The following method is my original step: class tasks(APIView): def get(self, request, format=None): pass def post(self, request, format=None): pass def put(self, request, format=None): pass def delete(self, request, format=None): pass I am trying to simplify this code by relying on DRF's concept of generic views. That would me I would need to use two views (one for lists and the other for detail), which will better adhere to RESTful API design. This has been my attempt so far: class Tasks(generics.ListCreateAPIView): queryset = Tasks.objects.all() serializer_class = MemberSerializer def list(self, request): queryset = self.get_queryset() serializer = MemberSerializer(queryset, many=True) return Response(serializer.data) This creates two endpoints GET/POST, how would I replicate my API view method so it also supports PUT and DELETE?