Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'str' object has no attribute 'values' on webpage and Broken pipe from ('192.168.11.11', 50642)
1.python version 3.9.0 django version 3.2.4. 2.getting error AttributeError: 'str' object has no attribute 'values' to client. while on terminal i get error Broken pipe from ('192.168.11.11', 50642). i am not able to use even simple serializers. -
Django DEBUG=False won't upload files to STATIC_ROOT
I'm trying to give the user the ability to upload images on a website I created with Django and the images are uploaded fine when running with DEBIG=True but the issue is that when DEBUG=False the image files doesn't upload to the STATIC_ROOT instead it gets uploaded to STATIC_DIRS. Also, even the files that are already in STATIC_ROOT after executing python manage.py collectstatic aren't loaded to the template and the image URL gives the 404 Page Not Found error. The CSS and JS files are still served so it means only the media url isn't working. Following are the codes I'm using. urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('Home.urls')), path('account/', include('Account.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' Note that I'm using whitenoise as the storage backend. Here is the model code that is used to upload the file. @deconstructible class PathAndRename(object): def __init__(self, sub_path): self.path = sub_path def __call__(self, instance, filename): ext = filename.split('.')[-1] filename = '{}.{}'.format(uuid4().hex, ext) return os.path.join(self.path, filename) rename_pp = PathAndRename('img/profile-pictures') class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) … -
Cannot get blog listing using get_context to work properly
I am trying to make a blog listing page using wagtail 2.13 but only managed to get {{ post.date }} and {{ post.url }} parts working. {{ post.heading }} and {{ post.standfirst }} do not appear. I tried some permutations like {{ post.heading }} {{ post.content.heading }} {{ post.block.heading }} but they did not work. What would be the correct {{ }} query to use here? Image of partially working listing #models.py from django.db import models from wagtail.core.models import Page from wagtail.core.fields import StreamField from wagtail.core import blocks from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel from wagtail.images.blocks import ImageChooserBlock richtext_features = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', "ol", "ul", "hr", "link", "document-link", "image", "embed", "code", "blockquote", "superscript", "subscript", "strikethrough", ] class BlogListingPage(Page): """Listing page lists all the Blog pages.""" template = "home/home_page.html" custom_title = models.CharField( max_length=255, blank=False, null=False, help_text='Overwrites the default title', ) content_panels = Page.content_panels + [ FieldPanel("custom_title"), ] def get_context(self, request, *args, **kwargs): """Adding custom stuff to our context.""" context = super().get_context(request, *args, **kwargs) context["posts"] = BlogPage.objects.live().public().order_by('-date') return context class BlogPage(Page): """ For individual blog pages.""" author = models.CharField(max_length=255, default="Niq") date = models.DateField("Post date") content = StreamField([ ('heading', blocks.CharBlock(form_classname="full title")), ('standfirst', blocks.CharBlock()), ('paragraph', blocks.RichTextBlock(features=richtext_features)), ('image', ImageChooserBlock()), ], block_counts={ 'heading': … -
How to create two templates in django for the same applicaton?
Good afternoon community, I am new to developing and I am working on a personal project in order to practice and get experience. The URL path for my project is: http://127.0.0.1:8000/simple_investing/ simple_investing is a static html template and I would like to add another template name concepts (http://127.0.0.1:8000/simple_investing/concepts). The first part (simple_investing) works, but concepts does not. Hereunder is my code: simple_investing urls.py urlpatterns = [ path('', TemplateView.as_view(template_name='simple_investing/main.htm')), path('', TemplateView.as_view(template_name='simple_investing/concepts.htm') mysite urls.py path('simple_investing/', include('simple_investing.urls')), I get the following error 404: The current path, simple_investing/concepts, didn’t match any of these. Any hints as to how can I solve this. -
Failed SPOTIFY web api authorization with django after heroku deployment
I have been trying to create a FULL STACK web application, having REACT in the frontend and Django in the backend for the purpose of learning the usages of SPOTIFY WEB API. I am able to authenticate users through SPOTIFY WEB API in the localhost, but facing an error of "Illegal redirect_uri" on the browser after deploying to Heroku. I am unable to find any solution for this, kindly if anyone can provide me any assistance with this. I have cross-checked multiple times whether I have done any typo with the REDIRECT_URI but it's fine This is my settings.py configuration while deploying to heroku import os from pathlib import Path from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ['SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ['DEBUG'] ALLOWED_HOSTS = ['127.0.0.1', 'accounts.spotify.com/authorize', 'djangodemo-bandha.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'spotify' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', … -
django query get extra data with annotate
Assuming it is a system with user's balance and there is a model Record to record balance history class Record(models.Model): ... created_at = models.DatetimeField(auto_now_add=True) previous_value = models.IntegerField(default=0) value_change = models.IntegerField() ''' And then the list view is like Now it's required to have options to make it group by day, as: The question is: How to get the Final Balance of the Day? Current Code is only providing the change but not the balance. qs = Record.objects.order_by('-created_at').values('created_at__date').annotate(day_change=Sum('change')) -
Get related model instance within template
I've got two related models: class Event(models.Model): title = models.CharField(max_length=100) start_time = models.DateTimeField() class EmployeeJob(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE, null=True, blank=True) employee = models.CharField(max_length=100) Then, within my template, I loop through all my events. Within each loop, I want to see if there is an EmployeeJob associated with the event and if so, print the employee's name. This isn't working, however {% for events in events %} {% elif employeejob.event_set.first %} {{employeejob.event_set.first.employee}} {% endif %} {% endif %} Thanks for your help!! -
Django: how to filter a query based on one of the objects?
I have a model: class PantryHours(models.Model): DAYS = { ('Sunday', 'Sunday'), ('Monday', 'Monday'), ('Tuesday', 'Tuesday'), ('Wednesday', 'Wednesday'), ('Thursday', 'Thursday'), ('Friday', 'Friday'), ('Saturday', 'Saturday') } day_of_week = models.CharField(max_length=20, choices=DAYS, null=True, blank=True) pantry_start_time = models.TimeField(blank=True,null=True) pantry_end_time = models.TimeField() clients_allowed = models.IntegerField() spots_remaining = models.IntegerField(default=0) I want to filter the results based on this: current time < (pantry_start_time - (pantry_end_time - pantry_start_time)) so it would be something like: current_time = datetime.datetime.now() PantryHours.objects.filter(pantry_start_time=(current_time__gte =(pantry_start_time - (pantry_end_time - pantry_start_time)) However, I need the pantry_start_time and pantry_end_time of each instance and do math with it. What's the best way to do this for each instance? -
DJANGO 3.1 'crispy_forms_tags' is not a registered tag library
I'm stuck on this and its driving me crazy. I installed django-crispy-forms and added it in the settings.INSTALLED_APPS. Also, I had installed the django-crispy-forms in my virtual environment then freeze on my requirements.txt. Any help would be great. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.Contrib. staticfiles', 'crispy_forms', 'leads', 'tailwind', 'them', 'bootstrap4', client_form.py {% extends "crm/base.html" %} {% load crispy_forms_tags %} {% block content %} <h3> {% if client %} <b>Client: </b> {{ client.name }} {% else %} <b>New Client</b> {% endif %} </h3> <form method="POST" class="uniForm"> {% csrf_token %} <div class="row"> <div class="form-control"> {{form.name|as_crispy_field}} </div> </div> <div class="row"> <div class="col-md-5"> {{form.address|as_crispy_field}} </div> <div class="col-md-5"> {{form.remarks|as_crispy_field}} </div> </div> <button class="btn btn-lg btn-warning" type="submit">Update</button> </form> {% endblock content %} -
How have django async views changed in 3.2?
I've been learning how to use django for the past few weeks, and was looking into async view tutorials to try to see how they worked. I was watching one by Pyplane and noticed that the code no longer ran asynchronously. I looked into the documentation a bit more and it seemed like what he showed should have worked. I also tried hard coding it with asyncio and it gave me a SynchronousOnlyOperation error. Does anyone know a fix? Thanks in advance! views.py from django.http import HttpResponse from asgiref.sync import sync_to_async, async_to_sync import asyncio import time from movies.models import Movie from stories.models import Story # Utils def get_movies(): print("Prepare to get the movies") time.sleep(2) qs = Movie.objects.all() print(qs) print("All movies retrieved") def get_stories(): print("Prepare to get the stories") time.sleep(5) qs = Story.objects.all() print(qs) print("All stories retrieved") @sync_to_async def get_movies_async(): print("Prepare to get the movies") time.sleep(2) qs = Movie.objects.all() print(qs) print("All movies retrieved") @sync_to_async def get_stories_async(): print("Prepare to get the stories") time.sleep(5) qs = Story.objects.all() print(qs) print("All stories retrieved") # Views def home_view(request): return HttpResponse('<h1>Hello, World!</h1>') def main_view(request): start_time = time.time() get_movies() get_stories() total_time = time.time() - start_time print(f"Sync Execution time: {total_time} second(s)") return HttpResponse('<h1>Sync</h1>') async def main_view_async(request): start_time = time.time() … -
How to display error messages for multiple forms, including formsets?
Say I'm rendering a template that has multiple forms on it. The one im having issue with at the moment, I am rendering a modelform, and a formset. return render(request, "dansapp/backtest.html", { "form": form, "formset": formset }) Both forms have custom clean() methods too, just for the record. In my layout.html, I have the run of the mill code for displaying any and all form errors. It works like a charm, so long as I am rendering a template with a SINGLE form called "form". In my case, with multiple forms, how would I do with without repeating a ludicrous amount of code in my layout? It makes it even worse, because in formsets, you get a list of forms to check (I think). I also need to check the non-error fields for my custom clean() methods. {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger alert-dismissible sticky-top fade show" role="alert"> <strong>{{ field.label }}:</strong> {{ error }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger alert-dismissible sticky-top fade show" role="alert"> <strong>Validation error:</strong> {{ error }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> … -
python, django: it does not show the price on price_details.html but there is no error message
On website home page User select the airport, suburb and passenger. after that, views.py do function to calcaulate the price with that information. but the price does not appear on price_detail.html here are the codes at views.py def price_detail(request): if request.method == "POST": airport = request.POST.get('airport') suburb = request.POST.get('suburb') passenger = request.POST.get('passenger') data = { 'airport': airport, 'suburb': suburb, 'passenger': passenger, } def price_cal(): if airport == 'To airport': return int(suburbs.get(suburb)) + (int(passenger) * 10) - 10 elif airport == 'From airport': return int(suburb.get(suburb)) + (int(passenger) * 10) return render(request, 'basecamp/price_detail.html', {'price_cal()': price_cal() }, ) else: return render(request, 'basecamp/price_detail.html', {}) I do not know what was wrong... please don't telll me to do django tutorial again... I am new and beginner... that's why I ask quesitons here. Thank you in advance -
How is DRF auth token received in a real world web application
This question might look stupid but I want to get some clarification. I'm building a Django rest framework application for the very first time. I'm able to set up api endpoints for the application. And when I register a user he gets a token. And when I login a user through postman it returns a token. But in real world app, how does the client receive that drf token that is return as json data that is needed to login. Does he receive it in his email that he used to register? Also, if the user recieves the token, am I supposed to create another API to contain the field that the user eventually sends the token through before gaining access to the website? Please I would appreciate it if I also get a good material that explains the process in details and uncomplicated. -
I want to use `django` to do something like the `Github` repository
I want to use django to do something like the Github repository, but I don't know how to do it. -
Problem loading bootstrap-v5 Javascript with Django
I am currently learning Django and bootstrap, and I wanted to test some dropdown features. I looked for a while in my html code seeking for errors but apparently, the problem comes from the javascript and popper libraries of bootstrap that won't load properly. When i'm making a dropdown menu, the dropdown button is displayed, but nothing happens when I click on it. Same for all the features of bootstrap requiring JS such as alerts, toasts.. But strangely, carrousels, for which the docs indicates also they require Javascript, work properly. It doesn't matter how I try to load the JS files, it never works. I tried to load the JS and Popper separately, by including these two lines just before the closing tag : <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script> </body> I also tried the bundle : <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script> </body> It never worked so I downloaded the bundle and tried to load it this way : <script src="{% static 'js/bootstrap.bundle.js' %}"></script> This doesn't work either. When I place a test.js in the same folder with some junk inside like document.write("test"), I can see than the file is loaded properly. Also, the chrome console doesn't show any … -
Django static (css) and templates folders
I want to organize my the templates and static for each app in project as following: project/ app1/ static/ css/ app1.css templates/ app1_template.html app2/ static/ css/ app2.css templates/ app1_template.html project/ settings.py ... templates/ base.html static/ css/ base.css The intention: base.html uses only css styling from base.css Both app1_template and app2_template.html extend base.html app1_template and app2_template.html use their own .css respectively. My settings.py has these lines: TEMPLATES = [ { ... 'DIRS': [(os.path.join(BASE_DIR, 'templates')),], ... }, }, ] ... STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) In base.html: {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/base.css" %}" rel="stylesheet"> </head> <body> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> In app1_template.html: {% extends "base.html" %} {% load static %} <link href="{% static "css/app1.css" %}" rel="stylesheet"> With the above setup, my app1_template.htlm does not load app1.css styling at all. If I put the styling from app1.css into base.css, then it loads nicely. What code lines do I change to keep this organization? -
Django- Cannot assign queryset must be a instance
I am trying to make a multiple choice form, but I am getting the error: Cannot assign "<QuerySet [<Session: bbbb>, <Session: jheeyyy>]>": "Booking.session" must be a "Session" instance. I checked some solutions in stackoverflow but I can't solve it. I tried to change ModelMultipleChoiceField as ModelChoiceField but it gives "select a valid choice. that choice is not one of the available choices error." when I did it. I need help. models.py class Booking(models.Model): """ Entry recording a user registration to an event """ event = models.ForeignKey( "Event", related_name="bookings", on_delete=models.CASCADE ) person = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="bookings", on_delete=models.CASCADE ) session = models.ForeignKey( "Session", related_name="bookings", null=True, blank=True, on_delete=models.SET_NULL, ) class Meta: unique_together = ("event", "person") ordering = ["id"] def __unicode__(self): return "{0} : {1}".format(self.event.title, self.person) forms.py class SessionChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return obj.get_label() class BookingSessionForm(ModelForm): session = SessionChoiceField( label="Select your session", queryset=None, required=True, widget = forms.CheckboxSelectMultiple, to_field_name = "title", ) class Meta: model = Booking fields = ["session"] def __init__(self, target_url, *args, **kwargs): super(BookingSessionForm, self).__init__(*args, **kwargs) self.fields["session"].queryset = self.instance.event.sessions.all() self.helper = FormHelper() self.helper.form_method = "post" self.helper.form_action = reverse( target_url, kwargs={"booking_id": self.instance.id} ) self.helper.layout = Layout( "session", FormActions( Submit("save", "Confirm", css_class="btn btn-success"), Reset("reset", "Reset", css_class="btn btn-warning"), ), ) views.py def _booking_update_session(request, booking, form_target_url): """ … -
I am receiving this error when I try to send a file from react to django. (TypeError: __init__() got an unexpected keyword argument 'file')
Please help me solve this error. When I try to get the data on using file_serializer = FileSerializer(request.POST, request.FILES) instead in the picture. I receive error that name field is required even though I have passed it. I am not sure what more I can describe the error but any help would be appreciated. Models.py from django.db import models import uuid # Create your models here. class File_Uploader(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) file = models.FileField(blank=False, null=False, max_length=1000000000) name = models.CharField(max_length=64) upload_date = models.DateTimeField(auto_now=True, db_index=True) size = models.IntegerField(default=0) def __str__(self): return self.file.name Serializer.py from rest_framework import serializers from .models import File_Uploader from django.views.decorators.csrf import csrf_exempt @csrf_exempt class FileSerializer(serializers.ModelSerializer): class Meta: model = File_Uploader fields = ("file", "name", "size") views.py # from django.shortcuts import render from rest_framework.parsers import FileUploadParser, MultiPartParser from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from .serializers import FileSerializer class FileUploadView(APIView): permission_classes = [] parser_class = (FileUploadParser,MultiPartParser,) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) if file_serializer.is_valid(): file = file_serializer.data.get("file") name = file_serializer.data.get("name") size = file_serializer.data.get("size") queryset = FileSerializer(file=file, name=name, size=size) queryset.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) React File Upload Code submit = (e) => { e.preventDefault(); let file = e.target.files[0]; let … -
How to clear a validation error in Django
I have a simple registration page in my Django web application. Once a user signs up, I am able to query my database and see if the username is already in use, if it is, I display a simple ValidationError. My problem is I can't figure out how to remove the error after a few seconds. I'm pretty good with Python but haven't found any luck, the only thing I can find is this outdated article from 2010 that gives me code that doesn't work anymore. This seems like a really simple fix, just import time and run a while statement, but I can't find the docs to remove a validation error. Bellow is my function for recognizing if the username is already in use. Thank you to everyone who helps! def clean(self): cleaned_data=super().clean() if User.objects.filter(username=cleaned_data["username"]).exists(): raise ValidationError("This username is taken, please try another one") -
Prepend URL to all URLs in Django
Was wondering if there was a way to prepend all URLs with a particular URL. I'll explain the challenge, perhaps I'm going about it all wrong: Imagine I have three sites all built using Django that are run using nginx and within separate docker containers: main_site, project1 and project2. When navigating to https://main_site, this should load the pages in main_site as normal. But when navigating to https://main_site/projects/project_1/, This should navigate to project 1. And similarly, when navigating to https://main_site/projects/project_2/, this should load the pages from project 2. I've managed to make this somewhat work using nginx and docker. I have rules something along the lines of: location / { proxy_pass http://main_site; } location /projects/project_1 { proxy_pass http://project_1; } location /projects/project_2 { proxy_pass http://project_2; } This works perfectly for the homepage (minus the static assets). But, whenever we use template tags in Django, the links in creates is always relative to root (/something/), whenever on any link, it takes me back to the main_site. I get why this is happening, because everything is happening on the same port. Question is, is there a way to prepend a URL to all the URLs (static assets as well) without fundamentally having to add … -
What is problems?
TemplateDoesNotExist at / pages/index.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.4 Exception Type: TemplateDoesNotExist Exception Value: pages/index.html Exception Location: C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\Scripts\python.exe Python Version: 3.8.5 Python Path: ['C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\ecomsite_web', 'C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\Scripts\python38.zip', 'c:\programdata\anaconda3\DLLs', 'c:\programdata\anaconda3\lib', 'c:\programdata\anaconda3', 'C:\Users\Leroi\Desktop\Ecom_site\Ecomenv', 'C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\lib\site-packages'] Server time: Sat, 05 Jun 2021 21:45:06 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\lib\site-packages\django\contrib\admin\templates\pages\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\lib\site-packages\django\contrib\auth\templates\pages\index.html (Source does not exist) Traceback Switch to copy-and-paste view C:\Users\Leroi\Desktop\Ecom_site\Ecomenv\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) -
Why dashboard route is not accessible to me even if I am logged in?
I am using private route in my app to access dashboard. if I am not logged in it worked correctly and redirect me to the sign in page. but even if I am logged in it does not gives access to dashboard. Here is my code. App.js import React from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import Home from './containers/Home'; import Login from './containers/Login'; import Dashboard from './containers/Dashboard'; import PrivateRoute from './components/PrivateRoute'; import { Provider } from 'react-redux'; import store from './store'; const App = () => ( <Provider store={store}> <Router> <Layout> <Switch> <Route exact path='/' component={Home} /> <PrivateRoute exact path='/dashboard' component={Dashboard} /> <Route exact path='/login' component={Login} /> </Switch> </Layout> </Router> </Provider> ); export default App; PrivateRoute.js import React from 'react'; import { Route, Redirect } from 'react-router-dom'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; const PrivateRoute = ({ component: Component, auth, ...rest }) => ( <Route {...rest} render={(props) => { if (!auth.isAuthenticated) { return <Redirect to="/login" />; } else { return <Component {...props} />; } }} /> ); const mapStateToProps = (state) => ({ auth: state.auth, }); export default connect(mapStateToProps)(PrivateRoute); And if I am logged in on react redux tool my … -
On Heroku getting error: python: can't open file 'manage.py': [Errno 2] No such file or directory
I try to push a Django website to Heroku and run it in a Docker container. After running "git push heroku master", I get the error "python: can't open file 'manage.py': [Errno 2] No such file or directory". If I try to run "git push heroku master", I get "Everything up-to-date". But running anything involving "manage.py" such as "heroku run python manage.py migrate", will get stuck in the "connecting" phase. The following is the content of the "heroku.yml" file: setup: addons: - plan: heroku-postgres build: docker: web: Dockerfile release: image: web command: - python manage.py collectstatic --noinput run: web: gunicorn bookstore.wsgi Link to the project github What can be the problem? -
Multiple focus selectors to dinamically show QuillJS toolbar, is it possible?
I'm using Django's QuillJS version, and what I'm trying to do is display the toolbar of the selected text area only. Using JS it kinda worked: const parentDiv = Array.from(document.getElementsByClassName("django-quill-widget-container")); const toolbar = Array.from(document.getElementsByClassName("ql-toolbar")); const editor = Array.from(document.getElementsByClassName("ql-editor")); for (let i = 0; i < editor.length; i++) { toolbar[i].style.display = "none"; parentDiv[i].style.borderTop = "1px solid #ccc"; editor[i].addEventListener("focusin", function () { toolbar[i].style.display = ""; parentDiv[i].style.borderTop = ""; }); editor[i].addEventListener("focusout", function () { toolbar[i].style.display = "none"; parentDiv[i].style.borderTop = "1px solid #ccc"; }); } The problem is that clicking the toolbar to utilize its features also counts as focusout. So yeah, it doesn't work. Any idea? -
How to chain a multi-feature search in Django
I have a 3 filter search for a job. One is for the job title/decription/company, one for job category for e.g Banking and one for the location for e.g New York How do I chain the query such that it should render me the appropriate results if I specified any one filter and if I specified all 3 it should perform an AND. I tried doing it with if else, but it is becoming too long. Is there another way? Here is my code: views.py if request.method == "POST": internship_desc = request.POST['internship_desc'] internship_ind = request.POST['internship_industry'] internship_loc = request.POST['internship_location'] results = [] if internship_desc != "" and internship_desc is not None: query_results = Internship.objects.filter( Q(internship_title__icontains=internship_desc) | Q(internship_desc__icontains=internship_desc) | Q(recruiter__company_name__icontains=internship_desc) ) if internship_ind !="" and internship_ind is not None: if internship_desc != "" and internship_desc is not None: query_results = query_results.objects.filter( industry_type__iexact=internship_ind) else: query_results = Internship.objects.filter(industry_type__iexact=internship_ind) if internship_loc !="" and internship_loc is not None: if internship_desc != "" and internship_desc is not None and internship_ind !="" and internship_ind is not None: query_results = query_results.objects.filter( industry_type__iexact=internship_ind) query_results = query_results.objects.filter( recruiter__company_region__iexact=internship_loc)