Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to ban users in Django?
so I want to have a ban system in Django. For now, I have a Django app, and I want a system to ban users as long as I want to. So what I'm looking for is: is there any package or module to install, so it will be updated in the admin, so I can use to ban any user. And in the ban system, there could be an option for how many days to ban. Like weeks, months, days and more. And after I ban, when that user tries to log in, they should get a message saying you are banned. So please let me know how to do this. IF there is a module or package to install, or if there's any other way to do it. Any type of ban system is good. Thanks! -
Django Rest Framework endpoint does not work with SPA and axios, but works with other client like vscode REST Client extension
I bootstrapped this project with cookiecutter-django, and did not make any changes to the security settings or DRF endpoints. You can find settings/base.py and settings/local.py below. Currently both Django and React work on localhost. I am trying to do a crossorigin setup. E.g. React static will be served by Firebase in www.mydomain.com, and Django app will be on some other host. Thanks. I call Axios in a React SPA like this (handleLogin is the onClick handler): const domain = "http://localhost:8000/"; const handleLogin = () => { axios .post(domain + "auth-token/", { username: username, password: password, }) .then((res) => { setErrorMessage("Success res:" + JSON.stringify(res)); }) .catch((err) => { setErrorMessage("Error err:" + JSON.stringify(err)); }); }; And I get the error: Error err:{"message":"Network Error", "name":"Error", "stack":"Error: Network Error\n at createError (https://localhost:3000/taskpane.js:15266:15)\n at XMLHttpRequest.handleError (https://localhost:3000/taskpane.js:14751:14)", "config":{"url":"http://localhost:8000/auth-token/","method":"post", "data":"{\"username\":\"johndoe\",\"password\":\"mypass\"}", "headers":{"Accept":"application/json, text/plain, */*", "Content-Type":"application/json;charset=utf-8"}, "transformRequest":[null],"transformResponse":[null], "timeout":0,"xsrfCookieName":"XSRF-TOKEN", "xsrfHeaderName":"X-XSRF-TOKEN", "maxContentLength":-1,"maxBodyLength":-1}} Following vscode REST Client extension request works, e.g. I get a token: # Send Request POST http://127.0.0.1:8000/auth-token/ Content-Type: application/json { "username": "johndoe", "password": "mypass" } settings/base.py: """ Base settings to build other settings files upon. """ from pathlib import Path import environ ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent.parent # mysite/ APPS_DIR = ROOT_DIR / 'mysite' env = environ.Env() READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=False) … -
Can I make multiple child models "likeable" in Django?
This is my first post here at Stackoverflow. I got a Post model containing 1 or more Article(child) models. I want to be able to like/dislike each child model seperatly. Here is the models: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class Article(models.Model): publisher = models.CharField(max_length=100) url = models.URLField(max_length = 200) likes = models.ManyToManyField(User, related_name='article_like') dislikes = models.ManyToManyField(User, related_name='article_dislike') blog_post = models.ForeignKey(Post, on_delete=models.CASCADE) -
Wrapping Django Backend and Node frontend into executable (.exe)
I have managed to wrap my Django backend(REST framework) into an executable using pyinstaller and wrap my Node frontend (HTML, JS and CSS) into an executable with pkg. Both of them can be run separately and can communicate with each other. Currently, I have tried using a bat file to run them at once but there will be two terminal windows appear for backend and frontend respectively. I am thinking whether there is a way to combine them both and run with a click on icon. And it is possible to not show the terminal? -
How to install Python with Sqlite3 on a hosted server
I'm a bit green where it comes to app deployment and I'm trying to deploy a Django app on a hosted server (app written in Python 3.8.8 win 32-bit). Since the server does not have any Python packages yet, I tried to install Python the following way through SSH bash: wget https://www.python.org/ftp/python/3.8.8/Python-3.8.8.tgz tar xvzf Python-3.8.8.tgz cd Python-3.8.8 ./configure --prefix=$HOME/.local make make install It does seem to install Python 3.8.8 so I then proceed to clone the code from Git and create virtual environment. The problem comes up when I try to install packages from requirements.txt and, specifically, for psycopg2 it shows an error that there is a missing module "_ctypes". I found that sometimes that reinstalling Python may help, but it didn't. Instead, I tried to install psycopg2-binary by pip install psycopg2-binary and it did work. However, when I try to run python manage.py collectstatic it's showing that Sqlite3 is missing. From what I learned, sqlite3 should be included in Python3 (it is when I install it on my PC). checked the folder directory and it indeed seems to be missing. Reinstalling did not help here either. Could those errors be caused by the fact that I'm installing Python incorrectly? … -
Template does not exist, django paths
Trying to run my server, but it doesn't seem to be cooperating. This is the text displayed when I tried running it: django.template.loaders.app_directories.Loader: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/contrib/admin/templates/rest_framework/api.html (Source does not exist) I have 'rest_framework' in my settings, 'INSTALLED APPS', I'm not sure what's going on -
How to add an array object to nested object in Django?
I need to add an array of objects to an another object whose structure has been shown below. Here is current response from Album: [ { "id": "1", "name": "Skin", "artists": [ { "id": "1", "name": "Flume", } ], "tracks": [ { "id": "1", "name": "Take A Chance" } ] } ] I need to transform tracks object from Album's response to this: [ { "id": "1", "name": "Skin", "artists": [ { "id": "1", "name": "Flume", } ], "tracks": { "items": [ { "id": "1", "name": "Take A Chance" } ] } } ] Here is my current models: class Artist(models.Model): name = models.CharField(max_length=300) albums = models.ManyToManyField('albums.Album', related_name='artists') tracks = models.ManyToManyField('tracks.Track', related_name='artists') class Album(models.Model): name = models.CharField(max_length=400) class Track(models.Model): name = models.CharField(max_length=400) album = models.ForeignKey('albums.Album', related_name='tracks', on_delete=models.CASCADE) -
Django 3.2 Model not instantiating properly in the register function
I apologize if my mistake is incredibly simple but I am completely new to Django. Currently, my models.py currently contains 2 types of profiles extending off of the default Django User model: from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) def __str__(self): return self.user.username class PCOProfile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) org_name = models.CharField(max_length = 100) org_phone = models.CharField(max_length = 20) is_active = models.BooleanField(default = False) def __str__(self): return f"{self.user.username} | {self.org_name}" I have a views.py file which contains 2 functions, one called register and another register-pco that collects base user information, as well as information related to only one of of these models as a form on the same page which will be submitted at the same time as the base user information: from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegistrationForm, UserProfileForm, PCOProfileForm def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) profile_form = UserProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() # Hooking up user_profile model to django default user model profile = profile_form.save(commit=False) profile.user = user profile.save() username = … -
I need to go to new page when reload this page button in browser is clicked in django
I am doing a web application using django framework. In a form in my app I need to go or redirect to a new page when reload this page button on the browser is clicked. Really appreciate the community for your answers. app.html <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <form method="post"> {% csrf_token %} #somecode <button type="submit" class="btn btn-primary">YES</button> </form> </body> </html> When this page is relaoded or refreshed I need to go to a new page(my home page in views.py) -
Next js Django Djoser Google authentication/
I am creating a website using next js and django and trying to authenticate with Google social auth . For this I am using djoser library and other library for JWT like django-simple-jwt. At first everting is okay . I can select my google account but it retuns bad request as 400 status . When I tried using postman it gives following error : ** "non_field_errors": [ "State could not be found in server-side session data." ]** Google.tsx file import React, { useEffect } from 'react'; import { connect } from 'react-redux'; import { googleAuthenticate } from '../actions/auth.action'; import { useRouter } from 'next/router' const Google = ({ googleAuthenticate }) => { const router = useRouter(); const code = router.query.code; const state = router.query.state; useEffect(() => { if (state && code) { googleAuthenticate(code, state) } }, [state, code]); return ( <div className='container'> <div className='jumbotron mt-5'> <h1 className='display-4'>Welcome to Auth System!</h1> <p className='lead'>This is an incredible authentication system with production level features!</p> <hr className='my-4' /> <p>Click the Log In button</p> <Link href='/LoginApi' ><button>Login</button></Link> </div> </div> ); }; export default connect(null, { googleAuthenticate })(Google); my redux action file as : export const googleAuthenticate = (state, code) => async dispatch => { console.log("GoogleAuthenticate … -
how can i filter with Django gabarit a condition on through model
In Django i would like to apply in a template a filter regarding a condition on a through model. I have the following models class Article(models.Model): txt_article = models.TextField(unique=True) teacher = models.ManyToManyField(User, through='Teacher_article', related_name='articles') class Teacher_article(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) article = models.ForeignKey(Article, on_delete=models.CASCADE) order_teacher = models.IntegerField() the view : select_article = Article.objects.get(txt_article=txt_ask) In the gabarit, i want to show for one article the teacher in the order : order_teacher but this solution is not working {% for teacher_i in select_article.teacher.all|dictsort:"order_teacher" %} {% endfor %} thanks a lot, Gonzague -
Django, how to test migration without creating new files / django_session row
I have an app called Sliders and have created the models. How do i run the migration, so just the database tables get created but no new entries in django_session table and no directory migrations created in app directory. This is what i normally do: After model is created then make migration file: python manage.py makemigrations sliders Then i run migration file: python manage.py migrate sliders This makes a migration directory in the Sliders app and inserts rows to django_sessions table. How do i prevent this? Just want the table to be created in database. -
Update model field ( SearchVector ) using signals.py
I am trying to update search vector field using post_save signal. Through "Admin.py", It is working perfectly, but through "Form page" , the searchVector field or any other field is not getting updated. In form page, I have many to many field - "Tag" that I save through "form.save_m2m" method Please review my code and suggest .. https://dpaste.org/ujPi Thanks in advance #models.py class JobPostManager(models.Manager): def search(self, search_text): search_vectors = ( SearchVector( 'job_title', weight='A', config='english' ) ) search_query = SearchQuery( search_text, config='english' ) search_rank = SearchRank(search_vectors, search_query) trigram_similarity = TrigramSimilarity( 'job_title', search_text ) qs = ( self.get_queryset() .filter(search_vector=search_query) .annotate(rank=search_rank + trigram_similarity) .order_by('-rank') ) return qs class JobPost(models.Model): job_title = models.CharField(max_length=100, db_index=True) job_description = models.TextField() tags = TaggableManager() author = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True) company_name = models.CharField(max_length=100,blank=True,null=True, db_index=True) objects = JobPostManager() def __str__(self): return self.job_title def get_absolute_url(self): return reverse('job_post_detail', kwargs={'slug': self.slug, 'pk':self.pk}) #################################################################################### #################################################################################### # views.py class JobPostCreateView(LoginRequiredMixin, CreateView): model = JobPost fields = ['job_title','job_description','tags'] widgets = { 'tags' : forms.TextInput(attrs={'data-role':'tagsinput'}), } def get_form(self): form = super().get_form() form.fields['tags'].widget = forms.TextInput(attrs={'value': 'all'}) return form def form_valid(self, form): print("views - form valid - run ") newpost = form.save(commit=False) form.instance.author = self.request.user form.instance.company_name = self.request.user.company_name print("form---------------------------") print(form.instance.author) print(form.instance.job_title) print(form.instance.company_name) print("form end---------------------------") newpost.save() print('newpost') print('--------------------------------',newpost) print('newpost',newpost.author) print('newpost',newpost.job_title) … -
How to create InMemoryUploadedFile objects proper in django
I,m using a python function to resize user uploaded images in django.I use BytesIO() and InMemoryUploadedFile() classes to convert pillow object to django UplodedFile and save it in the model. here how I instanciate InMemoryUploaded file object from PIL import Image import io import PIL import sys from django.core.files.uploadedfile import InMemoryUploadedFile def image_resize(image,basewidth): img_io = io.BytesIO() #code to resize image percent = (basewidth / float(img.size[0])) hsize = int(float(img.size[0]) * percent) img = img.resize((basewidth, hsize),PIL.Image.ANTIALIAS) img.save(img_io, format="JPEG") new_pic= InMemoryUploadedFile(img_io, 'ImageField', 'profile_pic', 'JPEG', sys.getsizeof(img_io), None) return new_pic but this resize the image and it does not save the file as jpeg it saves the file with type of File but when replace the filename with profile_pic.jpg it saves with the type of jpeg. why this happens -
Retreive last order of each customer
I am creating an API for the shop. There I should return the last order of each customer. Here is the code for my Customer and Order models. class Customer(models.Model): name = models.CharField(max_length=14, null=True) country = models.CharField(max_length=3, null=True) address = models.TextField() phone = models.CharField(max_length=50) class Order(models.Model): date = models.DateField(null=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) This is serializers.py class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ['id', 'name', 'country', 'address', 'phone'] class OrderSerializer(serializers.ModelSerializer): customer = CustomerSerializer() class Meta: model = Order fields = ['id', 'date', 'customer'] I am getting the last order of each customer using Django ORM in the following way @api_view(('GET',)) def customers_last_orders(request): orders = models.Order.objects.all().order_by('customer', '-date').distinct() serializer = serializers.OrderSerializer(orders, many=True) return Response(serializer.data) But I am getting from this view all the orders in descinding order. -
modelformset repeated my fields and fetching value from my db
I am using django 3 and modelformset, But I found a wired thing, that the modelformset is repeating my fields and autofilling the value: models.py `class DemoForm(forms.ModelForm): class Meta: model = Demo fields = ['title','content','type'] #def get_absolute_url(self): # return reversed('index') widgets ={ 'title': forms.TextInput(attrs={'class':'form-control','style':'width:500px;'}), 'content': forms.Textarea(attrs={'class':'form-control'}), 'type': forms.Select(attrs={'class':'form-control','style':'width:300px;'}), } #labels = {'title': 'Demo Name',"content":"Demo details","type":"Demo type"} class HostForm(forms.ModelForm): class Meta: model = Host fields = ['name','ip','os','method'] widgets ={ 'name': forms.TextInput(attrs={'class':'form-control'}), 'ip': forms.TextInput(attrs={'class':'form-control'}), 'os': forms.TextInput(attrs={'class':'form-control'}), 'method': forms.Select(attrs={'class': 'form-control','style':'width:300px;'}) } class CredForm(forms.ModelForm): class Meta: model = Credentials fields = ['login_user','keys','port'] widgets ={ 'login_user': forms.TextInput(attrs={'class':'form-control'}), 'keys': forms.TextInput(attrs={'class':'form-control'}), 'port': forms.TextInput(attrs={'class':'form-c ontrol'}) }` views.py `def cicd(request): u_session = request.session['user'] user = SystemUser.objects.get(username=u_session['name']) form1 = DemoForm() HostFormSet = modelformset_factory( model=Host, form=HostForm, extra=1 ) hostFormSet = HostFormSet() CredFormSet=modelformset_factory( model=Credentials, form=CredForm, extra=1 ) credFormSet=CredFormSet() demo = Demo.objects.all() for form in hostFormSet.forms: print(form) return render(request, "cicd.html", {'user': user,'form1':form1,'hostFormSet':hostFormSet,'credFormSet':credFormSet,'demo':demo})` template ` {% csrf_token %} {{form1.media}} {{form1.as_p}} {{ hostFormSet.as_p }} {{ credFormSet.as_p }}` But the form is rendered like this: Which is not horning the extra value and more strange it is autofilling the fileds value fetched from db automatically: Please help out, it is very strange! Thanks in advance. -
Can't get django-db-geventpool working in Heroku
I'm trying to set up my Django app in Heroku to use DB pooling, but I get an error when deploying the application to Heroku. I was following the guide for installing django-db-geventpool here: https://github.com/jneight/django-db-geventpool but that is not working. My guess is that for some reason Heroku is not loading my gunicorn_config.py file when launching gunicorn, but not sure why? My Procfile: release: python manage.py migrate web: gunicorn app.wsgi -k gevent --worker-connections 100 --timeout 600 --config gunicorn_config.py My gunicorn_config.py: from psycogreen.gevent import patch_psycopg # use this if you use gevent workers def post_fork(server, worker): patch_psycopg() worker.log.info("Made Psycopg2 Green") My settings.py: DATABASES = { 'default': dj_database_url.config(conn_max_age=500) } DATABASES['default'].update( ATOMIC_REQUESTS=False, OPTIONS={ 'MAX_CONNS': 4 } ) Here is the stack trace when deploying to Heroku: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django_db_geventpool/backends/postgresql_psycopg2/base.py", line 13, in <module> remote: from gevent.lock import Semaphore remote: ModuleNotFoundError: No module named 'gevent' remote: During handling of the above exception, another exception occurred: remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 115, in load_backend remote: return import_module('%s.base' % backend_name) remote: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 994, … -
Django Rest Framework - Add Data and return it
I am new to Django Rest Framework and trying to create add data upon request and return the data after creating. My URL is path('quiz/<str:classId>/<str:subject>/<str:chapter>', CreateQuiz.as_view()), I want to add a row to Quiz Model using the parameters in the URL and return it. How should I approach this ? I tried adding it in get_queryset method and it runs twice. Any guide to this specific problem ? Please help. -
how to make Qrcode scanner in django
how i can make qrcode scanner in django like this web so i can see the result in text not in image video i already make the views.py like this def camera_feed(request): stream = CameraStream() frames = stream.get_frames() return StreamingHttpResponse(frames, content_type='multipart/x-mixed-replace; boundary=frame') def detect(request): stream = CameraStream() success, frame = stream.camera.read() if success: status = True else: status = False return render(request, 'detect_barcodes/detect.html', context={'cam_status': status}) my camera_stream.py class CameraStream(str): def __init__(self): self.camera = cv2.VideoCapture(0) def get_frames(self): while True: # Capture frame-by-frame success, frame = self.camera.read() if not success: break else: ret, buffer = cv2.imencode('.jpg', frame) color_image = np.asanyarray(frame) if decode(color_image): for barcode in decode(color_image): barcode_data = (barcode.data).decode('utf-8') else: frame = buffer.tobytes() #hasil2 = b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + barcode_frame + b'\r\n\r\n' yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') this is my urls.py path('camera_feed', views.camera_feed, name='camera_feed'), path('detect_barcodes', views.detect, name='detect_barcodes'), and i use the html like this <img src="{% url 'qrcode' request.path %}" width="120px" height="120px;"> how i can pass the result in html? -
Django razorpay: How to get the order id after payment is complete
As per my understanding. Step1) create Order_id order_amount = 50000 order_currency = 'INR' order_receipt = 'order_rcptid_11' notes = {'Shipping address': 'Bommanahalli, Bangalore'} # OPTIONAL obj = client.order.create(amount=order_amount, currency=order_currency, receipt=order_receipt, notes=notes) then save order in databas order_id = obj['id'] Orders( id=order_id, status="pending", user=user, razorpay_payment_id="", razorpay_order_id="", razorpay_signature="").save() Step2 - Pass the order_id to the checkout page <form action="https://www.example.com/payment/success/" method="POST"> <script src="https://checkout.razorpay.com/v1/checkout.js" data-key="YOUR_KEY_ID" // Enter the Test API Key ID generated from Dashboard → Settings → API Keys data-amount="29935" // Amount is in currency subunits. Hence, 29935 refers to 29935 paise or ₹299.35. data-currency="INR"//You can accept international payments by changing the currency code. Contact our Support Team to enable International for your account data-order_id="order_CgmcjRh9ti2lP7"//Replace with the order_id generated by you in the backend. data-buttontext="Pay with Razorpay" data-name="Acme Corp" data-description="A Wild Sheep Chase is the third novel by Japanese author Haruki Murakami" data-image="https://example.com/your_logo.jpg" data-prefill.name="Gaurav Kumar" data-prefill.email="gaurav.kumar@example.com" data-theme.color="#F37254" ></script> <input type="hidden" custom="Hidden Element" name="hidden"> </form> Step3: Get the reponse on payment completed { "razorpay_payment_id": "pay_29QQoUBi66xm2f", "razorpay_order_id": "order_9A33XWu170gUtm", "razorpay_signature": "9ef4dffbfd84f1318f6739a3ce19f9d85851857ae648f114332d8401e0949a3d" } Now We have to verify this. But here we dont know this response is for which order_id as per this image. Because i have seen someone using the below to retrieve the order Orders.objects.get(order_id = … -
Decrease default checkbox size in django
I am developing a blood bank in django, and when updating the details of receiver in webpage, I have a checkbox called 'show details in receiver list' when rendering that checkbox from {{form.showDetails}} the size of the checkbox is huge and I cannot resize the size of that checkbox. If you have any idea to resize that box please share it. It would help me a lot. I have tried to decrease the size of that division but it did not help. And the code when rendering the checkbox data from the database is below. <div class="col-md-6"> <label for="inputAllergies" class="form-label">Show details in receiver list:</label> <div class="form-input" style="background-color:red; height: 20px;"> {{ form.showDetails}} </div> </div> -
Django sessions updated at django channel consumers
I am trying to update a certain Django request session value in my Django channel consumer. from my understanding from channels documentation, it’s the same session object and my session is updated correctly when I change its value in the consumer. however, when I reset my session value on the view side the value remains unchanged at the consumer session object. I could be missing something very simple. or my understanding of how this works is faulty. here is the snippet where I update at the consumers.py: self.scope['session']['unr_msg'] = f"{int(self.scope['session']['unr_msg']) + 1}" self.scope['session'].save() and at views.py : request.session['unr_msg'] = 0; request.session.modified = True I appreciate any help on this Best, -
NPM packages with Django CookieCutter
I am trying to setup my packages with NPM (instead of using Bower) with Django Cookiecutter. it is a fresh install of Cookiecutter. I can not get the packages to work. there is noting in my staticfiles. I am using gulp and it works fine. no issues when i run 'npm run dev' the packages show up as dependencies in the package.json. so how can i get the NPM packages to work as static files like: <script src="{% static 'jquery/dist/jquery.js' %}"></script> Thank you. from package.json "dependencies": { "foundation-sites": "^6.6.3", "jquery": "^3.6.0", "motion-ui": "^2.0.3", "what-input": "^5.2.10", "zingchart": "^2.9.3" }, "devDependencies": { "autoprefixer": "^9.4.7", "browser-sync": "^2.14.0", "cssnano": "^4.1.10", "gulp": "^4.0.0", "gulp-imagemin": "^5.0.3", "gulp-plumber": "^1.2.1", "gulp-postcss": "^8.0.0", "gulp-rename": "^1.2.2", "gulp-sass": "^4.0.2", "gulp-uglify-es": "^1.0.4", "pixrem": "^5.0.0" }, here is how cookiecutter sets up the gulpfile.js which is working fine when i run 'npm run dev. //////////////////////////////// // Setup //////////////////////////////// // Gulp and package const { src, dest, parallel, series, watch } = require('gulp') const pjson = require('./package.json') // Plugins const autoprefixer = require('autoprefixer') const browserSync = require('browser-sync').create() const cssnano = require ('cssnano') const imagemin = require('gulp-imagemin') const pixrem = require('pixrem') const plumber = require('gulp-plumber') const postcss = require('gulp-postcss') const reload = browserSync.reload const rename … -
<QuerySet Tags passing Through
So currently learning Danjo and have a problem I can't seem to get my head around. I have a model called eventlists which holds events (future and past), there is a separate table that holds event prices (because events have variable prices based on when you book). I have managed to join this data and pull it though to my template, all the fields from the eventslist table render correctly but the price field still comes through as: <QuerySet [Decimal('50.00')]>, the data itself is correct. Below is the view that is being executed, but I can for the life of me see this issue: def events_list_view(request): future_events = eventslist.objects.filter(eventStart__gt=datetime.now()).order_by('eventStart').prefetch_related("eventProductsList") past_events = eventslist.objects.filter(eventStart__lt=datetime.now()).order_by('eventStart').prefetch_related("eventProductsList") for future_event in future_events: currentEventActiveProduct = eventProducts.objects.filter(parentEvent=future_event.id, isActive=True) future_event.currentPrice = currentEventActiveProduct.values_list("productPrice", flat=True) return render(request, "events/eventlist.html",{'future_events':future_events, 'past_events':past_events,}) I'm sure its something super obvious that's just my lack of knowledge. -
Django Summernote Shows Blank on pythonanywhere but works fine locally
from django_summernote.widgets import SummernoteWidget # creating a form class PostForm(forms.ModelForm): content = forms.CharField(widget=SummernoteWidget()) # create meta class class Meta: # specify model to be used model = Post # specify fields to be used fields = [ "title", "slug", "content", "status", "youtubeVideo", "category", "image", ] create_post Template: {% load crispy_forms_tags %} <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ form | crispy}} <input type="submit" value="Submit" class="btn btn-danger"> <a href="/posts/posts_manager" class="btn btn-info">Cancel </a> </form> works fine locally but not on server.