Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django send http response without changing page
In django, if i wanted to send back a return httpresponse but not make a new page eg: when i send a http response it becomes https://localhost:8000/appname/submit/, i want to send an http response to https://localhost:8000/appname/ and not change it? I just want a general answer nothing specialised, if any code is needed please tell me. From my research i found a question with a very similar title unfortunately it is for flask or ajax and not django focused [yes i might be able to work it out but i recently just started django so it's a bit confusing :) ] -
Header refuses to show up on mobile view
I've spent a week trying to figure this out. I'm building a django website, and I have a navigation menu that always remains hidden behind some element when I look at the website on my mobile view. On Chrome Dev Tools, it looks perfectly fine, but on my phone, it's completely gone. Example of Chrome Dev Tools vs Phone: My first step in solving this was looking at the z-index. None of the indexes I tried worked, and I made sure to search for solutions to z-indexes not working on the Internet as well, such as having necessary prerequisites. Since my navigation menu is in my base.html template file, I even moved the header down to the very bottom of the body element (it has a fixed position), so that {%block content%} was always above the header. That didn't work either. So I tried moving all elements to the left whenever the navbar was open. This is what happened. If I try inspecting this on chrome dev tools by right clicking the empty space where there should be empty space, I get the following: ...meaning the only thing that's there is the HTML file itself. I'm completely baffled. I have … -
List and Put method
I'm new to django-framework. I'm trying to list and create two models at the same time. But I'm unable to bring the data of the two models in a single json models.py class User(models.Model): id=models.CharField(max_length=9,primary_key=True) name=models.CharField(max_length=30) def __str__(self): return self.name class ActivityPeriod(models.Model): tz=models.CharField(max_length=30) start_time=models.DateTimeField(auto_now=False, auto_now_add=False) end_time=models.DateTimeField(auto_now=False, auto_now_add=False) activityperiod2user=models.ForeignKey(User,related_name='activityperiods', on_delete=models.CASCADE) def __str__(self): return str(self.activityperiod2user) views.py class CustomApiView(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = serializers.CustomSerializer serializers.py class CustomUserSerializer(serializers.ModelSerializer): class Meta: model=models.User fields=("__all__") class CustomSerializer(serializers.ModelSerializer): activitydata=CustomUserSerializer() class Meta: model=models.User fields=('name','activitydata') -
Django FileField wont update path and url after save()
I have this model: class Galeria(models.Model): galeriaid = models.AutoField(db_column='GaleriaID', primary_key=True) nombre = models.CharField(db_column='Nombre', max_length=128, blank=True, null=True) ruta = models.FileField(db_column='Ruta', max_length=512, blank=True, null=True) And I overrided the save() to make my file look like {pk}.jpg or {pk}.mp4. The code works but it doesnt update the file.path and file.url. I get "media/{file}" instead of "media/imagenes/%Y%m/{file}". What am I doing wrong, the save() code below: def save( self, force_insert=False, force_update=False, *args, **kwargs): # Call save for post id super( Galeria, self ).save( *args, **kwargs ) ruta = self.ruta if ruta: # Create new file using pk and ext file oldfile = self.ruta.name dot = oldfile.rfind( '.' ) newfile = str( self.pk ) + oldfile[dot:] # Create new file and remove the old one if newfile != oldfile: self.ruta.storage.delete( newfile ) if newfile.endswith(".jpg"): self.ruta.storage.save( "imagenes/" + str(timezone.now().strftime("%Y/%m/")) + str(newfile), ruta ) elif newfile.endswith(".mp4"): self.ruta.storage.save( "videos/" + str(timezone.now().strftime("%Y/%m/")) + str(newfile), ruta ) else: self.ruta.storage.save( newfile, ruta ) self.ruta.name = newfile self.ruta.close() self.ruta.storage.delete( oldfile ) # keep the changes super( Galeria, self ).save( *args, **kwargs ) I tried adding a function to upload to, but still doesnt work. -
django channels project deploy on heroku
I cant deploy a Django channels app to Heroku. Django rest is deployed successfully but I can't connect to sockets from Heroku host when I try, I get error "ws/... not found" I think that problem is on settings of ASGI hosts, maybe I type incorrect host? REDISTOGO_URL: redis://redistogo:<key>@hammerjaw.redistogo.com:10388/ on my setting.py I write this: ASGI_APPLICATION = 'hahachat.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'asgi_redis.RedisChannelLayer', 'CONFIG': { "hosts": [ ('hammerjaw.redistogo.com', 10388) ], }, }, } routing application application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( url_pat ), ), }) On localhost all works correctly. -
Override django serializer or models create method
I'm trying to add data to my database. To this purpuse, I have a vue function : @api_view(['POST']) def update_add_bges(request): serializer = BGESSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) this one call a serializer to add new data in the database : class BGESSerializer(serializers.ModelSerializer): laboratoire = LaboratoiresSerializer() class Meta: model = BGES fields = '__all__' def create(self, validated_data): laboratoire_data = validated_data.pop('laboratoire') laboratoire_oj = Laboratoire.objects.create(**laboratoire_data) validated_data["laboratoire"] = laboratoire_obj["pk"] bges = BGES.objects.create(**validated_data) return bges The problem is that my Laboratoire classe is nested as well, and should add instances from an other class : class LaboratoiresSerializer(serializers.ModelSerializer): tutelles = TutellesSerializer(many=True) class Meta: model = Laboratoire fields = '__all__' def create(self, validated_data): tutelles_data = validated_data.pop('tutelles') laboratoire = Laboratoire.objects.create(**validated_data) for tutelle_data in tutelles_data: t = Tutelle.objects.get(nom=tutelle_data["nom"]) laboratoire.tutelles.add(t) return laboratoire This is not working, because not called as it's the create of the serializer and not the create of the Models. How should I do ? When I add a Laboratoire, I have Tutelle to create ... Should I implement the create in the Models ? As I am new to django, I have hard time to understand the subtility of functions calls. -
wagtailtrans with prefix_default_language=False: root (/) not found when changing language
I am using Wagtailtrans and have set prefix_default_language=False in my urls.py. Default language is 'en'. Root page 127.0.0.1:8000/ loads as expected. When I change to another language (in my case load 127.0.0.1:8000/nl/) the translated page loads as expected. But when I then change back to root 127.0.0.1:8000/, I get Page not found. When I then load 127.0.0.1:8000/en/ I get Page not found as expected, but subsequently loading 127.0.0.1:8000/ gives me the correct English home page. So then apparently some language setting has changed. My guess is this is caused by Wagtailtrans's TranslationMiddleware, because when I use LocaleMiddleware instead, this behavior does not occur. My question: is this 'normal' or perhaps 'intended' behavior, or am I doing something wrong? It seems to me that when prefix_default_language=False, the home page should always be found. And what am I missing if I just keep using LocaleMiddleware (not recommended in docs)? settings/base.py: MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'wagtail.core.middleware.SiteMiddleware', 'wagtailtrans.middleware.TranslationMiddleware', # depends on the previous line and replaces the next line # 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... project urls.py: ... urlpatterns += i18n_patterns( ... url(r"", include(wagtail_urls)), prefix_default_language=False ) Any help appreciated! -
Why background color of navigation bar in Bootstrap does not change?
I am working on a Django project. My problem is that the background color of the navigation bar is not changing despite me making changes in the bootstrap file. I made changes in both .nav and also the .navbar (though I am sure that for it to work, change needs to be made in only one of them). Please help..thanks. .nav { display: flex; flex-wrap: wrap; padding-left: 0; margin-bottom: 0; list-style: none; color: green; background-color: green; } .navbar { position: relative; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; padding: 0.5rem 1rem; color: green; background-color: green;} -
Could not find the variable, namely could not find the key "VariableDoesNotExist at /genres/"
I can not get the objects on the template that are associated with the mptt django model. Failed lookup for key [genres]. I have a model that is linked to another model. I use mptt django so that the object is connected through the relationship of many to many. Everything is fine on the administrative panel, but this problem occurs when displaying an object on a template. What should I do best? Maybe I am setting the cycle for the object incorrectly ? models.py: from django.db import models from django.urls import reverse from django.utils import timezone from mptt.models import MPTTModel, TreeForeignKey, TreeManyToManyField class Genre(MPTTModel): name = models.CharField(max_length=50, unique=True, verbose_name='Подкатегория') slug = models.SlugField(max_length=200, null=True, blank=True, unique=True, verbose_name='Nazvanie_kategorii') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', verbose_name='Категория') is_active = models.BooleanField(default=False, verbose_name='Активность категории') created = models.DateField(blank=True, null=True, default=timezone.now, verbose_name='Дата создания записи') updated = models.DateField(blank=True, null=True, default=timezone.now, verbose_name='Дата ред-ия записи') class MPTTMeta: order_insertion_by = ['name'] verbose_name = 'Тест мптт' verbose_name_plural = 'Тест мптт' class Meta: verbose_name = 'Дерево категорий' verbose_name_plural = 'Дерево категорий' def __str__(self): return '%s' % self.name def get_absolute_url(self): return reverse('test_mptt:promotion_list_by_category', args=[self.slug]) views.py: from django.shortcuts import render, get_object_or_404 from .models import Genre, Promotion, PromotionDetails from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def show_genres(request, category_slug=None): … -
Django url pathing, home url always overwriting path('', views.home, name='home')
from django.urls import path from . import views urlpatterns = [ path('signup/', views.signup, name='signup'), path('', views.home, name='home'), ] this is my code for the URLs under my something I call timetable from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('signup/' , include('timetable.urls')), path('', include('timetable.urls')), ] this is the code for the main urls.py so I know that the call to the other url.py works as if I take the '' (home) URL out it redirects to the right URL (the view that I have in place) but if I have the home URL in it just always goes straight to that URL, is there any way like in react where I can do Exact or do you guys know of any solution for this that is simple -
Correct way of overriding URLs by installed apps
Im facing with an issue attempting to override the URL of a 3rd party app (View flow) that i installed to my system. As mentioned in this thread : enter link description here it should work as long as it is above the app- supplied url. I will demonstrate some of my code . url.py urlpatterns = [ url( r'^pipeline/(?P<process_pk>\d+)/documents/(?P<task_pk>\d+)/assign/$', OverrideTaskView.as_view(), {'flow_class': Pipeline , 'flow_task': Pipeline.documents}, name="documents__assign"), path('pipeline/', include((pipeline_urls, 'pipeline'))), #<--- this is the pre-supplied URLs views.py class OverrideTaskView(AssignTaskView,FormView): #<-- inherited the view from the third party app to overwrite it form_class=AssignForm action_name = 'assign' def get_context_data(self, **kwargs): context = super(OverrideTaskView, self).get_context_data(**kwargs) context['activation'] = self.activation return context The redirection to the view is correct and works perfectly. However the issue is that by overriding the view in this method, it seems that the system is unable to find other URLs that was supplied by the third party app. error Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. debug page URLs admin/ ^pipeline/(?P<process_pk>\d+)/documents/(?P<task_pk>\d+)/assign/$ [name='documents__assign'] pipeline/ ^archive/$ [name='archive'] pipeline/ ^action/cancel/(?P<process_pk>\d+)/$ [name='action_cancel'] pipeline/ ^(?P<process_pk>\d+)/$ [name='detail'] #<--- here! Is there a reason for this? Please help! Im super lost! -
how to migrate django models to new database
i develope a django project on my local system, and now i deployed that to a server. i used MySql as database. whenever i try to migrate my models (using python manage.py migrate or python manage.py makemigrations) to server's new database, it shows me following error: django.db.utils.ProgrammingError: (1146, "Table '<DB_NAME>.mainapp_service' doesn't exist") and doesn't create tables into the database. i didn't move any of my local migration files to server, just moved mainapp/migrations/__init__.py file. how can i create all tables and run my app? -
Should I add multiple migration files into git repository with Django?
With Django whenever I make a change in the models, another migration file is generated automatically after I run following : python manage.py makemigrations python manage.py migrate What is the best way to keep these migration files for development, should they be committed to the source control ? -
Django debug mode hags even if DEBUG= False
I'm having problems with disabling DEBUG mode from Django. The main website still shows up as well as the /api debug calls. Before I wrote, I double checked all the solutions from: django DEBUG=False still runs in debug mode and the others posts, as well as the official documentation. The app is running on App Engine. This is my main configuration: main.py from apps.wsgi import application as app manage.py #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.dev") DEBUG = False try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) settings.dev logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.debug("loading settings dev.py") BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DOCS_ROOT = os.path.join(BASE_DIR, "docs", "html") DEBUG = False ALLOWED_HOSTS = ["*"] -
How to read Django settings file from Airflow instance?
Having seen the response to this question I'd like to do the same for a demo project. Full code for the demo project available here. However, I am unable to read in the Django settings file from the pizza module in the example Dag file. I get the following error: ModuleNotFoundError: No module named 'pizza'. Full stack trace as follows, -
'Cart' object has no attribute 'add' in django
I tried make a cart for shopping web site , cart has been working until this error raised, 'Cart' object has no attribute 'add' import datetime from django.db.models import Sum from django.db.models import F from . import models CART_ID = 'CART-ID' class ItemAlreadyExists(Exception): pass class ItemDoesNotExist(Exception): pass class Cart: def init(self, request): cart_id = request.session.get(CART_ID) if cart_id: cart = models.Cart.objects.filter(id=cart_id, checked_out=False).first() if cart is None: cart = self.new(request) else: cart = self.new(request) self.cart = cart def __iter__(self): for item in self.cart.item_set.all(): yield item def new(self, request): cart = models.Cart.objects.create(creation_date=datetime.datetime.now()) request.session[CART_ID] = cart.id return cart def add(self, product, unit_price, quantity=1): item = models.Item.objects.filter(cart=self.cart, product=product).first() if item: item.unit_price = unit_price item.quantity += int(quantity) item.save() else: models.Item.objects.create(cart=self.cart, product=product, unit_price=unit_price, quantity=quantity) def remove(self, product): item = models.Item.objects.filter(cart=self.cart, product=product).first() if item: item.delete() else: raise ItemDoesNotExist def update(self, product, quantity, unit_price=None): item = models.Item.objects.filter(cart=self.cart, product=product).first() if item: if quantity == 0: item.delete() else: item.unit_price = unit_price item.quantity = int(quantity) item.save() else: raise ItemDoesNotExist def count(self): return self.cart.item_set.all().aggregate(Sum('quantity')).get('quantity__sum', 0) def summary(self): return self.cart.item_set.all().aggregate(total=Sum(F('quantity')*F('unit_price'))).get('total', 0) def clear(self): self.cart.item_set.all().delete() def is_empty(self): return self.count() == 0 def cart_serializable(self): representation = {} for item in self.cart.item_set.all(): item_id = str(item.object_id) item_dict = { 'total_price': item.total_price, 'quantity': item.quantity } representation[item_id] = item_dict return … -
use of url in django
I have a doubt in use of urls and path in urls.py. I have tried a url in django as: url('budget-info/<str:username>',views.app_view, name='app') along with: return HttpResponseRedirect(reverse('app', kwargs={'username':user.username})) and return HttpResponseRedirect(reverse('app', args=(user.username,))) in my views.py. I am getting error of this type: Reverse for 'app' with keyword arguments '{'username': 'admin'}' not found. 1 pattern(s) tried: ['budget-info/<str:username>'] However this is working fine with path in replace of url. I cannot understand why this is happening considering that both url and path are used to design url. -
NOT NULL constraint failed: projects_property_applications.landlord
My app allows Tenants to apply for Properties that are listed on the site by Landlords. When I try to apply for I get the following error Traceback (most recent call last): File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Maksims\Desktop\RentSpot\2020-ca472-template-repo\src\projects\views.py", line 22, in property_apply link.save() File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 746, in save force_update=force_update, update_fields=update_fields) File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 784, in save_base force_update, using, update_fields, File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 887, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 926, in _do_insert using=using, raw=raw, File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 1204, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\compiler.py", line 1384, in execute_sql cursor.execute(sql, params) File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, … -
Problem integrate a vue.js frontend with my django backend
I've problem to integrate a vue.js frontend with my django backend. I use webpack loader to insert my vue.js web-pack-stats into my django template, but I get the follow error and I dont understand why my Vue.config.js const BundleTracker = require("webpack-bundle-tracker"); const webpack = require('webpack'); //const isProd = process.env.NODE_ENV === "production"; // Change this to match the path to your files in production (could be S3, CloudFront, etc.) const DEPLOYMENT_PATH = '/static/dist/' module.exports = { // on Windows you might want to set publicPath: "http://127.0.0.1:8080/" publicPath: process.env.NODE_ENV === 'production' ? DEPLOYMENT_PATH : 'http://127.0.0.1:8080/', outputDir: '../CodeGeniusERP/static/dist', devServer: { public: 'localhost:8080', headers: {`enter code here` 'Access-Control-Allow-Origin': '*', }, }, configureWebpack: { // Set up all the aliases we use in our app. plugins: [ new BundleTracker({ path: __dirname, filename: 'webpack-stats.json' }), new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 6 }) ] }, pwa: { name: 'Vue Argon Dashboard', themeColor: '#172b4d', msTileColor: '#172b4d', appleMobileWebAppCapable: 'yes', appleMobileWebAppStatusBarStyle: '#172b4d' }, css: { // Enable CSS source maps. sourceMap: process.env.NODE_ENV !== 'production' } }; django setting.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used … -
Django Rest Framework; how to create APIs for a model which has foreignkeys to multiple models?
I have 3 models. User, Refrigerator and UserRefrigerator. class User(Model): uid = CharField(max_length=50, unique=True) name = CharField(max_length=50) class Refrigerator(Model): uid = CharField(max_length=50, unique=True) name = CharField(max_length=50) class UserRefrigerator(Model): user = ForeignKey(User, related_name="user_refrigerators") device = ForeignKey(User, related_name="refrigerator_users") is_active = BooleanField(default=True) I am using rest framework along with rest_framework_nested. I have endpoints to retrieve and create users and refrigerators like /user /refrigerators I want to build following APIs for UserRefrigerator model Create a user refrigerator entry in UserRefrigerator model. Get all refrigerators for a user. Delete the user refrigerator entry from UserRefrigerator model. What will be the REST APIs standard to achieve this? I was thinking of creating following APIs. # Create user refrigerator entry POST /users/user-uid/refrigerators/ { "refrigerator": "refrigerator-uid" } # List all refrigerators for a user. GET /users/user-uid/refrigerators/ Response should be list of refrigerator objects. I can write my own APIView to achieve this but I wanted to know if this can be done using ViewSets and Serializers. -
Trying to redirect to different page based on login credential provided in DJango
I want to redirect to different pages based on the login credentials in django. For an example: There are two login provided If i login with X credentials then i will be redirected to X page. While on same login page if i login with Y credential i will be redirected to correponding Y page. I tried to put condition in user_login views.py file but this gives me following error. Exception Type: NoReverseMatch Exception Value: Reverse for 'companyDashboard.html' not found. 'companyDashboard.html' is not a valid view function or pattern name. My views.py file from django.shortcuts import render from django.template import RequestContext from wfhApp.forms import UserForm from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth.decorators import login_required # Create your views here. @login_required def company_dashboard(request): return render(request, 'wfhApp/company_dashboard.html') @login_required def companyDashboard(request): return render(request, 'wfhApp/companyDashboard.html') @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) 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: if user.username == 'prashant': login(request, user) return HttpResponseRedirect(reverse('company_dashboard.html')) elif user.username == 'saurabh': login(request, user) return HttpResponseRedirect(reverse('companyDashboard.html')) else: return HttpResponse("Account Not Exists") else: return HttpResponse("Account Not Active") else: print("Someone tried to login and … -
How do I fetch post.id for like button in AJAX - Django?
I am returning a dictionary for number of likes of each post. The idea is to increase the likes and send it to the AJAX request so that it renders likes count without refreshing. This is the Django view that I'm using. def like(request, pk): uid = request.user.id instance = Post.objects.filter(id=pk).get() if request.user in instance.likes.all(): instance.likes.remove(uid) instance.save() count = int(instance.likes.count()) -1 json_response = {'count': count} return redirect(json_response) else: instance.likes.add(uid) instance.save() count = int(instance.likes.count()) json_response = {'count': count} return redirect(json_response) And this is what my Django HTML page looks like : {%for post in post%} <a href="{% url 'post_detail' post.id %}"><h1>{{post.title}}</h1></a> <h2>{{post.content}}</h2> <p>{{post.date}}</p> <p>{{post.likes.count}}</p> {%if user in post.likes.all%} <form action="{%url 'like' post.id %}" method="POST"> {%csrf_token%} <button type="submit" id="like" >UNLIKE</button> </form> {%else%} <form action="{%url 'like' post.id %}" method="POST"> {%csrf_token%} <button type="submit" id="like" >LIKE</button> </form> {%endif%} {%endfor%} I want that as soon as the user clicks the like button of ANY post, the AJAX should send a request to this view with the respective post ID and fetches the number of likes using the above django view and renders it next to the post. I'm not a pro in AJAX/Jquery. Please someone help me. -
ImageField in not working in nested inline model in Django admin
I am using inline models nesting. For deep models nesting I am using the django-nested-inline==0.4.2 package. ImageField is not working while using the inline model nesting. I select the image and while saving the record, image is not uploading and I am not getting any kind of error. If After selecting the image and saving Below is the code of models and admin. It's working fine while using 1 level of inline model nesting but not in deep model nesting. After saving the record image is not getting uploaded and image field is empty. models.py class Course(models.Model): name = models.CharField(max_length=255) class Book(models.Model): name = models.CharField(max_length=255) course = models.ForeignKey(Course, on_delete=models.CASCADE) class Lesson(models.Model): name = models.CharField(max_length=255) book = models.ForeignKey(Book, on_delete=models.CASCADE) class LessonImage(models.Model): image = models.ImageField(null=True, blank=True, upload_to="uploads/") lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name='lesson_image') admin.py class LessonImageInline(NestedStackedInline): model = LessonImage extra = 1 min_num = 0 class LessonInline(NestedStackedInline): model = Lesson extra = 1 min_num = 0 inlines = [LessonImageInline] class BookInline(NestedStackedInline): model = Book extra = 1 min_num = 0 inlines = [LessonInline] @admin.register(Course) class CourseAdmin(NestedModelAdmin): list_display = ('created_at', 'updated_at') list_per_page = 50 inlines = [BookInline] Course Admin Dashboard: -
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 …