Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
updating django python code to latest lts
I have been trying to update my django python code from django version 1.9 and python version 2.7 to the django version 3.2.8 and the python3.8. but while updating I'm stuck with the below error (SA_python3.9_env) E:\SA_py_3.9\sa>python manage.py runserver sys.argv:- ['manage.py', 'runserver'] sys.argv:- ['manage.py', 'runserver'] Watching for file changes with StatReloader Performing system checks... Traceback (most recent call last): File "E:\SA_py_3.9\SA_python3.9_env\lib\site-packages\django\template\utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Exception in thread Traceback (most recent call last): django-main-thread File "E:\SA_py_3.9\SA_python3.9_env\lib\site-packages\django\template\backends\django.py", line 121, in get_package_libraries : Traceback (most recent call last): module = import_module(entry[1]) File "E:\SA_py_3.9\SA_python3.9_env\lib\site-packages\django\template\utils.py", line 66, in __getitem__ File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) return self._engines[alias] File "<frozen importlib._bootstrap>", line 1030, in _gcd_import KeyError File "<frozen importlib._bootstrap>", line 1007, in _find_and_load : 'django' During handling of the above exception, another exception occurred: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked Traceback (most recent call last): File "E:\SA_py_3.9\SA_python3.9_env\lib\site-packages\django\template\backends\django.py", line 121, in get_package_libraries File "<frozen importlib._bootstrap>", line 680, in _load_unlocked module = import_module(entry[1]) File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed return _bootstrap._gcd_import(name[level:], package, level) File "<frozen … -
Nav Bar Toggle Button - Won't dropdown
I have a Django homepage that has a Bootstrap navbar, and when resized I have it show a toggle button. My issue is that when this toggle button comes into effect, I cannot dropdown the navbar items? I am unsure how I can fix this. Snip of what these look like (for an idea): https://imgur.com/a/PyiUs38 Pastebin: https://pastebin.com/QqPiyVxf <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <!--LOGO--> <a class="navbar-brand" style="pointer-events: none"> <!-- Unclickable --> <img src="http://www.w3.org/2000/svg" width="30" height="30" alt=""> </a> <!--MAIN NAV--> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse justify-content-md-center" id="navbarTogglerDemo02"> {% with request.resolver_match.url_name as url_name %} <ul class="navbar-nav"> <li class="nav-item {% if url_name == 'home' %}active{% endif %}"> <a class="nav-link" href="{% url 'home' %}">Home</a> </li> <li class="nav-item {% if url_name == 'about' %}active{% endif %}"> <a class="nav-link" href="{% url 'about' %}">About</a> </li> <li class="nav-item {% if url_name == 'projects' %}active{% endif %}"> <a class="nav-link" href="{% url 'projects' %}">Projects</a> </li> <li class="nav-item {% if url_name == 'uses' %}active{% endif %}"> <a class="nav-link" href="{% url 'uses' %}">Uses</a> </li> <li class="nav-item {% if url_name == 'contact' %}active{% endif %}"> <a class="nav-link" href="{% url 'contact' %}">Contact</a> </li> </ul> {% endwith %} </div> <!--SOCIALS--> <!-- Twitter --> <a class="btn btn-primary" … -
django model form set initial
I have a list of comments stored in database, schema: models.py class Comment(models.Model): content = models.CharField(max_length=255) query set In [1]: from comments.models import Comment In [2]: Comment.objects.all() Out[2]: <QuerySet [<Comment: Comment object (1)>, <Comment: Comment object (2)>]> In [3]: Comment.objects.all()[0] Out[3]: <Comment: Comment object (1)> In [4]: Comment.objects.all()[0].content Out[4]: 'first comment' I want to use a CommentListUpdateView, to allow user to update many comments at the same page individually (each comment has a form and a update button) therefore, I in views.py # Create your views here. def commentListUpdateView(request): forms = [] for comment in Comment.objects.all(): form = CommentUpdateForm(request.POST, instance=comment, initial={'content': comment.content}) # form = CommentUpdateForm(request.POST, instance=comment) # form.fields['content'].initial = comment.content forms.append(form) return render(request, 'comments/comment_list_update.html', {'forms': forms}) forms.py class CommentUpdateForm(forms.ModelForm): class Meta: model = Comment fields = ['content'] template {% for form in forms %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button type="submit">Update</button> </form> {% endfor %} However, I can always get the value from backend, but the value is always missing in the frontend. the html I got as result: <form method="POST" enctype="multipart/form-data"> <input type="hidden" name="csrfmiddlewaretoken" value="zQtpR8P4K8A1a7i1ELI9kJg1YRo0Y7d02hpSWqY5VPX2j48x1j4UHubWmosaGk4Q"> <label for="id_content">Content:</label> <ul class="errorlist"> <li>This field is required.</li> </ul><input type="text" name="content" maxlength="255" required="" id="id_content"> <button type="submit">Update</button> </form> I have … -
How to get Google-Calendar events using access token
I have built a django app, which it includes google Oauth2.0 login. I want to get google calendar events of every users when they login with Oauth2.0 and I wrote the following code. I saved the access token into UserAuth table and fetched it, then used it to get google calendar. def get_events_server(request): user = User.objects.get(username=request.user) creds = UserAuth.objects.get(user=user).google_id_token credentials = AccessTokenCredentials(creds, "") http = httplib2.Http() http = credentials.authorize(http) service = build('calendar', 'v3', http=http) return service When I run the code, the following error has happened. HttpError at /calendar/ <HttpError 403 when requesting https://www.googleapis.com/calendar/v3/calendars/primary/events?timeMin=2021-10-28T04%3A33%3A08.956703Z&timeMax=2021-11-04T04%3A33%3A08.956712Z&singleEvents=true&timeZone=GMT%2B9%3A00&orderBy=startTime&alt=json returned "Request had insufficient authentication scopes.". Details: "[{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficientPermissions'}]"> Is there a solution to skip this issue? -
Making use of the token generated upon log in
I have coded the API to work with my web and also generate token upon login/register from the Postman request by using knox for the token. Now I want to make use of this token that is linked to the account that is logged in to get the username so I can know which account who make the request. But I am not sure on how to use this token. Can anyone provide me with some advise on how to do this as I am quite new on this. Just learned how to generated this token yesterday. Thanks ! views.py @api_view(['POST']) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) def create_job(request): job = Job() jobserializer = JobSerializers(job, data = request.data) if jobserializer.is_valid(): operation = jobserializer.save() data = {} if operation: data["Success"] = "Successfully created" return Response(data) return Response(jobserializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class JobSerializers(serializers.ModelSerializer): class Meta: model = Job fields = ['combinedparameters', 'servicedate'] models.py class Job(models.Model): owner = models.CharField(max_length = 150) datetime = models.DateTimeField(default=timezone.now) combinedparameters = models.CharField(max_length = 1000) servicedate = models.CharField(max_length=10) def __str__(self): return self.servicedate In the web browser, I get the user by request.user but I am not sure on how to make use of this token to get the user in API. -
Django / Models / Admin / Problem with the foreign key : __str__ returned non-string (type tuple)
I have already tried multiple solutions find on other topics but nothing works. I have a problem the foreign key in Django Admin. Impossible to see a records or add a new record. I have a table convertion_factor with no NULL values. see postgreSQL config This is my model : class convertion_factor(models.Model): foodID = models.ForeignKey('food_name', on_delete=models.CASCADE) measureID = models.ForeignKey('measure_name', on_delete=models.CASCADE) conversionFactorValue = models.FloatField() convFactorDateOfEntry = models.DateField(auto_now=False, auto_now_add=False) In order to views the data in Django Admin, you have to add def __str__(self): to the model. Ok let's do that : class convertion_factor(models.Model): foodID = models.ForeignKey('food_name', on_delete=models.CASCADE) measureID = models.ForeignKey('measure_name', on_delete=models.CASCADE) conversionFactorValue = models.FloatField() convFactorDateOfEntry = models.DateField(auto_now=False, auto_now_add=False) def __str__(self): return self.conversionFactorValue Now when I go to Django Admin and I click on the model convertion_factor I can see the table just fine but when I try to click on a record to edit it, I have this error : TypeError at /admin/kalo/convertion_factor/19505/change/ Exception Type: TypeError at /admin/kalo/convertion_factor/19505/change/ Exception Value: __str__ returned non-string (type float) I have the impression this is an error due to the foreign key because with my others models without a foreign key, everythings work just fine. In the function def __str__(self): I have tried : return … -
XAMPP Error: Apache Shutdown unexpectedly error
I am first time using XAMPP Apache, when I click start, Apache shut down unexpectedly, and when I click on the error logs, it gives me all the log errors as shown in the picture below which I am not sure what to do, can anyone help me? Log error: Apache XAMPP Stop -
New users can't login sessions in Django
I have created a user registration form, when I try to register new user it brings back the same form while I redirected it to home page. And I try to log in, I get None, so it displays in the template 'Wrong username or password.'. However, the super user that I created through the command line after I first installed django, is able to login with no problem. views.py from .models import * from .forms import OrderForm, CustomerForm, CreateUserForm from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required def registerPage(request): if request.user.is_authenticated: return redirect('home') else: if request.method == 'POST': form_value = CreateUserForm(request.POST) if form_value.is_valid(): form_value.save() user = form_value.cleaned_data.get('username') messages.success(request, 'Account was create for {}'.format(user)) return redirect('login') form_value = CreateUserForm context = {'form_key':form_value} return render(request, 'accounts/register.html', context) def loginPage(request): if request.user.is_authenticated: return redirect('home') else: if request.method == 'POST': username_value=request.POST.get('username') password_value=request.POST.get('password') user = authenticate(request, username=username_value, password=password_value) if user is not None: login(request, user) return redirect('home') else: messages.info(request, 'Username or Password is incorrect') context = {} return render(request, 'accounts/login.html', context) forms.py from django.db import models from django.forms import ModelForm, fields from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User class … -
converting input value into negatives before saving
Please I have the model and the view below but I want a situation in which any value entered in the quantity field would be saved as a negative number in my database. views.py def post(self, request): receiveform = ReceiveForm(request.POST or None) stockform = StockForm(request.POST or None) if request.method == 'POST': if receiveform.is_valid() and stockform.is_valid(): receiveform.save() stockform.save() messages.success(request,('Data save succefully')) return redirect('dashboard') else: print(receiveform.errors) receiveform = ReceiveForm(request.POST or None) context = { 'receiveform':receiveform, 'stockform':stockform, } return render(request, 'storesapp/receives.html', context) models.py class Receives(models.Model): date = models.DateField(default=now) category = models.ForeignKey(Category, on_delete=models.CASCADE) quantity = models.IntegerField(default='0', blank=True, null=True) -
Error running WSGI application, within pythonanywhere
Good day to all, I was having some issues trying to host my django webapp within pythonanywhere and I keep getting the following errors within the server. Sorry in advance I'm a beginner when it comes to programming WSGI File: # +++++++++++ DJANGO +++++++++++ # To use your own Django app use code like this: import os import sys # assuming your Django settings file is at '/home/myusername/mysite/mysite/settings.py' path = '/home/HumBen/AMC_Inventory/venv/src/src/settings.py' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'src.settings' ## Uncomment the lines below depending on your Django version ###### then, for Django >=1.5: from django.core.wsgi import get_wsgi_application stockmgmt = get_wsgi_application() ###### or, for older Django <=1.4 #import django.core.handlers.wsgi #application = django.core.handlers.wsgi.WSGIHandler() Server error: 2021-10-27 22:59:31,228: Error running WSGI application 2021-10-27 22:59:31,233: ModuleNotFoundError: No module named 'src' 2021-10-27 22:59:31,233: File "/var/www/humben_pythonanywhere_com_wsgi.py", line 16, in <module> 2021-10-27 22:59:31,233: application = get_wsgi_application() 2021-10-27 22:59:31,233: 2021-10-27 22:59:31,233: File "/home/HumBen/AMC_Inventory/venv/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-10-27 22:59:31,233: django.setup(set_prefix=False) 2021-10-27 22:59:31,233: 2021-10-27 22:59:31,233: File "/home/HumBen/AMC_Inventory/venv/lib/python3.9/site-packages/django/__init__.py", line 19, in setup 2021-10-27 22:59:31,234: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2021-10-27 22:59:31,234: 2021-10-27 22:59:31,234: File "/home/HumBen/AMC_Inventory/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ 2021-10-27 22:59:31,234: self._setup(name) 2021-10-27 22:59:31,234: 2021-10-27 22:59:31,234: File "/home/HumBen/AMC_Inventory/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup 2021-10-27 22:59:31,235: self._wrapped = Settings(settings_module) 2021-10-27 22:59:31,235: 2021-10-27 … -
How to change Django model from class using boolean
I have the location class in my models.py class Location(models.Model): ... orderplaced = models.DateTimeField(auto_now_add=True, blank=True) ordersent = models.BooleanField(default=False) order_sent_time = models.DateTimeField(auto_now=True, blank=True) How do I make it so that the boolean ordersent controls the if order_sent_time is blank or not I tried using if ordersent: order_sent_time = models.DateTimeField(auto_now=True, blank=True) else: order_sent_time = models.DateTimeField(null=True, blank=True) How can I get the boolean to affect order_sent_time? -
Connect Heroku deployed MySQL database to Django
I want to make connection with my MySQL database which is deployed on Heroku. However, after setting parameters for database I am getting this error: django.db.utils.OperationalError: (1044, "Access denied for user '*mu username*'@'%' to database '*name of my database*'") In my settings.py : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '*name of my database*', 'USER': '*my username*', 'PASSWORD': '*my password*', 'HOST': 'eu-cdbr-west-01.cleardb.com', 'PORT': '3306', } } -
Django - Communicate with persistent process
We have a legacy C library that can be used to communicate with a custom local server, and we have written command-line and GUIs tools with it. Now we would like to create a web interface using the library so users can just use the tools via a web browser instead of needing to install them locally. I have experience with Django, and this seems mostly plausible. However, there is one big hang up. In order for the C library to communicate with the local server, it must open up a per-instance connection for each user before transmitting data (and then closing the connection when the session is over). And to keep track of this session, it returns a void pointer that must be used for all library calls using this connection. And since it's a C void pointer, it's a pointer to a particular memory location in the process, and the session can only be used in the process it was created. This causes problems with Django because (as far as I know) I can't guarantee each request in different Django views for a session will be handled within the same process. One potential method for handling the problem … -
Why request,POST.get(var) is returning "NONE" value for radio input?
This is my code: a_selected = request.POST.get(q.text) it is returning "NONE" value I am using Django 3.0 -
how to store this data into a django session
so i have this code that stores favorite properties in to a database, how can i make that stores the properties into a session instead of using the database the json data of this view comes from a javascript that send data to the view when a (add)button is clicked views.py def updateFavoritos(request): response_json = request.body inmuebleId = None if response_json: data = json.loads(request.body) inmuebleId = data['id'] inmueble = Inmueble.objects.get(id=int(inmuebleId)) favorites, created = Favorito.objects.get_or_create(inmueble=inmueble) print('respuesta') favs = Favorito.objects.all() contexto = { 'id':inmuebleId, 'favoritos':favs, } return render(request, 'favorites.html', contexto) html code that show the favorite properties {% for favorito in favoritos %} <div class="col-lg-6 col-xl-4"> <div class="feat_property"> <div class="thumb"> <img class="img-whp" src="{{ favorito.inmueble.imagen.url }}" alt="fl1.jpg"> <div class="thmb_cntnt2"> <ul class="listing_gallery mb0"> <li class="list-inline-item"><a class="text-white" href="#"><span class="flaticon-photo-camera mr5"></span> 22</a></li> <li class="list-inline-item"><a class="text-white" href="#"><span class="flaticon-play-button mr5"></span> 3</a></li> </ul> </div> </div> <div class="details"> <div class="tc_content"> <h4><a href="page-listing-single-v8.html">{{ favorito.inmueble.nombre }}</a></h4> <p>251 SW 6th Ln Florida City, FL</p> <ul class="prop_details mb0"> <li class="list-inline-item"><a href="#"><span class="flaticon-bed"></span> <br>4 Cuartos</a></li> <li class="list-inline-item"><a href="#"><span class="flaticon-bath"></span> <br>5 Baños</a></li> <li class="list-inline-item"><a href="#"><span class="flaticon-car"></span> <br>1 Garage</a></li> <li class="list-inline-item"><a href="#"><span class="flaticon-ruler"></span> <br>1200 M2</a></li> </ul> </div> <div class="fp_footer"> <ul class="fp_meta float-left mb0"> <li class="list-inline-item"> <a href="#"> <small><del class="body-color">$2,800/mo</del></small><br> <span class="heading-color fw600">$2,300/mo</span> </a> </li> </ul> <ul class="fp_meta … -
Best way to set a referral code in django across all URLs
I wonder what's the best way to set a session id across all URLs without changing URL patterns and views. Is this a good idea to create one URL located at the top in urls.py, set a session id in the view and redirect to the url without referral code? Let me give you an example: Setting a top-level url to catch any link with referral code urlpatterns = [ re_path(r'^(.*)/ref/<str:ref_code>/$', views.set_ref_code), path('', views.index, name='index'), path('news/', views.news_list, name='news_list'), Set referral code in the session and redirect to url without referral code def set_ref_code(request, ref_code): url = request.path redirect(url) I am not sure that this example works. This is only an example to explain my idea. Maybe there is a better solution to set referral id across all the web application? -
Django Rosetta TypeError at /en/rosetta/files/project/
I want to add rosetta to my project.I installed version 0.9.7 (tried 0.9.5) and added to INSTALLED_APPS 'rosetta'. I have error: TypeError at /en/rosetta/files/project/ expected str, bytes or os.PathLike object, not NoneType My urls.py from django.conf import settings from django.conf.urls.i18n import i18n_patterns from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = i18n_patterns( path('admin/', admin.site.urls), path('cart/', include('cart.urls', namespace='cart')), path('order/', include('order.urls', namespace='order')), path('social-auth/', include('social_django.urls', namespace='social')), path('rosetta/', include('rosetta.urls')), path('', include('shop.urls', namespace='shop')), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL) Python == 3.8.10 Django == 3.2.7 -
ACCOUNT_USERNAME_VALIDATORS not throwing error, or working as validation
I have a very weird bug, When I try to set the setting ACCOUNT_USERNAME_VALIDATORS in base.py (used for my dev,staging, and production environments) it doesn't actually do it. It's not even throwing an error if I incorrectly set the value. base.py This is for my dev environment ACCOUNT_USERNAME_VALIDATORS = ('accounts.validators.custom_username_validators') Validators.py I created a simple validation to see if it works with another validator provided by django. from django.contrib.auth.validators import ASCIIUsernameValidator custom_username_validators = [ASCIIUsernameValidator()] This is to show that the way I reference the validators code is correct. Tree . ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── Pipfile ├── Pipfile.lock ├── Procfile ├── README.md ├── accounts │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── tests.py │ ├── urls.py │ ├── validators.py │ └── views.py ├── config │ ├── __init__.py │ ├── __pycache__ │ ├── asgi.py │ ├── settings │ ├── settings1.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── docker-compose.yml ├── manage.py ├── pages │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── context_processors.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── posts │ … -
Enforcing permissions through a related model in Django Rest Framework
I'm working on building out permissions for an API built with Django REST Framework. Let's say I have the following models: from django.db import models class Study(models.Model): pass class Result(models.Model): study = models.ForeignKey(Study) value = models.IntegerField(null=False) I have basic serializers and views for both of these models. I'll be using per-object permissions to grant users access to one or more studies. I want users to only be able to view Results for a Study which they have permissions to. There are two ways I can think of to do this, and neither seem ideal: Keep per-object permissions on Results in sync with Study. This is just a non-starter since we want Study to always be the source of truth. Write a custom permissions class which checks permissions on the related Study when a user tries to access a Result. This actually isn't too bad, but I couldn't find examples of others doing it this way and it got me thinking that I may be thinking about this fundamentally wrong. Are there existing solutions for this out there? Or is a custom permissions class the way to go? If so, do you have examples of others who've implemented this way? -
Django filter by many-to-many field doesn't work
There is a model of Article and it has many-to-many categories field. I want to filter it by that field but it doesn't work as i expected. For example: MyModel.objects.filter(categories__id__in = [0, 1, 2]) it gets model with categories 0 and 1 even if it hasn't category with id 2. i tried something like this: MyModel.objects.filter(Q(categories__id = 0) & Q(categories__id = 1) & Q(categories__id = 2)) but it even doesn't work. it doesn't even gets model if it has all of this categories. By the way, i don't want to use more than 1 filter method So, is there any solution for me? Thanks. -
Rules in views for custom user types
in my app I created two types of users by one-to-one relations. class Teacher(models.Model): user = models.OneToOneField(AuthUser, primary_key=True, on_delete=models.CASCADE) ... class Student(models.Model): user = models.OneToOneField(AuthUser, primary_key=True, on_delete=models.CASCADE) ... in views now I'm checking user role as follows: student = Student.objects.get(pk=request.user.id) teacher = Teacher.objects.get(pk=request.user.id) but it throws an exception, which better way should I use it? -
Deploy django app with gunicorn and nginx. ERROR supervisor: child process was not spawned
I'm trying to deploy my django app in a digital ocean droplet. I'm using nginx and gunicorn following this tutorial This is how gunicorn_start looks like #!/bin/sh NAME="PlantArte" DIR=/home/paulauzca/PlantArte USER=paulauzca GROUP=paulauzca WORKERS=3 BIND=unix:/home/paulauzca/run/gunicorn.sock DJANGO_SETTINGS_MODULE=project.settings DJANGO_WSGI_MODULE=project.wsgi LOG_LEVEL=error cd $DIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME\ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- This is PlantArte.conf file #!/bin/sh [program:PlantArte] command=/home/paulauzca/bin/gunicorn_start --daemon user=paulauzca startsecs=0 autostart=true autorestart=true redirect_stderr=true environment=PYTHONPATH=$PYTHONPATH:/home/paulauzca/bin/python stdout_logfile=/home/paulauzca/logs/gunicorn-error.log Following the tutorial I run sudo supervisorctl status PlantArte And I always get PlantArte RUNNING pid 3566, uptime 0:00:00 With 0 second runtime. Which is weird. If I go into gunicorn-error.log I get supervisor: couldn't exec /home/paulauzca/bin/gunicorn_start: EACCES supervisor: child process was not spawned I've tried the "solutions" to this problem I've found on the internet but there is not much information about this... -
Django and SuspiciousFileOperation:Detected path traversal attempt
I find myself in an odd situation only when deployed (debug == false): My model throws a path traversal attempt exception. I want to create a directory for every file uploaded and save the file within the directory (some.zip) used in example. In my dev environment I have no problems and everything works just fine. models.py: class Template(models.Model): def get_folder(self, filename): filename_PATH = Path(filename) template_dir = filename_PATH.stem return Path(settings.TEMPLATES_FOLDER).joinpath(template_dir, filename) name = models.CharField("template", max_length=32, unique=True) file = models.FileField("templatefile", upload_to=get_folder, null=True, max_length=260, storage=OverwriteStorage()) class OverwriteStorage(FileSystemStorage): #this is actually above def get_available_name(self, name, max_length=None): self.delete(name) return name forms.py: class TemplateAdminForm(forms.ModelForm): def __init__(self,*args,**kwargs): super().__init__(*args, **kwargs) class Meta: model = Template fields = ["name", "file", ] def clean(self): cleaned_data = super().clean() upFile = Path(str(cleaned_data["file"])) if upFile.suffix == ".zip": path = self.instance.get_folder(cleaned_data["name"]) logging.error(f"{path}") unpack_zip(path) ## works! the directory is created/filled else: raise forms.ValidationError("unknown file type ...") logging.error("DONE!") # I see this output return cleaned_data ## signal to see when the error might be happening: @receiver(post_save, sender = Template) def testing(sender, **kwargs): logging.error("we never get here") settings.py: TEMPLATES_FOLDER = PATH(MEDIA_ROOT).joinpath("TEMPLATES") but: ERROR:django.security.SuspiciousFileOperation:Detected path traversal attempt in '/opt/project/media_root/TEMPLATES/some/some' WARNING:django.request:Bad Request: /admin/appName/template/add/ -
How to get categories in django
I have a django programme of diffrent categories of books and I want to get the books in a particular category. I can do this using django, but when using rest framework I get stuck at various points.I have the following blocks of code: models.py class Category (models.Model): name = models.CharField(max_length=20, db_index=True) slug = models.SlugField(max_length=40, unique=True) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name serializers.py class categories_serializer(serializers.ModelSerializer): class Meta: model = Category fields = "__all__" views.py class product_CategoryView(generics.ListCreateAPIView): serializer_class = categories_serializer def get_queryset(self): return { "categories": Category.objects.all() } ================ class Book(models.Model): categories = models.ManyToManyField(Category) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="book_owner") name = models.CharField(max_length=150) slug = models.SlugField(max_length=255, blank=True, null=True) product_class = models.CharField(max_length=50) image = models.ImageField(upload_to="images/books/") .... Whenever I try to access the category using path(book/category', views.book_CategoryView.as_view(), name="book_category"),, I encounter the following error: AttributeError at /book/category Got AttributeError when attempting to get a value for field `name` on serializer `categories_serializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'name'. I don't understand why I am getting the error. How do I go about this? -
http.client - ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
def checkUrl(url): p = urlparse(url) conn = http.client.HTTPConnection(p.netloc) conn.request('HEAD', p.path) resp = conn.getresponse() return resp.status < 400 all_urls = URL.objects.all() for u in all_urls: my_url = u.url result = checkUrl(my_url) print(result) There are 3090 urls in model "URL". It works but after object 2895, the error occurs: ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host How to fix it?