Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to build a Python and Java language site? [closed]
I'm sorry My English is weak How to build a Python and Java language site? I need to build website look like amazon or Facebook in python Using django and java spring ? -
Pushing Data from Django API to Mixed Chart.js in an Interval
I have a problem displaying data into a mixed bar and line chart from an API designed using the Django Rest Framework. Here is the model for the readings from the pressure and flowrate sensors models.py from django.db import models # Create your models here. class ReadingQuerySet(models.QuerySet): pass class ReadingManager(models.Manager): def get_queryset(self): return ReadingQuerySet(self.model, using=self._db) class Reading(models.Model): date = models.DateField(auto_now=True) pressure =models.IntegerField(default=0) flowrate =models.IntegerField(default=0) timestamp =models.TimeField(auto_now_add=True) objects = ReadingManager() def __str__(self): return str(self.timestamp) + ' ' + 'Pressure: ' + str(self.pressure) + ' ' + 'Flowrate: ' + str(self.flowrate) The code for the serializer is here. serializers.py from rest_framework import serializers from app.models import Reading class ReadingSerializer(serializers.ModelSerializer): class Meta: model = Reading fields = ['id','date','timestamp','pressure','flowrate'] the serializer is in an api folder i placed within a django app. the code for the APIview is below. views.py from rest_framework import generics, mixins from rest_framework.response import Response from .serializers import ReadingSerializer from app.models import Reading class ReadingChartAPIView(mixins.CreateModelMixin, generics.ListAPIView): permission_classes = [] authentication_classes = [] serializer_class = ReadingSerializer def get(self, request, *args, **kwargs): qs = Reading.objects.all() data = { 'timestamp':qs.values('timestamp'), 'pressure':qs.values('pressure'), 'flowrate':qs.values('flowrate'), 'update':qs.values('pressure', 'flowrate').last() } return Response(data) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) and this is the data i receive … -
Django create object ignore constraints
The Manager, objects, is ignoring not null. I´m using Python 3.6.8 and Django 3.0.5. class Notificacao(models.Model): titulo = models.CharField('Título', max_length=255) categoria = models.CharField(max_length=20, choices=Categoria.choices) descricao = models.TextField('Descrição') endereco = models.CharField('Endereço', max_length=255, blank=True, null=True) localizacao = models.CharField('Localização', max_length=21) When I´m trying to create an empty object, it's created. But I have required fields. In [1]: from endemias.models import Notificacao In [2]: Notificacao.objects.create() Out[2]: <Notificacao: > -
How to run Daphne and Gunicorn At The Same Time?
I'm using django-channels therefore I need to use daphne but for the static files and other things I want to use gunicorn. I can start daphne alongside gunicorn but I can not start both of them at the same time. My question is should I start both of them at the same time or is there any better option? If should I how can I do that? Here is my runing server command: gunicorn app.wsgi:application --bind 0.0.0.0:8000 --reload && daphne -b 0.0.0.0 -p 8089 app.asgi:application PS: I splited location of / and /ws/ for gunicorn and daphne in nginx.conf. -
What is the recommended max. number of chars for django charfields when using postgresql?
In case model.CharFields shall be unique the recommended max. number of chars is 255 https://docs.djangoproject.com/en/dev/ref/databases/#character-fields . What's the recommended max. number of chars for models.CharField when the field is not unique and when I'm using a PostgreSQL 12.0 database? The PostgreSQL docs didn't get me further yet. -
How to call various python functions in a Django project from the front-end?
I'm working on a chatbot type of web application which I need to build using Django. I have developed a small prediction ML model and have build a small flow for the conversation to take place. The conversation flow contains a class and few functions inside it. The conversation flow module is something like this: class Arbitrary(object): def A(self): abc = input() ## perform some operation ## if this: a = Arbitrary() return a.B(abc) else: a = Arbitrary() return a.C(abc) def B(self, abc): abc = input() ## perform some operation ## return 'something' def C(self, abc): abc = input() ## perform some operation ## return 'something more' This piece of code works exactly how I want it on the terminal. The issue is now I want to create a web application in Django in such a way that there is a textbox on the webpage with a button. The user types something and with the click of the button, the text entered should be passed to the function A first and then the same function calls (flow of the conversation) must be followed like it happens in the terminal. The issue I'm facing here is the abc = input() which … -
What is the best to integrate "Direct message" functionality in django?
I just need the simple client server direct messaging in django and not getting what is the best and efficient way to do. I don't want to implement django channels as I think this is complex and provides extra functionaly which I don't need. One article that I found useful was and wanted: https://pypi.org/project/django-directmessages/ But implementing it cause different issues like : cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' I have found that this is not supporting django 3.0.2 which I have. So can anyone explain me some simple way to implement some direct message functionality? Any custom db model? -
Django user comment edit with UpdateView
I have a working review system for a 'restaurant review app' for uni. I am trying to allow users to modify their comments but I can't make the UpdateView work. Comments are displayed by restaurants with a regular view and I want to create there an edit button to allow the user to change the grade and content of it's comment. Here is the code I have for my review_edit view: class review_edit(UpdateView): model = UserReviewForm fields = ['user_review_grade', 'user_review_comment'] template_name_suffix = '_edit' # Get the initial information needed for the form to function: restaurant field def get_initial(self, *args, **kwargs): initial = super(review_edit, self).get_initial(**kwargs) initial['restaurant'] = self.kwargs['restaurant_id'] initial['userreview'] = self.kwargs['userreview_id'] return initial # Post the data into the DB def post(self, request, restaurant_id, *args, **kwargs): form = UserReviewForm(request.POST) restaurant = get_object_or_404(Restaurant, pk=restaurant_id) if form.is_valid(): review = form.save() print(review) # Print so I can see in cmd prompt that something posts as it should review.save() # this return below need reverse_lazy in order to be loaded once all the urls are loaded return HttpResponseRedirect(reverse_lazy('restaurants:details', args=[restaurant.id])) return render(request, 'restaurants/details.html', {'form': form}) Here is for urls: urlpatterns = [ ... path('<int:userreview_id>/edit', views.review_edit , name='review_edit') ] And this is my template: {% extends 'base_generic.html' … -
Django template won't re-load after changes
I'm trying to get a simple Django app working following the tutorial. I have a working view, URLconf, and template. I'm not using any packages, files, or settings not covered in the tutorial. I'm not even using a data model yet. I'm using Django 3.0.4, Python 3.6, and Ubuntu 18.04. When I make changes to the template file, they don't show up when I refresh the finished web page. I've tried clearing the browser cache and restarting the server. There's nothing I can find on the tutorial page on templates or official docs on templates to explain why this is happening or what I can do about it. All of the information I can find online and on Stack Overflow about similar problems involve "static files" from a package 'django.contrib.staticfiles', which I'm not using. I've also found this question, which I've verified is not my problem, since I've never copied template files (there's only one in the entire project and it has never moved). This is just the basic tutorial, slightly adapted. What's wrong? -
Separate fields for Users and admins in Django models.py
I have a BooleanField in my models.py file. I want it to be True for all Admins/Superusers by default, while I want it to be False for all users by default. I don't want to use if-else template tags in my html for this purpose, and I am hoping to get a more cleaner solution. Something like: field_name = models.BooleanField( if user.is_superuser: default = True else: default=False ) Any help is appreciated. -
Router in Django REST Framework with viewset queryset filter
I want to do data filtering in a api response. Ie make such addresses /api/v1//CoinCost?coin_id=coin_name&dateStart=2020-02-06T00:00:00&dateEnd=2020-02-08T00:00:00 My code now: from django_filters import rest_framework as filters class CoinCostFilterSet(filters.FilterSet) class Meta: model = CoinCost fields = { 'coin_id': ['exact'], 'timestamp': ['gt', 'lt'], } class CoinCostViewSet(viewsets.ViewSet): queryset = CoinCost.objects.all() serializer_class = CoinCostsSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = CoinCostFilterSet And my urls.py. This url no work router = DefaultRouter() router.register('CoinCost', CoinCostViewSet, basename='Coins') urlpatterns = [ path('', include(router.urls)), ] i try /api/v1//CoinCost?coin_id=bulbacoin and i see errors Using the URLconf defined in myminter.urls, Django tried these URL patterns, in this order: admin/ api/v1/ coins/ api/v1/ coins_costs/update/ api/v1/ coins_load/update/ api/v1/ ^$ [name='api-root'] api/v1/ ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] The current path, api/v1/CoinCost/, didn't match any of these. Why does my router not work and how to make a working router? Thanks! -
I want to add products based on category in my homepage in django
This is my view where I want to add products based on categories [And I have made the category choices[][2]][]2k.imgur.com/YFqPJ.jpg -
HOW TO MAKE EDIT AND DELETE FUNCTIONALITY BY USING DJANGO FORM
I have two models academic and child by which these two models have relationship to each other and also i pass a child ID into a template that display child and academic details and everything working as fine,within the template i have edit and delete functionalities for academic details but those functionalities don't work at all. Here is the academy model from child.models import Child_detail class Academic(models.Model): Student_name = models.ForeignKey(Child_detail,on_delete = models.CASCADE) Class = models.CharField(max_length = 50) def __str__(self): return str(self.Student_name) Here is the child model class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) def __str__(self): return self.Firstname Here is my form.py file class AcademicForm(forms.ModelForm): class Meta: model=Academic fields='Class' Here is my views.py file for edit and delete functionality #edit functionality def edit_academy(request,pk): child=get_object_or_404(Child_detail,pk=pk) form=AcademicForm(request.POST or None,instance=child) if form.is_valid(): form.save() return redirect('more',pk=pk) context={ 'form':form, } return render(request,'functionality/more/academy/edit.html',context) #delete functionality def delete_academy(request,pk): child=get_object_or_404(Child_detail,pk=pk) if request.method == 'POST': academy.delete() return redirect('more',pk=pk) context={ 'academy':academy, } return render(request,'functionality/more/academy/delete.html',context) -
Best way for Serializing data in Python
I want to be able to create custom serializers that can be defined from a database For example, Let's say I have an input dict {"attr1": 4, "attr2": 7, "attr3":10} and I have a table called Serializers, and has a row that has a JSON field with the following {"parent1": {"attr_rename_1": "attr1", "attr_rename_2": "attr2"}, {"attr_rename_3": "attr3"}} and if I apply that JSON field to my dictionary, I should receive the following: {"parent1": {"attr_rename_1": 4, "attr_rename_2": 7}, {"attr_rename_3": 10}} Can you please advise on what is the best way to do this? -
qr scanner update django database
I am relatively new to django and python. I want to make an app in django which records the amount of times I scan a specific QR code. I have no idea how to connect the Qr scanner on my phone to the online django database. Could anybody give me a pointer. -
Django - is it possible to filter a Queryset on a calculated field?
I have a database table which stores a users push notification time preferences, with local_push_time, and local_time_zone fields. I have an automated job that runs on our servers (in UTC time) every 10 minutes, and I’m looking to find users who are due to get a push notification in the next 10 minutes. Since we’re using Django, almost all of our data access takes places through the Django QuerySet API, which mostly does what we need. But for the use case described above, I’ve not seen a way that the QuerySet API could help here. What I’ve ended up doing is writing raw SQL, which looks something like this: SELECT * FROM user_push_preferences WHERE CAST(CAST(CAST(NOW() AS DATE) + CAST(local_push_time AS TIME) AS TIMESTAMP) AT TIME ZONE local_time_zone AS TIME) >= CAST(NOW() AS TIME) AND CAST(CAST(CAST(NOW() AS DATE) + CAST(local_push_time AS TIME) AS TIMESTAMP) AT TIME ZONE local_time_zone AS TIME) < CAST(NOW() AS TIME) + interval '10 minute’; We did consider storing a utc_push_time field on the DB table, but this was a non-starter, as it would need to update itself as the local_time_zone moves in or out of daylight savings time. So what I really want is to be able … -
Cannot import ASGI_APPLICATION module 'booktimes.routing'
I make chatting application, stuck since installed channel, I'm getting an error while ./manage.py runserver: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 08, 2020 - 11:11:30 Django version 3.0, using settings 'booktimes.settings' Starting ASGI/Channels version 2.4.0 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Exception in thread django-main-thread: Traceback (most recent call last): File "/home/kash/.local/share/virtualenvs/booktimes-7D7i9gyr/lib/python3.7/site- packages/channels/routing.py", line 29, in get_default_application module = importlib.import_module(path) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'booktimes.routing' During handling of the above exception, another exception occurred: 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 "/home/kash/.local/share/virtualenvs/booktimes-7D7i9gyr/lib/python3.7/site- packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/kash/.local/share/virtualenvs/booktimes-7D7i9gyr/lib/python3.7/site- packages/channels/management/commands/runserver.py", line 101, in inner_run application=self.get_application(options), File "/home/kash/.local/share/virtualenvs/booktimes-7D7i9gyr/lib/python3.7/site- packages/channels/management/commands/runserver.py", line 126, in get_application return StaticFilesWrapper(get_default_application()) File "/home/kash/.local/share/virtualenvs/booktimes-7D7i9gyr/lib/python3.7/site- packages/channels/routing.py", line 31, in get_default_application raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'booktimes.routing' here is setting.py ALLOWED_HOSTS = [] CHANNEL_LAYERS = { 'default': { 'BACKEND': "channels_redis.core.RedisChannelLayer", 'CONFIG': … -
Django, including one template in another results TemplateDoesNotExist at /
I'm using Django 3.0.4, Python, 3.8, VS Code and Windows 10. I want to include the post_list.html and post_new.html templates in my base.html file. I need to show them all on the main website. I just want to have one page comprising these templates. I think this would allow me to have an audio file playing consistently even when I submit a post - page would not reload I believe (but I haven't achieved this phase of project yet). I started achieving my goal by including my template post_new.html in the base.html. However, I spinned up the server, visited main site and I encountered a problem: TemplateDoesNotExist at / post_new.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.4 Exception Type: TemplateDoesNotExist Exception Value: post_new.html Exception Location: C:\Users\marecki\Desktop\mareknasz_projekt\evviva_larte\venv\lib\site-packages\django\template\backends\django.py in reraise, line 84 Python Executable: C:\Users\marecki\Desktop\mareknasz_projekt\evviva_larte\venv\Scripts\python.exe Python Version: 3.8.0 Python Path: ['C:\\Users\\marecki\\Desktop\\mareknasz_projekt\\evviva_larte\\ewiwa', 'C:\\Program Files (x86)\\Python38-32\\python38.zip', 'C:\\Program Files (x86)\\Python38-32\\DLLs', 'C:\\Program Files (x86)\\Python38-32\\lib', 'C:\\Program Files (x86)\\Python38-32', 'C:\\Users\\marecki\\Desktop\\mareknasz_projekt\\evviva_larte\\venv', 'C:\\Users\\marecki\\Desktop\\mareknasz_projekt\\evviva_larte\\venv\\lib\\site-packages'] Server time: Wed, 8 Apr 2020 12:57:51 +0200 In settings.py I have included the following: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], This is a base.html: {% load static %} {% include "post_new.html" %} <html> <head> <link rel="shortcut icon" href="{% static '/assets/favicon-32x32.png' %}" /> … -
Is there any way to get Domain name in Django DRF
I created REST API in Django DRF and it will using clients. Now, i would like to get Client's Domain name and IP address. I get the IP through request.META suggest me, is there any way to get proper Domain_name and IP_address -
How to pass parameters in dict form using drf-yasg(Swagger)
I'm trying to pass the parameters in dict format how can I do this using drf-yasg. { "a": false, "stores": { "type1": 678, "type2": 58, "type3": 58 }, "contact": { "mobile_valid": true, "mobile": "00000000" } } -
Correct way of overriding URL viewflow (Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name.)
im stuck with an error of : Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. when i tried to override the AssignTaskView View. The rationale for doing so is to allow my user to reassign Tasks to others without having to generate a seperate task to do so as well as to put in my custom forms for displaying the lsit of users to choose from. I have most of my inspirations from this particular post : Overwrite django view with custom context (Django 1.11, Viewflow) And here is my code: url.py It actually allows me to override and display my own form . path('pipeline/<process_pk>/documents/<task_pk>/assign/', OverrideTaskView.as_view(), { 'flow_class': Pipeline, 'flow_task': Pipeline.documents }), the issue lies here : views.py class OverrideTaskView(AssignTaskView,FormView): form_class=AssignForm def get_form_kwargs(self): kwargs = super(OverrideTaskView, self).get_form_kwargs() kwargs.update({'id': self.request.user}) return kwargs def get_context_data(self, **kwargs): context = super(AssignTaskView, self).get_context_data(**kwargs) context['activation'] = self.activation return context def form_valid(self, form): if '_assign' or '_continue' in request.POST: form.save(commit=False) assigned = form.cleaned_data.get('user') self.activation.assign(assigned) self.success(_('Task {task} has been assigned')) return HttpResponseRedirect(self.get_success_url()) else: return self.get(request, *args, **kwargs) I suspect it has something to do with the get_success_url ? The error only pops up after i click the confirmation button , please … -
Template Does not exsist-heroku django
I have been working on a django application by following the coreyMS tutorials.Now it is at the deployment stage.I tried to deploy the app using heroku. The app gets deployed and all the blog apps templates are fine.But the users app templates are not getting rendered.Any help will be appreciated.Thanks in advance! My settings.py file: { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]``` Only the templates of blog are getting rendered.I am having two apps-blog and users. in both the apps i have the templates in the following way: app->templates->appname->.htmlfiles One is getting rendered while the other is not.. -
NoReverseMatch at / Reverse for 'delete_order' with arguments '('',)' not found. 1 pattern(s) tried: ['delete_order/(?P<pk>[^/]+)/$']
i am using to delete a specific data in table. But this is not working ! i Can't seem to find any wrong with my code ! please help me this is making me crazy ! i did exactly what youtube did but their's code is working while mine is showing error like this: NoReverseMatch at / Reverse for 'delete_order' with arguments '('',)' not found. 1 pattern(s) tried: ['delete_order/(?P[^/]+)/$'] here the views.py def deleteOrder(request, pk): order = anime.objects.get(id=pk) if request.method == "POST": order.delete() return redirect('/') context={'list':order} return render(request, 'main/delete.html',context) here's table.html <td><a href="" class="btn btn-success">Update</a></td> <td><a href="{% url 'delete_order' order.id %}" class="btn btn-danger">Delete</a></td> </tr> {% endfor %} here's urls.py urlpatterns = [ path('',views.homepage,name ="homepage"), path('anime/',views.addAnime,name="anime"), path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"), ] -
django-inlinecss returns error You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path
I am trying to load a page as PDF. actually it loaded successfully - without any style or even the images. So I installed django-inlinecss and added it in installed_apps in settings.py and loaded it in template and called it as I was told. but it returns an error You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. and points at: 1 {% load inlinecss %} 2 {% load static %} 3 {% inlinecss "css/style.css" %} <--- I don't have any idea how to fix it. Hope someone could help me in this -
Reverse for 'user_login' not found. 'user_login' is not a valid view function or pattern name
These are my files while making a signup and login page please tell me where it went wrong. url.py/home ''' from django.contrib import admin from django.urls import path,include from . import views app_name='home' urlpatterns = [ path('',views.index, name='index'), path('register/',views.register, name='register'), path('login/',views.user_login, name='login'), ] ''' views.py ''' def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Your account was inactive.") else: print("Someone tried to login and failed.") print("They used username: {} and password: {}".format(username,password)) return HttpResponse("Invalid login details given") else: return render(request, 'home/login.html', {}) ''' settings.py ''' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') MEDIA_DIR = os.path.join(BASE_DIR,'media') STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR,] MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' LOGIN_URL = '/home/user_login/' '''