Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku: python version problems
I am trying to deploy a Django app on Heroku, but I am having compatibility issues with the requirements.txt file, it specifies "python-3.11.1". According to Heroku's documentation, Heroku stack 22 supports Python 3.11.1. But each time I try to deploy using the Heroku CLI, I get an error message. -----> Building on the Heroku-22 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt Traceback (most recent call last): File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> r = f.read().strip() File "/usr/lib/python3.10/codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 9: warning: command substitution: ignored null byte in input ! Requested runtime '��python-3.11.1 ! For supported versions, see: https://devcenter.heroku.com/articles/python-support ! Push rejected, failed to compile Python app. ! Push failed I tried git push heroku master I have followed the buildpack checking tutorial in the documentation: heroku buildpacks heroku buildpacks:clear heroku buildpacks:add heroku/python -
My Paginator not working at the last page button
when click next and previous button is working, but the last page not working model.py class VenueForm(ModelForm): class Meta: model = Venue fields = ( 'name', 'address', 'zip_code', 'phone', 'web', 'email_address' ) labels = { 'name': '', 'address': '', 'zip_code': '', 'phone': '', 'web': '', 'email_address': '', } widgets = { 'name': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Venue Name'}), 'address': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Address'}), 'zip_code': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Zip Code'}), 'phone': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Phone'}), 'web': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Web'}), 'email_address': forms.EmailInput( attrs={'class': 'form-control', 'placeholder': 'Email'}), } view.py from .models import Event, Venue from django.core.paginator import Paginator def list_venues(request): venue_list = Venue.objects.all() p = Paginator(Venue.objects.all(), 3) page = request.GET.get('page') venues = p.get_page(page) nums = "a" * venues.paginator.num_pages return render(request, 'events/venue.html', { 'venue_list': venue_list, 'venues': venues, 'nums': nums}) events/venue.html <nav aria-label="Page navigation example"> <ul class="pagination justify-content-center"> {% if venues.has_previous %} <li class="page-item"> <a class="page-link" href="?page=1">&laquo; First</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ venues.previous_page_number }}">Previous</a> </li> {% endif %} {% for i in nums %} <li class="page-item"> <a class="page-link" href="?page={{ forloop.counter }}">{{ forloop.counter }} </a> </li> {% endfor %} {% if venues.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ venues.next_page_number }}">Next</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ venues.paginator.num_pages ))">Last &raquo;</a> … -
Force login not working with fixtures (Django TestCase)
I'm populating my test db via a fixture, and everything loads fine. However, I'm unable to get either login or force_login to work. User is also in the fixture. When I try to test the first view, it redirects to the login page. class TestUnauthUser(TestCase): fixtures = ['project.json'] @classmethod def setUpTestData(cls): cls.client = Client() # Get User and Login cls.unauth_user = User.objects.get(username='unauth_user') print(cls.unauth_user.pk) #cls.login = cls.client.login(username=cls.unauth_user.username, password=cls.unauth_user.password) cls.client.force_login(cls.unauth_user) # Get Project cls.project = Project.objects.get(slug='test-project') cls.slug_dict = {'slug': cls.project.slug} # Get Task cls.task = Task.objects.get(slug='test-task') def test_login(self): self.assertTrue(self.unauth_user.login) def test_project_view(self): # Project Main response = self.client.get(reverse('customerportal:project', kwargs=self.slug_dict)) self.assertEqual(response.status_code, 403) I'm able to verify that I have the correct user object with: print(cls.unauth_user.pk). So the User exists and is being obtained. But, it's still not logging-in successfully. -
Is there a way to do {% url 'blog' blog[i].slug %} in Django?
I want to make this type of loops: {% for i in length %} where lenth = range(len(blogs)) in views.py. And then into that loop I want to do: <a href="{% url 'single_blog' blogs[i].slug %}"> blogs go from views.py too: blogs = Blog.objects.all() But it shows an error, it says it can't use [i] in this construction. Please let me know, how can I use blogs[i] in Django HTML? Thanks. -
Preserve and display Django form inputs on POST submission
--PROBLEM-- I have created a basic calculator using Django. The app takes some basic form inputs before executing some calculations and returning the outcomes to the user, however I want the user's inputs to remain visible in the form on submission. At present the followin experience occurs. User enters values into form and submits using 'Calculate' button. Results are returned as expected but form and values are no longer present. User can press 'Calculate' button to return to start of process and blank form. --DESIRED OUTCOME-- --CODE-- forms.py from django import forms class InvestmentForm(forms.Form): starting_amount = forms.FloatField() number_of_years = forms.FloatField() return_rate = forms.FloatField() annual_additional_contribution = forms.FloatField() views.py from django.shortcuts import render from django.views import View from .forms import InvestmentForm class Index(View): def get(self, request): form = InvestmentForm() return render(request, 'loancalculator/index.html', {'form': form}) def post(self, request): form = InvestmentForm(request.POST) if form.is_valid(): total_result = form.cleaned_data['starting_amount'] total_interest = 0 yearly_results = {} for i in range(1, int(form.cleaned_data['number_of_years'] +1)): yearly_results[i] = {} # CALCULATE THE INTEREST interest = total_result * (form.cleaned_data['return_rate'] / 100) total_result += interest total_interest += interest # ADDITIONAL CONTRIBUTION total_result += form.cleaned_data['annual_additional_contribution'] # SET YEARLY RESULTS yearly_results[i]['interest'] = round(total_interest, 2) yearly_results[i]['total'] = round(total_result,2) # CREATE CONTEXT context = { 'total_result': round(total_result,2), … -
With a Django QuerySet, how to get a list of the included columns?
In the application context, we have a dynamic QuerySet that may return variable number of columns, e.g. date_of_birth in type Date, and/or postalcode in type Text, etc. We wonder how to get a list of the columns included in the QuerySet, including: the column's name the datatype of the column corresponding to the serializer fields of serializers.IntegerField, serializers.DateTimeField, etc. We appreciate hints and suggestions. -
TypeError: unhashable type: 'dict' in Django
I',m working on django rest project and i'm getting an err, i'm getting an error can anyone help, below is my code & d err msg def get(self, request, reference): transaction = walletTransaction.objects.get( paystack_payment_reference=reference, wallet__user=request.user) reference = transaction.paystack_payment_reference url = 'https://api.paystack.co/transaction/verify/{}'.format(reference) headers = { {"authorization": f"Bearer {settings.PAYSTACK_SECRET_KEY}"} } r = requests.get(url, headers=headers) err message File "/home/olaneat/Desktop/files/project/django/jobConnect/job-connect/wallet/serializers.py", line 59, in save headers = { TypeError: unhashable type: 'dict' can anyone help pls -
crispy_forms is not working : ModuleNotFoundError: No module named 'crispy_forms'
Steps that I followed pip install django-crispy-forms add inside setting.py INSTALLED_APPS = [ ... 'crispy_forms', ... ] and CRISPY_TEMPLATE_PACK = 'uni_form' press the run icon of pycharm (top right) I tried to install pip install -e git+git://github.com/maraujop/django-crispy-forms.git#egg=django-crispy-forms I tried to make a migration but same error. I tried to install with pipenv install django-crispy-forms. I don't have the error if I do : "python3 manage.py runserver" but crispy-forms doesn't work ERROR : ... File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'crispy_forms' -
Django simplejwt validate token
I am implementing authentication with Django simpleJwt, and have a question. I want to create something with Client's jwt token. I use methods provided from simpleJwt to validate and decode jwt token. class AccountBookAPIView(APIView): def post(self, request): jwt_authenticator = JWTAuthentication() raw_access_token = request.META.get('access_token') validated_token = jwt_authenticator.get_validated_token(raw_access_token) user = jwt_authenticator.get_user(validated_token) However, I doubt that some methods really validate token. So I checked the method's implementation. Below is the code for question. def get_validated_token(self, raw_token): """ Validates an encoded JSON web token and returns a validated token wrapper object. """ messages = [] for AuthToken in api_settings.AUTH_TOKEN_CLASSES: try: return AuthToken(raw_token) except TokenError as e: messages.append( { "token_class": AuthToken.__name__, "token_type": AuthToken.token_type, "message": e.args[0], } ) raise InvalidToken( { "detail": _("Given token not valid for any token type"), "messages": messages, } ) # this class is AuthToken in my opinion. class AccessToken(Token): token_type = "access" lifetime = api_settings.ACCESS_TOKEN_LIFETIME I can't find the point that validate token from Database. It looks like just construction of token for me. Don't I need to check token in the Database(blacklist and outstanding tokens)? Plz help me. Any answer is welcome. Below is my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # my apps 'members', 'account_books', … -
WSGI django ModuleNotFoundError: No module named 'django'
I have been trying forever to get my django api to deploy via apache. I have installed mod_wsgi for python 3.7 and my venv is using python 3.7.15. Trying to go to my django app url I am getting a 500 error. Error log shows: [Tue Dec 20 21:31:30.690951 2022] [:error] [pid 19216] /usr [Tue Dec 20 21:31:30.691287 2022] [:error] [pid 19216] mod_wsgi (pid=19216): Target WSGI script '.../project/project/wsgi.py' cannot be loaded as Python module. [Tue Dec 20 21:31:30.691323 2022] [:error] [pid 19216] mod_wsgi (pid=19216): Exception occurred processing WSGI script '.../project/project/wsgi.py'. [Tue Dec 20 21:31:30.691393 2022] [:error] [pid 19216] Traceback (most recent call last): [Tue Dec 20 21:31:30.691423 2022] [:error] [pid 19216] File ".../project/project/wsgi.py", line 19, in <module> [Tue Dec 20 21:31:30.691428 2022] [:error] [pid 19216] from django.core.wsgi import get_wsgi_application [Tue Dec 20 21:31:30.691444 2022] [:error] [pid 19216] ModuleNotFoundError: No module named 'django' [Tue Dec 20 21:31:51.190670 2022] [:error] [pid 19217] 3.7.15 (default, Oct 31 2022, 22:44:31) [Tue Dec 20 21:31:51.190707 2022] [:error] [pid 19217] [GCC 7.3.1 20180712 (Red Hat 7.3.1-15)] apache conf file: <VirtualHost *:80> ServerName api.project.com DocumentRoot path/to/project/root WSGIScriptAlias / /path/to/wsgi.py WSGIDaemonProcess project-name processes=4 threads=1 display-name=%{GROUP} python-path=path/to/lib/python3.7/site-packages:/path/to/project/root WSGIProcessGroup project-group <Directory "/path/to/project/root"> Require all granted </Directory> #SSL stuff... </VirtualHost> wsgi.py: … -
django redirect to subdomain with exact same url
I have a Django website accessible at codewithbishal.com. This is basically a django blog website and all the blog articles are accessible at codewithbishal.com/example/<path> But now I want to completely restructure the website{such that it is accessible at blog.codewithbishal.com/<path>} and I do no want to lose the current SEO therefore I want to configure django redirect such that when someone launches codewithbishal.com/example/<path> through google search search result or directly through link, they are redirected to blog.codewithbishal.com/<path> instead of a 404 page and eventually google will start showing the new links instead of old once. -
Creating a simple multiple users app in Django
So I've created 3 different users: admins, developers, and project managers. When I use the individual signup forms for each of these users and log out, it works, but then I when try to use the login form, it seems to me that it's acting like the signup form. Because when I input the same user details as the one I just created into the login form, it throws up the built-in error message, 'A user with that user name already exists' I'm not sure how to proceed from here. Here's what I have so far. models.py class CustomUser(AbstractUser): ACCOUNT_TYPE_CHOICES = ( ('admin', 'Admin'), ('developer', 'Developer'), ('project_manager', 'Project Manager') ) account_type = models.CharField(max_length=20, choices=ACCOUNT_TYPE_CHOICES) login and signupviews class LoginView(View): def get(self, request): # Render the login form form = LoginForm() return render(request, 'users/login.html', {'form': form}) def post(self, request): # Get the form data from the request form = LoginForm(request.POST) # Validate the form data if form.is_valid(): # Get the username and password from the form username = form.cleaned_data['username'] password = form.cleaned_data['password'] # Authenticate the user user = authenticate(request, username=username, password=password) # If the user is authenticated, log them in and redirect to the homepage if user is not None: login(request, … -
Django-admin startproject
I am new to django and I tried to create a project with django-admin startproject command. The tutorial I was referring to had no errors while going through this command but I get the following error. The tutorial and I are not doing it in any virtual environment. Though this error comes, the files and folder is created in the directory I am working in, how should I solve this error? Traceback (most recent call last): File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in run_module_as_main return run_code(code, main_globals, None, File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Users\username\AppData\Local\Programs\Python\Python39\Scripts\django-admin.exe_main.py", line 7, in <module> File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management_init.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management_init.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\startproject.py", line 21, in handle super().handle("project", project_name, target, **options) File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\templates.py", line 225, in handle run_formatters([top_dir]) File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\utils.py", line 165, in run_formatters subprocess.run( File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 501, in run with Popen(*popenargs, **kwargs) as process: File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 947, in init self._execute_child(args, executable, preexec_fn, close_fds, File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 1416, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, PermissionError: [WinError 5] Access is denied -
Django Admin doesn't recognise blank=True in model
When I try to edit a user (using a custom UserChangeForm) in the Django admin panel, validation insists that fields I have set blank=True in the model are required. I don't know where to begin solving this; I had the same issue with the CustomUserCreationForm but reverted to using the default which works as expected (asks for username, password1 & password2, creates the user with blank display_name, bio and profile_picture fields). models.py: from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): display_name = models.CharField(max_length=30, blank=True, null=True) bio = models.TextField(blank=True, null=True) profile_picture = models.ImageField(upload_to='images/', blank=True, null=True) def save(self, *args, **kwargs): if not self.display_name: self.display_name = self.username super().save(*args, **kwargs) def __str__(self): return self.username forms.py: from django import forms from django.contrib.auth.forms import UserChangeForm from .models import CustomUser class CustomUserChangeForm(UserChangeForm): display_name = forms.CharField(label="display_name") bio = forms.CharField(widget=forms.Textarea) profile_picture = forms.ImageField(label="profile_picture") class Meta(): model = CustomUser fields = ("username", "email", "display_name", "bio", "profile_picture") admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): form = CustomUserChangeForm fieldsets = ( (None, {'fields': ('username', 'password', 'email', 'display_name', 'bio', 'profile_picture')} ), ) model = CustomUser list_display = ["username", "email",] admin.site.register(CustomUser, CustomUserAdmin) -
'NoneType' object has no attribute 'strip' - CS50W Wiki
I'm getting this error while trying to create a search function in Django. This is where I'm having trouble: If the query does not match the name of an encyclopedia entry, the user should instead be taken to a search results page that displays a list of all encyclopedia entries that have the query as a substring. For example, if the search query were ytho, then Python should appear in the search results. This is the view: def search(request): if request.method == 'POST': search_title = request.POST['q'] content = converter(search_title) if search_title is not None: return render(request, "encyclopedia/entry.html", { "entry": content, "entryTitle": search_title }) else: entries = util.list_entries() search_pages = [] for entry in entries: if search_title in entries: search_pages.append(entry) return render(request, "encyclopedia/search.html",{ "entries": search_pages }) And the HTML: <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> Traceback: Traceback (most recent call last): File "C:\Users\anshi.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\anshi.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python\Py Projects\CS50 attempt 00\wiki\encyclopedia\views.py", line 70, in search content = converter(search_title) File "D:\Python\Py Projects\CS50 attempt 00\wiki\encyclopedia\views.py", line 19, in converter html = Markdowner.convert(content) File "C:\Users\anshi.virtualenvs\storefront-bp3LZ8Cr\lib\site-packages\markdown\core.py", line 248, in convert … -
Adding widgets to django form does not update the forms
So I have a login form for which I am trying to edit the css attributes. However I cannot seem to find the correct solution. Below is my views.py, forms.py and html snippet accordingly. def index(request): context = {} if request.method == 'POST': form = LoginForm(data=request.POST) context['form'] = form logging.debug(form.is_valid()) logging.debug(form.cleaned_data) logging.debug(form.errors) if form.is_valid(): logging.debug("form valid") username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') if authenticate(username, password): logging.debug("logged IN") messages.success(request, f' welcome {username} !!') return redirect('loggedIn') else: logging.debug("wrong!") messages.info(request, f'Password or Username is wrong. Please try again.') form = AuthenticationForm() return render(request, "index_logged_out.html", {"form": form}) class LoginForm(forms.ModelForm): class Meta: model = WebsiteRegistrant fields = ['username', 'password',] widgets = { 'username': TextInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Username' }), 'password': PasswordInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Password' }) } <form method="POST"> {% csrf_token %} <center> <div class="form-group" style = "margin-bottom: 10px; width: 300px"> {{ form.password }} </div> <div class="form-group" style = "margin-bottom: 10px; width: 300px"> {{ form.password }} </div> <button class="btn btn-primary btn-block fa-lg gradient-custom-2 mb-3" type="submit" style="width: 300px;">Login</button> </center> </form> Any idea what I am doing wrong or what I could fix in order to add the class name and attributes as I have defined in the form widget? Thanks -
How to add data to Django's database by the click of a button using JS and AJAX
I'm trying to add data that I rendered on a page from an API endpoint, to my database when I click "Add to my records" button, as can be seen in the image below, and I'm only trying to store "Date and Country" into the database (my model table has only date and country) enter image description here I've seen many resources talking about how JS and AJAX are useful in this case but I'm lost with logic of it all. Is there any way someone could explain how it's supposed to be done. models.py from django.db import models class CountryData(models.Model): country = models.CharField(max_length=100) date = models.DateTimeField() def __str__(self): return self.country views.py def all_countries(request): first_response = requests.get("https://api.covid19api.com/summary").json() results = len(first_response["Countries"]) my_new_list = [] data_list = [] for i in range(0, results): my_new_list.append(first_response["Countries"][i]) # print(my_new_list) if request.method == "POST": if request.POST.get("country") and request.POST.get("date"): added_record = CountryData() added_record.country = request.POST.get("country") # 2022-12-19T08:53:48.179Z added_record.date = datetime.datetime.strptime( request.POST.get("date"), "%Y-%m-%dT%I:%M:%S.%fZ" ) added_record.save() return render(request, "allcountries.html") else: return render(request, "allcountries.html", ) context = {"my_new_list": my_new_list} return render(request, "allcountries.html", context) urls.py from django.urls import path, include from .views import home, all_countries urlpatterns = [ path("", home, name="home"), path("allcountries", all_countries, name="all_countries") ] allcountries.html {% extends '_base.html' %} {% … -
Upload file to database with file link
I am working on a project whereby the user has to upload a document. I have successfully been able to upload a file to the database and serve the user the uploaded file. I however want to upload files to the database using the file link rather than just selecting file from your device. models.py class Books(models.Model): title = models.CharField(max_length=500, default="") author = models.CharField(max_length=500, default="") publication = models.CharField(max_length=500, default="") edition = models.IntegerField(default="") is_available = models.BooleanField() book = models.FileField( default="", upload_to="books", validators=[validate_book_extension], verbose_name="books", ) genre = models.ForeignKey(Genre, on_delete=models.CASCADE, default="") class Meta: verbose_name_plural = "Books" def __str__(self): return self.title views.py def books(request): genres_names = Genre.objects.all() if request.method == "POST": form = BookFile(request.POST, request.FILES) files = request.FILES.getlist("book") genres_name = request.POST.get("genres") try: if form.is_valid(): new_old_genre, created = Genre.objects.get_or_create( genres=genres_name.lower() ) genre = Genre.objects.filter(genres=genres_name) if files: for f in files: names = str(f) name = names.strip(".pdf") Books.objects.create( genre=new_old_genre, book_title=name, book=f ) return redirect(index) except IntegrityError: messages.error(request, "value exist in database") return redirect(books) else: form = BookFile() return render(request, "books.html", {"form": form, "genres_names": genres_names}) forms.py class BookInfo(forms.ModelForm): class Meta: model = Genre fields = [ "genres", ] widgets = {"genres": forms.TextInput(attrs={"list": "genres"})} class BookFile(BookInfo): book = forms.FileField(widget=forms.ClearableFileInput(attrs={"multiple": True})) class Meta(BookInfo.Meta): fields = BookInfo.Meta.fields + [ "book", … -
cannot import name 'FieldDoesNotExist'
I am trying to run command: python3 manage.py runserver 0:80 and I get the below error Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib64/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib64/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 423, in check databases=databases, File "/usr/local/lib/python3.6/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py", line 416, in check for pattern in self.url_patterns: File "/usr/local/lib/python3.6/site-packages/django/utils/functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py", line 602, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.6/site-packages/django/utils/functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py", line 595, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib64/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "/home/rc/qrd/qos-dashboard/config/urls.py", line 4, in from rest_framework_swagger.views import get_swagger_view File "/usr/local/lib/python3.6/site-packages/rest_framework_swagger/views.py", line 3, in from … -
Setup logging of Celery in Django correctly - how?
Setting up celery on our production server seems to be more complicated than it should be - and the problem is logging. Our setup is like this: Server is Ubuntu 20.04.5 LTS We run Django 3.2.8 in it's own user and group named "django" The Celery process also has it's own user and group named "celery". Celery is set up as a service and logs to /var/log/celery In celery.py we have set djangoConf pointing to the main settings.py On startup Celery tries to touch a django-logfile and - missing the permissions to do so - returns an error: Dec 16 10:57:27 h2989788 celery[128418]: Usage: celery [OPTIONS] COMMAND [ARGS]... Dec 16 10:57:27 h2989788 celery[128418]: Try 'celery --help' for help. Dec 16 10:57:27 h2989788 celery[128418]: Error: Invalid value for '-A' / '--app': Dec 16 10:57:27 h2989788 celery[128418]: Unable to load celery application. Dec 16 10:57:27 h2989788 celery[128418]: While trying to load the module theApp the following error occurred: Dec 16 10:57:27 h2989788 celery[128418]: Traceback (most recent call last): Dec 16 10:57:27 h2989788 celery[128418]: File "/usr/lib/python3.8/logging/config.py", line 563, in configure Dec 16 10:57:27 h2989788 celery[128418]: handler = self.configure_handler(handlers[name]) Dec 16 10:57:27 h2989788 celery[128418]: File "/usr/lib/python3.8/logging/config.py", line 744, in configure_handler Dec 16 10:57:27 h2989788 … -
Unable to install libapache2-mod-wsgi-py3
I am having some issues with wsgi and getting my django api up and running using apache. I think the issue is the mod_wsgi.so. I have already installed libapache2-mod-wsgi, but my venv is configured using python 3.6. Based on my research I think I need libapache2-mod-wsgi-py3. Trying to install with sudo yum install libapache2-mod-wsgi-py3 returns Loaded plugins: extras_suggestions, langpacks, priorities, update-motd amzn2-core | 3.7 kB 00:00:00 No package libapache2-mod-wsgi-py3 available. Error: Nothing to do Error log shows: Traceback (most recent call last): [Tue Dec 20 19:02:24.660246 2022] [:error] [pid 13266] File ".../project/project/wsgi.py", line 13, in <module> [Tue Dec 20 19:02:24.660275 2022] [:error] [pid 13266] from django.core.wsgi import get_wsgi_application [Tue Dec 20 19:02:24.660283 2022] [:error] [pid 13266] File ".../lib/python3.6/site-packages/django/__init__.py", line 1, in <module> [Tue Dec 20 19:02:24.660295 2022] [:error] [pid 13266] from django.utils.version import get_version [Tue Dec 20 19:02:24.660302 2022] [:error] [pid 13266] File ".../lib/python3.6/site-packages/django/utils/version.py", line 7, in <module> [Tue Dec 20 19:02:24.660313 2022] [:error] [pid 13266] from django.utils.regex_helper import _lazy_re_compile [Tue Dec 20 19:02:24.660319 2022] [:error] [pid 13266] File ".../lib/python3.6/site-packages/django/utils/regex_helper.py", line 10, in <module> [Tue Dec 20 19:02:24.660330 2022] [:error] [pid 13266] from django.utils.functional import SimpleLazyObject [Tue Dec 20 19:02:24.660336 2022] [:error] [pid 13266] File ".../lib/python3.6/site-packages/django/utils/functional.py", line 362, in <module> … -
Seeing a 500 internal server error with mod_wsgi, apache and django but nothing in the log file. Gunicorn runs without issue
We released some new code that depends on django-tree-queries and are now seeing an internal server error with mod_wsgi. There is nothing in the apache logs and nothing in the django logs. Normally when we have django erors we do see a stack trace in the logs and get an email. Here is our apache config: <VirtualHost IP_ADDR:443> ServerName our.url ErrorLog ${APACHE_LOG_DIR}/dev-ssl-error.log CustomLog ${APACHE_LOG_DIR}/dev-ssl-access.log combined LogLevel debug Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" SSLEngine on <Directory /var/www/django/app/config> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess apps-dev processes=2 threads=15 display-name=%{GROUP} WSGIProcessGroup apps-dev WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias / /var/www/django/app/config/wsgi.py RewriteEngine On RewriteCond %{REQUEST_METHOD} ^(OPTIONS|TRACE) RewriteRule .* - [F] </VirtualHost> Here is our wsgi.py file: activate_file = "/var/www/django/app/venv/bin/activate_this.py" exec(open(activate_file).read(), {"__file__": activate_file}) import os # noqa: E402 import sys # noqa: E402 from pathlib import Path # noqa: E402 from django.core.wsgi import get_wsgi_application # noqa: E402 ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent # This allows easy placement of apps within the interior # our_app directory. sys.path.append(str(ROOT_DIR / "our_app")) sys.path.append(str(ROOT_DIR)) # Explicitly set the settings module for this wsgi app os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.apps_dev" # Enable dot env file reading by default for this environment os.environ["DJANGO_READ_DOT_ENV_FILE"] = "True" # This application object is used by any WSGI server configured to … -
My django form is never valid. Why is this happening?
I have django application where I want user to be able to upload videos. My view looks like this: class CreateVideo(View): def post(self, request): videos = models.Video.objects.all().order_by('-created_on') form = forms.VideoUploadForm(request.POST) if form.is_valid(): print('form is valid') video = form.save(commit=False) video.save() print('video uploaded') else: print('form not valid') context = { 'video_list': videos, 'form': form, } return redirect('index') def get(self, request): videos = models.Video.objects.all().order_by('-created_on') form = forms.VideoUploadForm() context = { 'video_list': videos, 'form': form, } return render(request, 'videos/upload_video.html', context) My form: class VideoUploadForm(forms.ModelForm): class Meta: model = Video fields = ['title', 'description', 'file'] and model: class Video(models.Model): video_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True ) title = models.CharField(max_length=50, null=True) description = models.CharField(max_length=500, null=True) file = models.FileField(null=True) created_on = models.DateTimeField(default=timezone.now, null=True) at = models.ForeignKey(at, on_delete=models.CASCADE, null=True) and my template: <div> <form method="post"> {% csrf_token %} {{ form | crispy }} <button>Submit!</button> </form> </div> When I click submit button, I get: form not valid in terminal. I want form to be created, but form is just never valid. Where is the problem? -
How can I add a dyno for my deployed app in Heroku?
I deployed the app for Heroku successfully but when I check status with 'heroku ps' command I receive information that I have no dynos on the app. The app is created in Django. I tried to add a dyno for my app by browser on my account but there is not any option to do that. Is there a possibility that Procfile causes that issue? My Procfile (file without extension) command: web: gunicorn mywebsite.wsgi --log-file - I tried a lot of solutions from the internet and stackoverflow but my problem is still not solved. I would be grateful for any help. -
I don't know where to look
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I don't know where to look