Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get the form processing data immediately after form submitting in Javascript, before page refresh
I have used Django to develop a web app. After form submit, I want to get the form processing result( msg here in my case) immediately in view function, before page refresh. url.py: path('index/', views.form_process, name='index'), view.py def form_process(request): if request.method == 'POST': Form_instance = Form(data=request.POST) if Form_instance.is_valid(): msg="success" else: msg="fail" return render(request, 'index.html', context={'msg': msg}) index.html <form id="myform"> ... </form> <button class="button" onclick="myFunction()" id="submit">submit</button> <script> function myFunction() { ... $("#myform").submit(); if ('{{msg}}'.includes('success')) {alert("success"); } } </script> Now the msg always send to the js after page refresh. My boss want to make it pop up immediately after form submitting, before page refresh. How could get the msg generated in view function immediately after form submitting in Javascript, before page refresh. I have tried ajax but failed to capture the msg, no alert form ajax popped up: $('#myForm').ajaxForm({ url : '/index/', //I also tried 127.0.0.1:8000/index, also no pop up type: 'get', success : function (response) { alert("The server says: " + response); } }) ; How could I get the form processing data immediately after form submitting in Javascript, before page refresh? -
Django Cookiecutter template doesn't return post listing
I'm using the cookiecutter boilerplate from PyDanny and created a second app called Content on top of the default Users app. I have a view to list all posts and created some test posts in the database. Now I want to loop to display my posts but nothing appears. I started with the code below but that didn't return anything: ... {% for post in posts %} <h1> {{ post.title }} {% endfor %} ... I figured this was because the Post model in a separate app so I tried: ... {% for post in content.posts %} <h1> {{ post.title }} {% endfor %} ... No luck with this either. Here's my view: class PostFeed(ListView): model = Post context_object_name = "posts" template_name = "home.html" paginate_by = 10 title = "Manutd" feed_type = "all" def get_context_data(self, **kwargs): context = super(PostFeed, self).get_context_data(**kwargs) context["title"] = self.title context["feed_type"] = self.feed_type context["feed_name"] = self.feed_name return context def get_queryset(self): queryset = self.get_post_list() queryset = queryset.order_by(*self.get_ordering()) queryset = queryset.select_related("user").prefetch_related("likes") return queryset def get_ordering(self): return self.sort["ordering"] def get_post_list(self): raise I get the post list with this: class AllPostFeed(PostFeed): def get_post_list(self): post_list = Post.objects return post_list I've tried adding this to the code above but that didn't work post_list … -
Permission does not show in admin page
I have added an app to my existing django site and to view it, I created an extra permission overview.view. But, I do not see it in my admin page, so I can also not assign this permission to any user. I think I have all files setup correctly, but I guess I am missing something. I have all the same files in the overview folder as I have in other working folders. I do see the page, but somehow I am not logged in either. This is my urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ] models.py: from django.db import models class Overview(models.Model): class Meta: permissions = ( ('view', "May view the overview"), ) and (part of) settings.py INSTALLED_APPS = [ 'overview.apps.OverviewConfig' ] -
How to edit "view on site" url on django admin?
How in the modern version of Django edit the "view on site" url on django admin? -
How to represent facts in Django ORM
Having a problem of representing facts in the Django model. Will try to make a general example: I have a "Material" model with a Foreign key to a "Price". During the year 2020, a "Material" has one price, but in the year 2021 I want to change the "Price" but still keep track of the history of price changes. The summed cost of a "Material" consumption during 2020 should not change because of a "Price" change during 2021. Is there a common strategy to handle this in Python/Django? In Clojure & Java, there is a solution solving this problem - Datomic. -
Stripe Fetch Subscription Data (ERROR: relation "subscriptions_stripecustomer" does not exist)
I'm getting this error. relation "subscriptions_stripecustomer" does not exist I'm trying to configure Django Stripe Subscriptions following this manual https://testdriven.io/blog/django-stripe-subscriptions/ The code below is views.py which fetches subscription data. It's following the above manual. import stripe from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.http.response import JsonResponse, HttpResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from subscriptions.models import StripeCustomer @login_required def home(request): try: # Retrieve the subscription & product stripe_customer = StripeCustomer.objects.get(user=request.user) stripe.api_key = settings.STRIPE_SECRET_KEY subscription = stripe.Subscription.retrieve(stripe_customer.stripeSubscriptionId) product = stripe.Product.retrieve(subscription.plan.product) # Feel free to fetch any additional data from 'subscription' or 'product' # https://stripe.com/docs/api/subscriptions/object # https://stripe.com/docs/api/products/object return render(request, 'home.html', { 'subscription': subscription, 'product': product, }) except StripeCustomer.DoesNotExist: return render(request, 'home.html') The error occurs at stripe_customer = StripeCustomer.objects.get(user=request.user) because I use custom user model "CustomUser" My models.py from django.conf import settings from django.db import models class StripeCustomer(models.Model): user = models.OneToOneField(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripeCustomerId = models.CharField(max_length=255) stripeSubscriptionId = models.CharField(max_length=255) def __str__(self): return self.user.username accounts/models.py from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): class Meta: verbose_name_plural = 'CustomUser' My settings.py #used for django-allauth AUTH_USER_MODEL = 'accounts.CustomUser' In this situation, how should I change the below code proper way along with custom user model "CustomUser"? stripe_customer = StripeCustomer.objects.get(user=request.user) or add … -
Clicking over a menu item adds directory to current URL in Django
I have an issue with my navigation menu items. When the user is in the page of Item X and they click over to the Item Y of the navigation menu, they should be taken to example.com/ItemY. Instead, they are taken to example.com/ItemX/ItemY which results in a page-not-found error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/biology/ItemX/ItemY Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ [name='home'] chemistry/<slug:slug>/ [name='chemi'] summernote/ blog/ <str:parent>/<slug:slug>/ [name='blog_list'] ^media/(?P<path>.*)$ The current path, blog/biology/ItemX/ItemY, didn’t match any of these. These are my project url patterns: #urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('chemistry.urls')), path('summernote/', include('django_summernote.urls')), path('blog/', include('blog.urls')), ] And these are my app urls: #blog/urls.py urlpatterns = [ path('<str:parent>/<slug:slug>/', views.BlogDetail.as_view(), name='blog_list'), ] And here is the HTML template that contains the navbar: <div class="card-body"> <nav><ul> {% for blog in blog_list %} <li><a href="{{blog.slug}}">{{blog.title}}</a></li> {% endfor %} </ul></nav> </div> How can I fix this? -
pip install erro
any time I use the "pip install" command on my terminal i get error, most times "ERROR:exception"enter image description here -
What is the best option to deploy Django with React on 2021? [closed]
I am developing an aplication with Django and Django Rest Framework for backend and React for frontend. In my previous project, that I started 2 years ago, I use Webpack to deploy DRF with React. I followed a tutorial (https://www.valentinog.com/blog/drf/#django-and-react-together) so I didn't think much about the different options I had. Noweadays, two years later, I'm not sure that is the best option. So, now, on 2021, I'd like to ask about the best way to deploy my app, basically: Option 1: DRF for API + React for frontend separety → You must manage two ports and the authentication might be harder. Option 2: DRF + webpack + React → React is included in Django and you only use one port. The configuration is hard, I can't find much documentation, only blogs, and can be difficult to keep the app up to date. Any other option? I will need to deploy the app for production one day, using nginx and uwsgi for example. -
Pyhon and Django and three js
I want to insert a 3d model into my site using the Three.js, but I can not do it, except for this code did not do anything, did not install anything, maybe I missed something or incorrectly prescribed or did not install something, <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> <title>{{ title }}</title> </head> <body> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r123/three.min.js"></script> <script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/loaders/GLTFLoader.js"></script> <script> scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 10; render = new THREE.WebGLRenderer({alpha: true, antialias: true}); renderer.setClearColor(0x000000, 0); renderer.setSize(1280, 720); renderer.domElement.setAttribute("id", "scene3DObj"); document.body.insertBefore(renderer.domElement, document.body.firstChild); const aLight = new THREE.AmbientLight(0x404040, 1.2); scene.add(aLight); const pLight = new THREE.PointLight(0xFFFFFF, 1.2); pLight.position.set(0, -3, 7); scene.add(pLight); const helper = new THREE.PointLightHelper(pLight); scene.add(helper); let loader = new THREE.GLTFLoader(); let obj = null; loader.load('../news/scene.gltf', function(gltf) { obj = gltf; obj.scene.scale.set(1.3, 1.3, 1.3); scene.add(obj.scene); }); function animate() { requestAnimationFrame(animate); if(obj) obj.scene.rotation.y += 0.03; renderer.render(scene, camera); } animate(); </script> <style> #scene3DObj { position: absolute; right: 0; top: 0; z-index: 999; } </style> </body> </html> enter image description here enter image description here enter image description here -
error while deploying my django to the digital ocean server with postgres
i cloned my github repository to the remote machine and i done the following changes to the files changed allowed host to server's ip cleared migration files which was created in my local machine because that caused me many error collected static files sucessfully migrated but when i run server i throws the following error Exception Type: ProgrammingError Exception Value: relation "blog_short_intro" does not exist LINE 1: ...."profile_pic", "blog_short_intro"."content" FROM "blog_shor... when i open the admin panel i can able to view the database tables but when i try to enter any of the tables that gives me error pictures error in homepage admin panel admin panel error when entered into any table -
_MultiThreadedRendezvous object time delay while using for loop
I am using GRPC server to return data to Django server which in turn formats it to json and send it to Angular UI. The issue is it takes a lot of time to process the data. Rough algorithm of my code is : data = service.getData() // data from GRPC server // takes less than a 1 sec. response = [] for d in data: // it takes more then 9 sec just to start the loop dict = google.protobuf.json_format.MessageToDict(run, preserving_proto_field_name=True) // code to format data into desired json format // it takes less then a 1 sec per element in data response.append(formated_d) return response The code works fine and return desired response but this api call takes 10 - 11 sec to return 25 elements of data. The time increases as number of element increases. API: UI<->django<->grpc server Any solution to reduce this time or alternate implementation to achieve the same in less time? Thank you in advance. -
How to update existing data without duplication?
I must be able to update the attributes of my drink. The drink name could be retained or it could also be updated but the name should not be existing in the database. I have this but it allows me to update the name into an existing one, resulting in multiple drinks with the same name. There are no problems with the updating of price and description since both could be retained or duplicated. What should I do? views.py def update_drink(request, pk): f = get_object_or_404(Drink, pk=pk) if(request.method=="POST"): update_name = request.POST.get('update_name') update_description = request.POST.get('update_description') update_price = request.POST.get('update_price') drink = Drink.objects.filter(name=request.POST.get(‘name')).exclude(name='update_name') if drink: return render(request, ‘MyApp/update_drink.html', {’d’:d, "warning": “Drink is already existing”}) else: Drink.objects.filter(pk=pk).update(name=update_name, description=update_description, price=update_price) return redirect("view_drinks") else: f = get_object_or_404(Drink, pk=pk) return render(request, ‘MyApp/update_drink.html', {‘d’:d}) models.py class Drink(models.Model): name = models.CharField(max_length=300) description = models.CharField(max_length=500) price = models.FloatField(default=0) objects = models.Manager def getName(self): return self.name def getDesc(self): return self.description def getPrice(self): return self.price update_drink.html {% extends ‘MyApp/base.html' %} {% load static %} {% block content %} <div class="card" style="justify-items: center; width: 500px; margin-left: 500px;"> <div class="card-body"> <form method="POST" class="card-text"> <h3>Update Drink</h4> {% csrf_token %} {% if warning %} <h5 class=card style="align-content: center;"><span class="badge badge-danger">{{warning}}</span></h5> {% endif %} <div class="form-group"> <label for="update_name"> … -
Django-location-field - Map doesn't display
I'm implementing a django modal form in which I have a PlainLocationField (I followed this tuto : Tutorial - django-location-field). My problem is that the map doesn't display in my modal. I have this : Here is my code : models.py class Soiree(models.Model): ... city = models.CharField(max_length=255,default="") location = PlainLocationField(based_fields=['city'], zoom=7, default="") settings.py LOCATION_FIELD = { 'map.provider': 'google', 'map.zoom': 13, 'search.provider': 'google', 'search.suffix': '', 'provider.google.api': '//maps.google.com/maps/api/js?sensor=false', 'provider.google.api_key': '<my_api_key>', 'provider.google.api_libraries': '', 'provider.google.map.type': 'ROADMAP', } forms.py class CreationSoireeForm(BSModalModelForm): class Meta: model = Soiree fields = ['Intitule','Type_Soiree','city','location', 'confidentialite','soiree_date'] ... Thanks ! -
How to save file or remove older files when going back to the previous step in formwizard
Could you please share idea that how we can delete the older files in fileinput field created by the same session during form wizard. Because each time when we came back to the previous step, the uploaded file seems to disappear, and I need to upload again. Thanks. -
What is the difference between django and tkinter?
I have just starting learning to code in tkinter. However, I was also exposed to django. Both uses pythn programming language. Why do they have different style or documentation in terms of coding? Can someone explain in detailed on the whole process flow? -
How to interrupt a running websocket function with a button
Hello everyone, I am using Channels to implement websocket in my Django app. My goal for the app is to log datas comming from a RS323 link, print them so the user can see them and save them in a file. The program logging the datas works fine. Saving the datas in a file is also working. But i have a problem with the printing part. I use Channels to print the data in "real time" using websockets and I want the user to just : press the 'start log' button It starts logging the datas press the 'stop log' button It stops logging This is my consumer.py file : import json from channels.generic.websocket import WebsocketConsumer class CrioConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): print('disconnected') pass def receive(self, text_data): text_data_json = json.loads(text_data) fifo = text_data_json['message'] # this is the part where i log the datas but i cannot post it here because it is 600 lines long And this is my log.html file : {% extends "appliCrio/base.html" %} {% block content %} <hr> <form action="/appliCrio/log/" method="post"> {% csrf_token %} <p> {{ form }} </p> <input id="id_Start" type="submit" value="Démarrer enregistrement"> </form> <input id="start_log" type="button" value="Log"> <input id="stop_log" type="button" value="Stop Log"> <script> … -
Django how to save objects in a for loop
I want to save x MediaStreams for one Media Object. So I have a One-to-Many relation here (ForeignKey) but I'm not sure how I can this working as currently always the same stream gets saved and not 5 different ones as expected. Where do I need to place "i" to make this working for object creation within the for-loop? for i in clean_result['streams']: new_stream = MediaStreams.objects.create(index=index_value, stream_bitrate=streambitrate_value, codec_name=codec_name_value, codec_type=codec_type_value, width=width_value, height=height_value, channel_layout=channel_layout_value, language=language_value, media=new_object) new_stream.save() current error: TypeError: 'dict' object is not callable Thanks in advance -
How can I solve Recursion Error in django rest framework when using render_fields?
here are my codes. views.py class Contents(models.Model): name = models.CharField(max_length=100) formula = models.CharField(max_length=20) description = models.TextField(null=True, max_length=100) wiki = models.CharField(null=True, max_length=100) youtube = models.CharField(null=True, max_length=100) file = models.FileField() def __str__(self): return self.name models.py from django.db import models # Create your models here. class Contents(models.Model): name = models.CharField(max_length=100) formula = models.CharField(max_length=20) description = models.TextField(null=True, max_length=100) wiki = models.CharField(null=True, max_length=100) youtube = models.CharField(null=True, max_length=100) file = models.FileField() def __str__(self): return self.name serializers.py from rest_framework import serializers from .models import Contents class ContentsSerializer(serializers.ModelSerializer): class Meta: model = Contents fields = '__all__' admin.html <h4>Add Name <i>*</i></h4> <span> <div class="input_box"> {% render_field serializer.name template_pack='rest_framework/inline' %} </div> </span> following is the error message Traceback (most recent call last): File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\rest_framework\response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\rest_framework\renderers.py", line 167, in render return template.render(context, request=request) File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\gyuman\PycharmProjects\CharChokka_DB\venv\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) … -
Dropdown box foreign key in django to change into text box
i m making a submit form in that form there are 2 foreign keys which appears in select option (dropdown-box ) foreign keys contains 1000 of keys value which make my severs load high when there are many request from client side so I want something like text box where user can type there foreign keys yeah have used select2 but it is not efficient way because it preloads all the foreign keys Django community please suggest we some efficient ways of doing it -
How to get field name and value in django-reversion?
I am using Django-reversion to track the version. I want to get previous value as well as updated value in all models with a field name that has been updated. Here is the code I have tried so far: class ModelHistoryView(generic.ListView): """Creates the version history for a given model here. """ # model = None queryset = reversion.models.Version.objects.all() template_name = "backend/single_card.html" single_card.html {% extends current_module.base_template %} {% load i18n material_form material_frontend %} {% load static %} {% load my_tags %} {% block breadcrumbs_items %} <a href="{% url "backend:index" %}">{{ title|default:"Backend" }}</a> {# {% if object_list %}#} {# {% for object in object_list %}#} <a class="active">History</a> {# {% endfor %}#} {# {% endif %}#} {% endblock %} {% block content %} {% block left-panel %} <div class="left-panel"> {% block cards %} <div class="row"> <div class="col m12 s12"> {% for object in object_list %} <div class="card"> <div class="card-content"> <div class="card-title"> {% block card-title %}{% if object %}{{ object }}{% else %}{{ title }} {% endif %}{% endblock %}</div> <div>Revision: {{ object.revision.id }}</div> <div>Model: {{ object.content_type }}</div> <div>Instance Id: {{ object.object_id }}</div> <div>Changed by <strong style="text-transform: capitalize">{{ object.revision.user }}</strong> on <strong>{{ object.revision.date_created }}</strong></div> <div> <table> <tr> <th>Field</th> <th>Value Before</th> <th>Value After</th> </tr> <tr> … -
Custom icons for Django Oscar Dashboard
I have created set of icons that I would like to replace the font-awesome fonts currently used by Django Oscar. It is possible to add custom icons to the Django Oscar dashboard including the primary and children links in the header? How can I do it? Any suggestion to how can this can be done? -
Log out a user when the user log in's from another device django
How can i logout a user from a device if the user log in's from another device in django -
How to let the user add as many forms as they want to a ModelForm that saves to the same model in django
I have a form to let users make a new poll, it consists of 2 ModelForms one for the Question model and another for the Choice model Make new poll form i want there to be something like a (+) or (add another choice) button where users can add as many choices as they want and then submit it all. here's the models.py file models.py from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=False) questionText = models.CharField(max_length=150) datePublished = models.DateTimeField(auto_now_add=True) def str(self): return self.questionText class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choiceText = models.CharField(max_length=200) choiceVotes = models.IntegerField(default=0) def str(self): return self.choiceText forms.py from django import forms from .models import Question from .models import Choice class NewPollForm(forms.ModelForm): class Meta: model = Question labels = { "questionText":"Poll question" } fields = ("questionText",) class NewChoicesForm(forms.ModelForm): class Meta: model = Choice labels = { "choiceText":"Choice" } fields = ("choiceText",) the view for this form's page you can see it is set for only one choice field right now from .forms import NewPollForm from .forms import NewChoicesForm def newpoll(request): if request.user.is_authenticated == True : pass else: return redirect("users:signup") if request.method == "POST": qform = NewPollForm(request.POST) cform = … -
How to query items and orders them if one of params is in the list
I've got the list with users: following = [x.user for x in UserFollow.objects.filter(user=request.user)] Also the tweets: tweets = Tweet.objects.all() How can i sort the tweets to have tweets that are created by users in following at first places?