Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Build a one-page website that show results from InfluxDB query (Python? Node js? React?)
I have a InfluxDB database sat on an Ubuntu VM. I've written some basic Python code to run through some dates and pull out summary results from the influx database based on hard-coded (for now) calculations. What i'd like to do is to create a basic one page website (on a new VM) to go out on there on the web, where I can feed variables from pre-canned dropdown boxes (to create the calculations), fire off the script, then display the results on the page. Then ultimately show a graph, but i'd be happy with a table of results for starters. Apart from knowing a small amount of HTML from way back when, I no experience of creating websites. Wordpress doesn't count does it? :) I've seen Flask and Django mentioned from the Python side, but I can't see too much about an Influx client for those or whether they would be suitable? When I look at Node I see a fully fledged Influx API https://github.com/node-influx/node-influx So do I go down the React js route? Its all a bit daunting and unclear what is the best path to take. I'd be learning something from scratch whatever route I take. Any … -
How to change the response structure
I am facing one issue to change the following structure..... THis is the structure I am getting { "labels": [ "List A", "List B", "List C", "List D" ], "data": [ 19, 25, 30, 32 ], "colors": [ "#e15759", "#f28e2b", "#76b7b2", "#4e79a7" ], } But I want to change the following data in to the following method { "category": "List D", "value": 32, "colors": "#e15759" }, { "category": "List C", "value": 25 "colors": "#f28e2b" }, { "category": "List B", "value": 30, "colors": "#76b7b2" }, { "category": "List A", "value": 19, "colors" : "#4e79a7" } Here is my code class AbcListAPI(APIView): def get(self, request, format=None): a = data_fuction() return Response(a) In this code I am getting this response from a function data_fuction that is used in another part of my code.... So I am unable to edit that response from there ..... But in this function I need to format this code .... -
How do I get a url using "requests" in host adapter only? I keep getting HTTPSConnectionPool NewConnectionError
The error I keep getting when I try to run url The code I'm using -
Django Outer Join
I'm creating a small web application to track my orders, i have two models: Order(models.Model) " This model to record the new orders" class Order(models.Model): customer= models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) product= models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=CATEGOTRIES) note = models.CharField(max_length=200, null=True) OrderHistory(models.Model) " This model to record the changes for each order in any field" version_num = models.AutoField(primary_key=True) Order = models.ForeignKey(Order, null=True, on_delete= models.SET_NULL) customer= models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) product= models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True) note = models.CharField(max_length=200, null=True) View: def update_orders(request,pk): theOrder = Order.objects.get(id=pk) theHistory = createOrderHistory({ 'Order': theOrder.id, 'customer': theOrder.customer, 'product': theOrder.product, 'date_created': theOrder.date_created, 'status': theOrder.status, 'note': theOrder.note }) print('The History of the order ',theHistory) UpdateForm = createOrder(instance=theOrder) theid = pk if request.method == 'POST': UpdateForm = createOrder(request.POST,instance=theOrder) if theHistory.is_valid(): if UpdateForm.is_valid(): theHistory.save() UpdateForm.save() return redirect('home') else: UpdateForm = createOrder(instance=theOrder) context = {'UpdateForm':UpdateForm} return render(request,'accounts/updateOrder.html',context) In the View update_orders function am taking the current order and save it into OrderHistory and then i save the new changes into Order Model it's working fine but the OrderHistory Model is not including the new change. orderHistory to get the history of the order def orderHistory(request,pk): theHistoryOfTheOrder … -
Mocking django tests - why is this patched function still being called?
I'm trying to test a function in one of my models, and am trying to to mock out the filesytem using mock.patch. No matter what I try, it doesn't seem to intercept the method. Model to test: app/models.py from django.db import models from .utils.storageutils import get_file from .utils.datautils import derive_data Class DataThing(models.Model): #defined here def set_data_from_file(self): data = derive_data(get_file('filepath')) setattr(self, 'derived_data', data) self.save() app/utils/datautils.py import pandas as pd def derive_data(data_from_file): df = pd.DataFrame('...') #do stuff with dataframe return df app/tests/unit_tests/tests_models.py from django.test import TestCase import mock from app.models import DataThing class DataThingModelTest(TestCase): @classmethod def setUpTestData(cls): cls.datathing = DataThing @mock.patch('app.models.derive_data') def test_set_data_from_file(self, mocked_derive_data): mocked_derive_data.return_value=('pretend_dataframe') self.datathing.set_data_from_file() self.assertEquals(self.datathing.derived_data, 'pretend_dataframe') I would expect this to pass. However, I get an error, because datathing.set_data_from_file() is still ultimately calling utils.storageutils.get_file. I've tried patching in app.utils.datautils.derive_data but have the same issue. -
Call View Function and send FCM Without Refresh Page Using AJAX In Django
When i click on a href they go on Script code but form Script not call the views.py function! Link code:: <a class="likebutton" href="#"> <span id="unlock"> <i class="fas fa-lock"></i>&nbsp;Send Message </span> </a> Script code:: <script type="text/javascript"> $('.likebutton').click(function(){ $.ajax( { type:"GET", url: "sendnotification", success: function(){ alert('Done') } }) }); </script> urls.py:: url(r"^sendnotification",views.sendnotification,name='sendnotification'), views.py:: @csrf_exempt def sendnotification(request): if request.method == 'GET': push_service = FCMNotification(api_key="*********") registration_id = "****************" data_message = { "Nick" : "Mario", "body" : "great match!", "Room" : "PortugalVSDenmark"} result = push_service.single_device_data_message(registration_id=registration_id, data_message=data_message) return HttpResponse('success') -
Django Rest Frame in oTree
Does anyone have experience with the Django Rest Framework being applied into a oTree project. I want to serialize a query of saved chat messages saved from a chat application and send them as JSON to websocket so they can be shown in the frontend. When I serialize with the from django.core.serializers import serialize function and parse it in the frontend i don't get a desirable JSON object but just a JSON in a string. models.py class Message(models.Model): content = models.TextField() timestamp = django_models.DateTimeField(auto_now=True) player = models.ForeignKey('Player', on_delete=models.CASCADE, null=True) def last_15_messages(self): return Message.objects.order_by('-timestamp').all()[:15] consumers.py async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] messages_from_db = serialize('json', Message.last_15_messages(self)) messages_from_db_json = json.dumps({ 'messages_from_db': messages_from_db }) # Send message to room group await self.channel_layer.group_send( self.room_name, { 'type': 'chat_message', "message": { "chat_message": message, "db": messages_from_db_json } } ) play.html socket.onmessage = event => { let data = JSON.parse(event.data).message; let db = JSON.stringify(event.data).message.db; console.log(db); }; I have added two images one displaying the json of the query in the backend and the received string in the javascript console in the frontend. Backend Image Frontend Image -
I am not able to open admin page
Once i go into localhost:8000/admin the browser says: Firefox can’t establish a connection to the server at 127.0.0.1:8000. I am using PyCharm: This is the error that comes up in the terminal: Not Found: / [21/Apr/2020 15:18:20] "GET / HTTP/1.1" 404 2031 Following which the server cuts off my app/urls: from django.urls import path from . import views urlpatterns = [ path('', views.index), ] And my project/urls: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('KMIO_page/', include('KMIO_app1.urls')), ] -
Storing Access Token in httponly Cookie but user can still see it in Network tab of Chrome Dev Tools?
I am using django to create a python backend and am storing the user's access token and refresh token in httponly cookies so I can authenticate requests to my backend. 1) Is this the right way to do this? 2) I know that httponly prevents seeing the cookie using 'document.cookie', but you can still see the cookie by analyzing the network tab in Chrome Dev Tools. Is this fine because only the user can see it (not other people)? Or is this still bad? -
I want to apply flex to django template would you see this?
I have a question current code is this {% if object_list.exists %} {% for p in object_list %} <div class="d-flex flex-wrap"> <div class="col-sm-4"> <div class="card"> <div class="card-body"> <h5 class="card-title">{{p.title}}</h5> <p class="card-text">{{p.description}}</p> <a href="{% url 'challenge:lecinfo_list_for_challenge' p.title %}" class="btn btn-primary">go</a> </div> </div> </div> </div> {% endfor %} {% else %} <tr> <td colspan="6"> <h4>no subject!</h4> </td> </tr> {% endif %} and current result is this I want to change like this is this possible? Is it possible to use bootstap or flex? Thanks for the specific way I did a search, but I'm not sure what to do. https://codepen.io/trufa/pen/rmwLzJ -
Specific Time interval by user
While using a start_time and end_time in an HTML file for django application. I have used the time tag as follows: <div>Start Time <input type="time" min="" max="" id="" name="start_time"></div> <div>End Time <input type="time" min="" max="" id="" name="end_time"></div> But the constraint here is - the user will give the timings varying from 5:00 AM to 4:59 AM. So, can anyone suggest what values should we need to have as min and max for start_time and end_time in the tags. Any other workaround is also welcomed. -
Not able to apply migrations to Django application. Facing this issue from a long time
the error is something like this - raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (no schema has been selected to create in LINE 1: CREATE TABLE "django_migrations" ("id" serial NOT NULL PRIMA... ^ ) These are my database settings # Database Settings export DB_NAME='qbo' export DB_USER='' export DB_PASSWORD='' export DB_HOST='localhost' export DB_PORT='' And I also have given all privileges to the user - Can someone explain way this issue is actually happening? -
How To Create A Socail Media App With Python?
I Want To Create An Social Media App Purely With Python. I Just Listed Out What And All To Learn. So Please Check The List And Tell I Am Correct Or Wrong. To Create A Social Media App With Python I Must Know : Python Kivy Postgreql Sockets The Manin Question Is Below : Is There Anything Else I Need To Study Or These Things Are More Than Enough. By The Way In What Order I Am Supposed To Complete This. I Know Python. Next I Must Go With What ? Kivy Or Postgreql Or Sockets . Thank You In Advance -
How to stage forms in Django?
I have form data that I gather in the views. What the user inputs will determine what the next form will be like. Should I create another view? If so, how do I pass on variables from one view to another? And should the separate view render a different html page? Or is there a way to work in the same view that I gathered the data initially? The view looks like this: def admission(request): if request.method == 'POST': form = DeterminingForm(request.POST) if form.is_valid(): selected_season = form.cleaned_data['season'] selected_batch = form.cleaned_data['batch'] form = DeterminingForm() context = { 'form': form, } return render(request, 'admission.html', context) -
How to filter ManyToMany fields in django?
I have two classes: class A: name tags = manytomany(B) class B: name I need to get A-objects, which contain all elements of tag_list: tag_list = array of several B pk's A.objects.filter(tags__contains=tag_list) How can I write this ORM-queryset? -
Django, sum of values in form, then submit to database
Say for example I have this. Take the input fields, and add via the calculate button. I tried using django-mathfilters inside of my html file, but then I realized that the fields would always be empty beforehand, so nothing would ever be calculated. What is the right approach to this? Do I need to split Final_Result from my book table? Book Price: $10 (input field) Delivery charge: $3 (input field) Delivery type: $5 (input field) Final Result: (result of adding the fields above when user clicks the calculate button [calculate] [submit] submit button will finalize the results and sent the values to the database. This is my model for the table class book(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) book_price = models.IntegerField() delivery_charge = models.IntegerField() delivery_type = models.IntegerField() final_result = models.IntegerField() views.py for the form def final_price(request): if request.method == 'POST': form = RequestForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect('final_price') else: form = RequestForm() args = {'form': form} return render(request, 'final_price.html', args) Model for to allow me to edit the fields in my book module class RequestForm(forms.ModelForm): class Meta: model = book fields = ( 'book_price', 'delivery_charge', 'delivery_type', ) I tried adding them through the … -
TypeError: title() missing 1 required positional argument: 'request'
Traceback (most recent call last): File "C:\Users\danfi\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\danfi\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\danfi\AppData\Local\Programs\Python\Python38-32\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 975, in _find_and_load_unlocked File "", line 671, in _load_unlocked File "", line 783, in exec_module File "", line 219, in _call_with_frames_removed File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\WILLIAMSWEBSITE\TJWEXOTICS\urls.py", line 21, in path('', include('TJW.urls')) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\urls\conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "C:\Users\danfi\AppData\Local\Programs\Python\Python38-32\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) … -
I want to serve static files with permissions logic in my django project
So I've been working on a django project. Its a marketplace platform (two kinds of users - buyer & seller) and when a seller uploads files for a buyer, only those two users should have access to the uploaded files. I'm trying to figure how static files can be served with these permissions. I'm not sure if this is relevant but I'm using nginx to serve the static files, so is there a way to add permissions logic in django to serve these static files? -
Python(Django), PHP, Ruby frameworks: How do they handle browser side scripting?
I am quite familiar with javascript frameworks like Angular, React & Vue. Since browsers understand and knows how to run javascript, these frameworks are used for end-to-end web application development. But when we think of non-javascript frameworks like Python(Django/Flask), PHP, Ruby on Rails etc. few questions come to my mind: Do these framework supports only server side scripting in their respective languages (i.e. Python, PHP, Ruby)? When these frameworks send webpage/response to browser and lets say for example the page is having submission form which needs validations, which scripting do they use on browser side? Because browsers don't support Python, PHP, Ruby languages. OR Django/Flask, PHP, RoR programmers also need to know javascript and they got to embed it in pages/responses they send? -
Profile model Data is not saving when I try to create user and Profile simultaneously
When I try to create a new user, I also want to create their profile at the same time. But there is no data coming from the Profile form. User is created but in Profile creation form I am getting an error. Here is my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) StudentID = models.IntegerField(primary_key=True, verbose_name='SID') image = models.ImageField(default='default.jpeg', upload_to='profile_pics', blank=True) def __str__(self): return self.Branch def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() class Meta: model = User fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2'] class ProfileCreationForm(forms.ModelForm): class Meta: model = Profile fields = ['StudentID', 'Branch', 'YearOfStudy', 'ContactNumber'] views.py when I try to print StudentID, I get None value. I think there is data loss. def register(request): print("hello") if request.method == 'POST': form = UserRegisterForm(request.POST) form1 = ProfileCreationForm(request.POST) if form.is_valid() and form1.is_valid(): user = form.cleaned_data.get('username') StudentID = form.cleaned_data.get('StudentID') print(StudentID) profile = form1.save(commit=False) profile.user = user form.save() profile.save() messages.success(request, f'Your account has been created! You are now able to log in') print("reached here") return redirect('login') else: form = UserRegisterForm() form1 = ProfileCreationForm() … -
How to export data into csv file from multiple django models?
from django.db import models Models.py class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) class Album(models.Model): artist = models.ForeignKey(Musician, on_delete=models.CASCADE) name = models.CharField(max_length=100) release_date = models.DateField() num_stars = models.IntegerField() class Runner(models.Model): MedalType = models.TextChoices('MedalType', 'GOLD SILVER BRONZE') name = models.CharField(max_length=60) medal = models.CharField(blank=True, choices=MedalType.choices, max_length=10) artist1 = models.ForeignKey(Album, on_delete=models.CASCADE) I want to export the data from multiple models to single csv files.Is there any way to do that ? I'm trying to applay the export features for user not on admin side. -
How to add Auto increment Field, Which isn't a Primary Key in Django Models
I want to add a field id in my Django Model. The primary key is the email id. I want the id field to be AUTO_INCERMENT. we can use models following AutoField(primary_key=True) but this makes id the primary key to the id, which isn't the desired case. it returns the following error. django.db.utils.Error: Incorrect table definition; there can be only one auto column and it must be defined as a key [SQLCode: 1075], [SQLState: 42000] below code for model class USER(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) email = models.EmailField(primary_key=True) when I am making primary_key=False it will return same error django.db.utils.Error: Incorrect table definition; there can be only one auto column and it must be defined as a key [SQLCode: 1075], [SQLState: 42000] -
Is it possible to implement Session AND Token Authentication together in DRF?
I'm kind of new with DRF and I am building a website. I've successfully implemented a basic authentication using forms and the code below: def login_request(request): if request.method == 'POST': form = AuthenticationForm(request=request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('/user-area/') form = AuthenticationForm() return render(request = request, template_name = "myapp/login.html", context={"form":form}) After logged in, the user is redirected to a page that shows some data about him. My question is: Is it possible to show the user Authentication Token on this page (on browser, with my HTML template)? So the user would be able to just copy the Token and use it in his device to request some data (on another page), without needing of provide his login/password credentials? I'm looking for the both Authentication Method... to allow the user login providing the credentials on his browser AND use only the token on his external device. There is a similar question, but without answers here: DRF both Token and Session Authentication -
How to use Django ORM with cloud NDB?
I am trying to create an django project in which database is handled by cloud NDB. I checked out the cloud ndb documentation here and it only specifies the middleware that I need to include in my settings.py file. I want to use django ORM facility but I don't know how to do that with cloud NDB. I don't even know if I can use it so any answers are welcome. Thank you for help. -
Django REST Framework got Server Error 500
I followed the turial at django-rest-framework quickstart I have two URLs namely /users/ and /groups/ The group works perfectly: but the user url gets a error like this: server error 500 I set DEBUG to True then add some host to ALLOWED_HOST in settings.py: DEBUG = False ALLOWED_HOSTS = [ '127.0.0.1', 'localhost' ] INSTALLED_APPS = [ 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] my urls.py: from django.contrib import admin from django.urls import include, path from rest_framework import routers from django_rest.django_rest_app import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] this is my serializers.py: from django.contrib.auth.models import User, Group from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url','username','email','group'] class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ['url','name'] and this is my views.py: from django.shortcuts import render from django.contrib.auth.models import User, Group from rest_framework import viewsets from rest_framework import permissions from django_rest.django_rest_app.serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer permission_classes = …