Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'login' is not defined error happens in React.js
I made frontend app in React.js. I wrote codes in App.js of frontend like import React, { Fragment, useState, useEffect, Component, View } from 'react'; import axios from 'axios'; import Routes from '../src/components/Routes'; import TopNavigation from './components/topNavigation'; import SideNavigation from './components/sideNavigation'; import Footer from './components/Footer'; import './index.css'; import Router from './Router'; const App = () => { const [user, setLogin] = useState(null) const [report, setReport] = useState(null) useEffect(()=>{ login().then(user => setLogin(user)) }, []) useEffect(()=>{ getReport().then(report => setReport(report)) }, []) return <div> {user != null? <p>name: {user.name}</p>:<button>Login</button>} </div> } export default App; I wrote in this code login().then(user => setLogin(user)) whether user already logined or not. Login system was made in Django,so I want to use it.I think React has login method but I really cannot understand what is wrong.How should I fix this? -
How to render signals.py error message to the django-rest API?
I am trying to render the error message from Django signals.py file to django-restframework views.py. I created the views.py file like this, class HazardIndexViewSet(viewsets.ModelViewSet): queryset = HazardIndex.objects.all() serializer_class = HazardIndexSerializer permission_classes = [permissions.IsAuthenticated] My signals.py file looks like, @receiver(post_save, sender=HazardIndex) def publish_to_geoserver(instance, created, *args, **kwrgs): try: geo.create_coveragestore(instance.name, instance.workspace_name, path=instance.file) exception as e: instance.delete() print("Something is wrong while creating coveragestore") I want this print statement(print("Something is wrong while creating coveragestore")) to display the error message in API. And another things is, I want to create the instance only if the publish_to_geosever function runs successfully. Otherwise it should through error. Any help? -
Cloudinary & Django - Django3 does not support django.utils.six fix?
I am using Heroku to deploy an application that I made with Django 3.1.2 (python 3.6.12), and I am using Cloudinary to store uploaded images. I am running into a ModuleNotFoundError (shown below) because cloudinary-storage imports django.utils.six, but Django 3.0 does not support django.utils.six. I have researched a bit, but have not found a working answer. One suggestion was to downgrade to Django2 - but when I did this I started receiving many other errors for other parts of my application so I don't want to go this route if possible. So now I am trying to figure out a way that I can use Django3 and Cloudinary together, and get around the problem that Django3 does not support django.utils.six. Any help/suggestions would be greatly appreciated Here is the traceback: Django Version: 3.1.2 Python Version: 3.6.12 Installed Applications: ['users.apps.UsersConfig', 'point_system.apps.PointSystemConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cloudinary_storage', 'cloudinary'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py", line 98, in dispatch … -
EC2 files - slow to display
Environment : Django I have a python function def get_downloading_videos(project_id, stream_name): objects = [] ssm = get_aws_service_client('ssm') response = ssm.list_commands(InstanceId='i-xxxxxxxxxxx', Filters=[{'key': 'ExecutionStage', 'value': 'Executing'}]) for download_req in response['Commands']: command = download_req['Parameters']['commands'][0] if project_id in command and stream_name in command: video_params = {'url': '', 'key': '', 'command_id': download_req['CommandId'], 'start_time': download_req['RequestedDateTime'].strftime('%Y-%m-%d %H:%M:%S'), 'status': 'executing'} objects.append(video_params) return objects When I want to display these files on a webpage, if I have some files which match with these filters, display is normal. But if I don't have any files, loading is very very slow. Also, is there any way to display EC2 files in instance in JavaScript with SDK? -
How to get data from another different ModelForm
Is it possible to auto populate data from a search to a two different ModelForm ? What I want to do is when I "search" using a GET Method, it shows the Asset details, after the query. the page shows the Asset details with a "Assign" button, when pressed it passes on the "asset_id" and goes to the next HTML create form(LoanerForm). My problem is that on the LoanerForm does not auto populate the "asset_number". I dont get why, the pk is correct and I pass it on as instance on the Form. The other fields updates except the "asset_number" remains the default select option. My View: def loaner_view_page(request): asset = request.GET.get('q') my_asset = Asset.objects.filter(asset_number=asset) print('Printing results', request.GET) context = { 'asset':my_asset, } return render(request, 'assets/asset_loaner_page.html', context) def loaner_assign(request, pk): asset = Asset.objects.get(id=pk) form = LoanerForm(instance=asset) if form.is_valid(): print('Printing results', request.POST) form.save() return redirect('/Dashboard/') context = { 'form': form, } return render(request, 'assets/asset_loaner_assign.html', context) My Model: class Asset(models.Model): model_item = models.ForeignKey(Model_Items, null=True, on_delete= models.SET_NULL) po_number = models.ForeignKey(Po, null=True, on_delete= models.SET_NULL) asset_number = models.CharField(max_length=10, default='') serial_number = models.CharField(max_length=10, default='') asset_location = models.ForeignKey(Location, null=True, on_delete= models.SET_NULL) asset_type = models.CharField(max_length=10, default='')#primary device owner/loaner def __str__(self): return self.asset_number class Loaner(models.Model): loaner = models.ForeignKey(Asset, null=True, … -
Patch ajax to a viewset returns 403 and works with APIview. DjangoRestFramework
I have a simple ajax request made with jQuery. It keeps returning 403, despite the same request works ok with APIview. let option_id = $('.option_checkbox_checked').attr('value') let token = $('#token').attr('value') var patch = { 'selected_options': option_id, 'csrfmiddlewaretoken': token } $.ajax({ url: 'http://127.0.0.1:8000/api/router/user_passed_test/5/', type: 'PATCH', dataType: 'json', data: patch, success: function (data) { console.log(data) } }) Viewset looks like following: class UserPassedTestViewSet(viewsets.ModelViewSet): permission_classes = [permissions.AllowAny] serializer_class = UserPassedTestSerializer queryset = UserPassedTest.objects.all() -
Views and HTTPresponse with user's data - Django
Given a GET the url is /home/data Where data is a value that will depend on the user, that is, the complete domain will be domain/home/data What I want is to return an HTTP response depending on the data value url.py urlpatterns = [ path('admin/', admin.site.urls), path('home/', home, name='home'), ] views.py def home (request): response =item.objects.filter(radius<data) return HttpResponse(response ) As you can see, radius is an attribute of the item model. And I want to filter all radius that are less than data. How can I include data in that home function? -
Im am doing a project in the book "Python crash course 2nd eddition"
I am doing the web applications project and I have successfully deployed my project to heroku.com but my topics and entries are not synced with the server only the person who created the topic/ entry can see it. When I am on the admin sight i can see who all the different entries but for some reason, even as an admin no one can see each others topics or entries. -
Django overriding form_valid with other processing functions not related to form
This is more of a best practices Django question that I am struggling with. I am uploading an excel file via a form, in which the form_valid function is overridden adding some data prior to calling form.save(), however I also need to save the headers (columns) for the file at the same time, to ensure the file and the headers are saved together. Is this acceptable below or am I handling too much logic inside of form_valid that really does not belong there? It would look something like this in views: class FileUploadCreateView(generic.CreateView): template_name = 'fileupload/file-create.html' form_class = FileUploadModelForm success_message = 'Success: File was uploaded.' def get_success_url(self): return reverse('files_list') def form_valid(self, form): self.instance = form.save(commit=False) self.instance.file_upload = form.cleaned_data['file_upload'] self.instance.my_user = self.request.user self.instance.file_status = 'ready' form.save() # Get file object just saved fileObj = FileUpload.objects.filter(id=self.instance.id) file_upload_path = fileObj.file_upload.path # validation logic handled in forms to determine file type # Process excel file headers df = pd.read_excel(file_upload_path, header=0) col_names = list(df.columns.values) fhModel = FileHeaders() fhModel.my_user = userObj fhModel.file_upload = fileObj fhModel.file_headers = json.dumps(col_names) fhModel.save() return super().form_valid(form) -
How to make field editable not for all instances in django admin list view?
How to make field editable not for all instances in django admin list view. For example if sum exists make this instance editable. I tried override ModelForm and add widget but it doesn't work. Also I tried override has_permission function but it doesn't work too. -
Database for a fair reservation system
I'm developing a fair reservation system for people who sign up for using a stand of the fair but I'm quite complicated on defining the database since I later on need to use a search feature and see which stand is occupied for specific date, so here is what I've come up with: from django.db import models from .choices import CATEGORY class Fair(models.Model): name = models.CharField(max_length=30) number_of_stands = models.IntegerField() class Stand(models.Model): entrepreneur = models.ForeignKey(Entrepreneur, on_delete=models.CASCADE) check_in = models.DateTimeField(null=True, blank=True) checkout_in = models.DateTimeField() entrepreneur_category = models.IntegerField(choices=CATEGORY, default=3) class Entrepreneur(models.Model): name = models.CharField(max_length=30) email = models.EmailField() I'm looking for some guidance to have this working later on when using the search and date range filter. I'm not quite sure if this could work because the check_in/checkout might not the the most proper way to do it. Is this the best way to do it? -
Celery task hanging on Django app with Rabbitmq
I'm following the First Steps With Django for my app running on a docker container. I have rabbitmq setup on a separate docker container. Opening a python shell to run the task add just results in hanging/freezing without any reports/errors from celery interface. Below are the details. Django version - 3.0.5 Celery - 5.0.2 amqp - 5.0.2 kombu - 5.0.2 Rabbitmq - 3.8.9 myapp/myapp/settings.py CELERY_BROKER_URL = 'pyamqp://guest:guest@myhost.com//' CELERY_RESULT_BACKEND = 'db+postgresql+psycopg2://postgres:111111@myhost.com/celery' myapp/myapp/celery.py import os from celery import Celery import logging logger = logging.getLogger(__name__) # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('myapp') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') logger.error('in celery') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') myapp/myapp/init.py from .celery import app as celery_app import logging logger = logging.getLogger(__name__) logger.error('in init') __all__ = ('celery_app',) myapp/otherapp/tasks.py from celery import shared_task import logging logger = logging.getLogger(__name__) @shared_task def add(x, y): logger.error('add') return x + y Once I run celery -A demolists worker --loglevel=INFO in terminal, I get the … -
Resizing bootstrap cards to match them
I'm using the card bootstrap parameters, but my differents card-img-top resizes differently. I'm searching for css in order to make them even but trying to maintain the same quality or similar. -
Python. Upload CSV file, show results in the table and import results from table to database
Hello i am looking for some solution with which will be easier to realise such functionality on Python 2.7 (Django and Bootstrap). Upload CSV file Show results in the table (will be frontend future with possibility to edit ce Import results from table to database Need your recommendations for realisation such functionality. Thank you! -
Django: delete requests returning error 405
I have a small React/Django blog app and I'm trying to change the behavior on a DELETE request. Specifically I want to check if the post in the database has a field called "protected" equal to true or not, and fail if true. At some point before this, deleting posts worked fine. When I overloaded the destroy method in PostView in views.py below, I noticed that it didn't work. The destroy method is never called - I never see the print statement inside. The server respondes with a 405 request and never calls destroy. Here's the error: Method Not Allowed (DELETE): /api/posts/3 Method Not Allowed: /api/posts/3 [29/Nov/2020 17:03:04] "DELETE /api/posts/3 HTTP/1.1" 405 0 If I remove my destroy method, it still doesn't work like it did previously, so I think I broke something unrelated. What am I missing? Here's my urls.py: from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.urls import path, include, re_path from rest_framework import routers from server import views from .views import index router = routers.DefaultRouter() router.register(r'posts', views.PostView, 'post') urlpatterns = [ path('', index, name='index'), path('admin/', admin.site.urls), path('api/', include(router.urls)), re_path(r'^(?:.*)/?$', index, name='index'), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and views.py: from rest_framework import viewsets, status … -
'NoneType' object has no attribute 'model' despite rendering form in template
I am getting the AttributeError 'NoneType' object has no attribute 'model' and can't work out why. I instantiate DateChoiceForm() in views.py: form = DateChoiceForm( trips=trips, initial={ "trip_date": default_selected, "num_passengers": passenger_total, }, ) In forms.py I initialise it with the queryset: class DateChoiceForm(forms.Form): num_passengers = forms.IntegerField(widget=forms.HiddenInput()) trip = forms.ModelChoiceField( queryset=None, widget=forms.RadioSelect() ) def __init__(self, *args, **kwargs): trip_dates = kwargs.pop('trips', None) passengers = kwargs.pop('passengers', None) super(DateChoiceForm, self).__init__(*args, **kwargs) self.fields['trip'].queryset = trip_dates The form renders as expected in the template as the correct choices from the queryset are shown. However when I click to submit the form, I get the error following this in the log: except (ValueError, TypeError, self.queryset.model.DoesNotExist) Running validation shows some issue around the form.is_valid() function. But checking local vars shows variables have data: Any help understanding this would be appreciated -
Issue with Django startproject
I'm new to django and python. I am currently trying to create a new django project by doing "django-admin startproject project" in the terminal, which works, but the only file that is in the folder is manage.py. I am not sure why the other files such as settings.py, urls.py, etc. are not located there -
why there is No exception message supplied
I am doing everything as in guide why does it show an error:No exception message supplied except stripe.CardError as e: message.info(request, "Your card has been declined.") -
Django different backends for different devices
I've stumbled upon a weird and non-standard problem. My Django app is separated into two parts standard web Django template rendering part where users are authenticated using username and password and then by sessions. mobile app + REST API part where users are Authenticated using username, password and unique installation identifier stored in app keychain and then JWT's This is a little bit tricky as don't want mobile "smart" users to authenticate using web browser without the aforementioned mobile identifier (even if they will get only json responses instead of full website - I don't want that). So the question narrows to: How to authenticate User using only username and password while he's on web app and at the same time not authenticate this user when he calls the api JWT obtain token enpoint with only username and password (wihout giving installation identifier) I have additional already backend written but I don't want to expose my app to unauthorized access Thanks in advance for any help -
Raising Errors in Django
I am working on a website that translates dna chains into proteins. Here's the thing, a dna chain must be divisible by 3. So if the user inputs a value which is not divisible by three, it raises an arithmetic error. Here's the code: if len(phrase) % 3: raise ArithmeticError("DNA chain must be divisible by 3") return protein The code works because it raises the error. However, I would want the error to be raised in this page in the template where I input the chain. How can I do that. Here's the html code for the template in case you need to make changes. {% extends "base.html"%} {% block content %} <form action="{% url 'translated' %}" method="post">{% csrf_token %} <div class="form-group"> <h2 class = "display-3">TRANSLATE YOUR DNA CHAIN</h2> <br> <br> <textarea class="form-control" name= 'text' placeholder="Enter your DNA chain here" style= "font-size: 24px;" rows="1"></textarea> <br> <button type='Submit' class= "btn btn-primary btn-lg btn-block">Translate</button> <br> <br> <p>There are four types of nitrogenous bases:</p> <p>- Adenine (A)</p> <p>- Thymine (T)</p> <p>- Cytosine (C)</p> <p>- Guanine (G)</p> </div> </form> {% endblock content %} -
Django POST Request: getting data
I'm building a REST API with django, and using this curl command to send a POST request to one of my functions: curl -X POST -H "Content-Type: application/json" -d @/Users/name/desktop/test.json http://127.0.0.1:8000 -u username The localhost address takes in the POST request, process the json file provided with the -d flag and then returns a JSONResponse. I was wondering how, in my django function, I would get the username and password entered into this request? Let's say my function is named ```python def train(request): -
How To Get Logged In User From Token IN Django Rest Framework Backend With Angular Frontend
I am a beginner in frontend development so pardon me if this is something very basic. I have a Django Rest Framework backend in which when creating a lead object it automatically gets the user. I am authenticated using basic token authentication and have an Angular based UI. However, when I send the request it still shows Anonymous User despite the token appearing in my browser's local storage. I tried following a few tutorials however am unable to solve it. Here's the angular code: base_url = "http://127.0.0.1:8000/leads/" create_url = this.base_url + 'create/' httpHeaders = new HttpHeaders({ 'Content-type': 'application/json' }); constructor(private http: HttpClient) {}; postLead(leadData): Observable<any> { return this.http.post(this.create_url, leadData, {headers: this.httpHeaders}); } } Here is what I use for authentication export class TokenInterceptorService implements HttpInterceptor{ constructor(private injector: Injector) { } intercept(request: HttpRequest<any>, next: HttpHandler){ let authService = this.injector.get(AuthService) let tokenizedReq = request.clone( { setHeaders: { Authorization: `Bearer ${authService.getToken()}` } } ) return next.handle(tokenizedReq); } } Obviously in the backend I'm trying to retrieve the user using: user = self.request.user -
No module named 'config.settings' while deploying Django project on Heroku
I'm getting the error ModuleNotFoundError: No module named 'config.settings' while deploying a Django app on Heroku. I'm deploying it from Github. Been battling for days with this problem but can't fix this. The build is successful and so is the deployment but for some reason when navigating to the site address there is an application error. But It's running fine on the local server. Github code here: https://github.com/niloy-biswas/niloy-biswas.github.io Folder Structure: Root folder - portfolio * static * templates * __init.py__ * asgi.py * settings.py * urls.py * views.py * wsgi.py - manage.py - Procfile - requirements.txt wsgi.py - import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'portfolio.settings') application = get_wsgi_application() Procfile - web: gunicorn portfolio.wsgi --log-file - Heroku log file - 2020-11-29T20:26:25.388554+00:00 heroku[web.1]: Starting process with command `gunicorn portfolio.wsgi --log-file -` 2020-11-29T20:26:28.090181+00:00 app[web.1]: [2020-11-29 20:26:28 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-11-29T20:26:28.091131+00:00 app[web.1]: [2020-11-29 20:26:28 +0000] [4] [INFO] Listening at: http://0.0.0.0:45706 (4) 2020-11-29T20:26:28.091342+00:00 app[web.1]: [2020-11-29 20:26:28 +0000] [4] [INFO] Using worker: sync 2020-11-29T20:26:28.096462+00:00 app[web.1]: [2020-11-29 20:26:28 +0000] [10] [INFO] Booting worker with pid: 10 2020-11-29T20:26:28.157113+00:00 app[web.1]: [2020-11-29 20:26:28 +0000] [11] [INFO] Booting worker with pid: 11 2020-11-29T20:26:28.362776+00:00 app[web.1]: [2020-11-29 20:26:28 +0000] [10] [ERROR] Exception in worker process 2020-11-29T20:26:28.362807+00:00 app[web.1]: Traceback (most … -
Django + Nginx cannot find staticfiles but works on dev with "Runserver"
I have a server on Ubuntu + Nginx running on Digital ocean that almost works, but it can't find /static/js/project.js and /static/css/project.css. But they exist! The problem is that I have these directories: /home/user/project/staticfiles #and /home/user/project/app/static But when I look at the nginx log, I'm seeing: /home/user/project/static/js/project.js So either it should be looking in: /home/user/project/app/static/js/project.js or /home/user/project/staticfiles/js/project.js I'm using the base.py, local.py, test.py and production.py setup where the latter 3 derive from base.py. So all of them are pulling the same static paths: STATIC_ROOT = str(ROOT_DIR / "staticfiles") STATIC_URL = "/static/" STATICFILES_DIRS = [str(APPS_DIR / "static")] STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] On runserver, it is pulling it from: /home/user/project/app/static/js/project.js The only thing I can think of is that I am using whitenoise (I used the Cookieuctter to set it up) but I've tried turning it off as well as turning off the caching. (I've had the following two lines activate separately but not at the same time): STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" #and STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' As well as turning it off and that doesn't seem to help. I run manage.py collect static with the production settings on the production server every time so I'm not accidentally using the local settings. … -
Django CSRF Malfunction after using HTTPS
I know that this problem is occurs many times here. But none of them has working for me right now. I've been struggling in this error since I change the protocol of my app to https using apache2 and LetsEncrypt. I try the configurations in settings but it doesn't solve the problem. # settings.py CSRF_COOKIE_DOMAIN = ".myapp.ml" CSRF_COOKIE_SECURE = True CSRF_USE_SESSIONS = True SESSION_COOKIE_SECURE = True Ofcourse in every forms with POST method required that I have has {% csrf_token %} in there. It also shows in request data. This errors occurs in Log in and Sign Up forms. Inside the app after I add csrf_exempt in login and signup, I use DRF and when I make requests like POST, DELETE, PUT etc... It only shows the error {"detail":"CSRF Failed: Referer checking failed - no Referer."} Here is my apache2 configuration file: <IfModule mod_ssl.c> <VirtualHost *:443> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the …