Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
register redirect home python django
Can anyone explain why my code does not redirect me to home.html after successful registration? I'm creating custom login and registration forms. Let me know if there is more code you need to see. ``` from django.shortcuts import render, redirect from django.views.generic import TemplateView, CreateView from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from django.contrib import messages from .forms import JoinForm class HomeView(TemplateView): template_name = "home.html" class JoinView(TemplateView): template_name = "registration/join.html" def join(request): if request.method == "POST": form = JoinForm(request.POST or None) if form.is_vaild(): form.save() return render(request, 'home') else: return render(request, 'join') class LoginView(TemplateView): template_name = "login.html" ``` -
Group send a channel layer from outside consumer class
I have a process that when it gets a message it sends a command to a celery process. From there I would want to send back a message from the celery worker back to the backend telling it "Im done now you can continue". So can I send a group message to a channel layer from outside -
How to log INFO logs in settings.py
I'm trying to log some info messages specifically in django settings.py. I'm following the first example in the django documentation that shows a simple configuration. The only thing I changed was having the log show INFO level messages. When I run python manage.py runserver, the log statement is never shown. The logs are only shown for WARNING level or above (more critical). Here is my configuration that is located in settings.py import logging ... LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, '': { 'handlers': ['console'], 'level': 'INFO', 'propagate': True }, } ... def do_something(): logger.info('Doing Something') do_something() Note I'm trying to log statements only in my settings.py file as of right now. -
Unable to fetch user details by an id given in a JSON string | Getting a Type error in Django
I am trying to get a user's details (in a JSON string format) by providing a user id (also in a JSON string format) This is my model's code class Description(models.Model): description = models.CharField(max_length=150) def __str__(self): return self.description class Team(models.Model): team_name = models.CharField(max_length=50) description = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.team_name class User(models.Model): name = models.CharField(max_length=64) username = models.CharField(max_length=64, unique=True) description = models.ForeignKey(Description, null=True, on_delete=models.SET_NULL) team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.name}" This is the serializer Code from rest_framework import serializers from users.models import Description, Team, User class DescriptionSerializer(serializers.ModelSerializer): class Meta: model = Description fields = "__all__" class TeamSerializer(serializers.ModelSerializer): class Meta: model = Team fields = "__all__" class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" This is the views code from urllib import response from django.shortcuts import render from django.http import JsonResponse from rest_framework.response import Response from rest_framework.decorators import api_view from users.models import User, Team, Description from .serializers import UserSerializer, TeamSerializer, DescriptionSerializer # describe user @api_view(["GET"]) def describe_user(request): user = User.objects.get(pk=request.data["id"]) serializer = UserSerializer(user) return JsonResponse(serializer, safe=False) Whenever I enter a JSON data in the body of URL eg: {"id":"2"} I get this error [TypeError at /describe/ Object of type UserSerializer … -
How to substract amount input from current balance to get available balance in python Django
I have available balance field and current balance field in my user profile model in Django. I want to substract amount input from current balance to get available balance show in my web page of the user profile -
Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name. I have tried other solutions, but none of them work
I am making a Django blog, and I encountered this error. When you press submit, this error shows up: Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name. If you want to see the error yourself, go to mayfly404.com, click on a post, and then try to comment. Here is my code: blog/views.py from django.shortcuts import render, redirect from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import FormView from django.views.generic.detail import SingleObjectMixin from django.urls import reverse from django.views import View from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) from .models import Post, Comment from .forms import CommentForm def home(request): context = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', context) class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] class PostComment(SingleObjectMixin, FormView): model = Post form_class = CommentForm template_name = 'blog/post_detail.html' def post(self, request, *args, **kwargs): self.object = self.get_object() return super().post(request, *args, **kwargs) def get_form_kwargs(self): kwargs = super(PostComment, self).get_form_kwargs() kwargs['request'] = self.request return kwargs def form_valid(self, form): comment = form.save(commit=False) comment.post = self.object comment.save() return super().form_valid(form) def get_success_url(self): post = self.get_object() return reverse('post_detail', kwargs={'pk': post.pk}) + '#comments' class PostDisplay(DetailView): model = Post template_name = 'blog/post_detail.html' context_object_name = … -
Send 3 or more forms at the same time with Django
Please tell me how to do Django tasks in parallel, like I've 3 accounts sending 3 forms at same time, each form on one account, I want the forms to be sent at the same time on the background. Currently, I'm sending the forms with celery on background , I just want them to run on parallel instead of a queue. -
Django: How to use and return 2 values from a model
I have 3 tables, a relation many to many. 1 is INVOICE 1 Product(as category) and the middle one who links them. I need in the middle table to get also the "price" from product table not only the name; because i have an inline form and when i select the product name i would like the price to appear without the user to type it in. Can someone help ? -
How to exclude 404 error messages from logging to email?
Good afternoon. I have this type of logs in the settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', }, 'mail_admins': { 'level': 'WARNING', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler', 'include_html': True, }, }, 'loggers': { '': { 'handlers': ['console', 'mail_admins'], 'level': 'DEBUG', 'propagate': False, }, } } I receive all messages of the level of warning and above in the email. Due to various robots, spammers or other users looking for hidden files and folders, I get a lot of 404 (page not found) error messages. How can I stop receiving information about 404 errors? -
django rest framework with React js : How to use google map api with django
i have done the project with reactJS and django as back , i have used django rest framework. I have to work with google maps api, at the moment, i have the front but for the back, i really don't know how does it works. -
Pytest and pytest-cov raises ImportError while importing test module
After executing my test suite using Pytest + Pytest-cov I'm getting the following error: ERROR collecting env/Lib/site-packages/social_core/tests/backends/test_yahoo.py ____________________________________ImportError while importing test module '/app/env/Lib/site-packages/social_core/tests/backends/test_yahoo.py'. I have excluded the env folder by configuring my setup.cfg like this: [flake8] max-line-length = 119 exclude = .git,*/migrations/*,*env*,*venv*,__pycache__,*/staticfiles/*,*/mediafiles/* [coverage:run] source = . omit= *apps.py, *settings.py, *urls.py, *wsgi.py, *asgi.py, manage.py, conftest.py, *base.py, *development.py, *production.py, *__init__.py, */migrations/*, *tests/*, */env/*, */venv/*, [coverage:report] show_missing = True However for some reason the test is not excluding the env folder. I can't understand why it is not excluded during test. I am running the test from docker file by executing the following command: docker compose exec api pytest -p no:warnings --cov=. can some one help me in figuring out the issue? -
Internal Server Error while deployoing Django on Heroku
Please find given below my error log 2022-09-23T13:04:15.841669+00:00 app[web.1]: path('tinymce/', include('tinymce.urls')), 2022-09-23T13:04:15.841669+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/urls/conf.py", line 38, in include 2022-09-23T13:04:15.841674+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/tinymce/urls.py", line 1, in 2022-09-23T13:04:15.841675+00:00 app[web.1]: from django.conf.urls import url 2022-09-23T13:04:15.841675+00:00 app[web.1]: ImportError: cannot import name 'url' from 'django.conf.urls' (/app/.heroku/python/lib/python3.9/site-packages/django/conf/urls I have been facing this problem while deploying my app on heroku, anyone can help on this? -
Intances are created when using annotate and Foreign Key
I have the following situation: I am creating an app where I have a Person model and I want to store a status history in a table, so that looking for the most recent status in the table would return the current status of the person. My solution was creating a Status table with a Foreign Key pointing to the Person. Looking for the most recent entry in person.status_set would make it easy looking for the current status. class Person(models.Model): ... def _get_status(self): return self.status_set.order_by("-timestamp").first() @property def status(self): try: return self._get_purchase_status().status except AttributeError: # TODO: log error: Person without status. return None # TODO: Change this. @status.setter def status(self, new_status): s = Status( person=self, status=new_status ) s.save() @status.deleter def status(self): if self.status: self.status_set.order_by("-timestamp").first().delete() class Status(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) status = models.CharField( max_length=50, ) timestamp = models.DateTimeField(auto_now_add=True) When I try to create a QuerySet containing the person and the last status info, I perform this query: Person.objects.annotate( person_status=Subquery( Status.objects.filter(person_id=OuterRef("id")).order_by("-timestamp").values("status")[:1] ) ).values() Calling the annotate function using .values() at the end works as expected, but when I only run the annotate function, Person.objects.annotate( person_status=Subquery( Status.objects.filter(person_id=OuterRef("id")).order_by("-timestamp").values("status")[:1] ) ) I see that there are instances created in the Status table for each Person … -
How to implement Like Dislike button for anonymous user in Django?
How can I implement like and dislike button functionality for anonymous users in my django website? I am recently developing django website,and decided not to use User Login & Logout for the purpose of more visiting users. The problem is how to do implement IP Address instead of "request.user". Anyone knows how to set IP address as if like a user for "like and dislike button"??? Below is my code so far (set request.user for like dislike function): #views.py Dislike is the same code. @login_required(login_url="login") def Like(request, slug): add = Add.objects.get(slug=slug) # remove dislike when user hit like. is_dislike = False for dislike in add.dislikes.all(): if dislike == request.user: is_dislike = True break if is_dislike: add.dislikes.remove(request.user) # add like is_like = False for like in add.likes.all(): if like == request.user: is_like = True break if not is_like: add.likes.add(request.user) if is_like: add.likes.remove(request.user) next = request.POST.get("next", "/") return HttpResponseRedirect(next) #review.html inside templates <div class="rate-added-rule"> <form action="{% url 'like' added_data.slug %}" method="POST"> {% csrf_token %} <input type="hidden" name="next" value="{{ request.path }}"> <button type="submit" class="like-button"> <i class="far fa-thumbs-up">LIKE<span>VOTES:&nbsp;{{ added_data.likes.all.count }}</span></i> </button> </form> <form action="{% url 'dislike' added_data.slug %}" method="POST"> {% csrf_token %} <input type="hidden" name="next" value="{{ request.path }}"> <button type="submit" class="dislike-button"> <i class="far fa-thumbs-down">DISLIKE<span>VOTES:&nbsp;{{ … -
Include django rest serializer data with Django `json_script` templatetag
I use Django Camel Case to swap from pythons snake_case in the backend to camelCase in the front end, so the keys of the data comply with conventional JavaScript syntax. This works great for AJAX calls returning JSON. However often I wish to embed some JSON in an HTML template with Django's standard 'json_script`. I don't wish to use some other JSON strinfier because then it won't be safely escaped. The problem is that when I embedded the JSON in HTML, it is not camelCased: Example # --- models.py --- from django.db import models class Foo(models.Model): last_name = models.CharField(max_length=250, unique=True) # --- serializers.py --- from rest_framework import serializers class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = ('id', 'last_name') # --- views.py --- from django.views import generic from . import models class IndexView(generic.ListView): template_name = f"myapp/index.html" model = Foo def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['serializer'] = serializers.FooSerializer(self.object_list, many=True) return context Then in the template: {{ serializer.data|json_script:"FOO_DATA" }} <script type="module"> const foos = JSON.parse(document.getElementById('FOO_DATA').textContent); console.log(foos) </script> But unfortunately it will result in something like: [{ id: 1, last_name: 'Smith'}, { id: 2, last_name: 'Kent'}] But I require last_name to be camel cased: [{ id: 1, lastName: 'Smith'}, { id: 2, … -
Django CSRF Token with POST Throws 403 Due to No Origin Header
Got migrating legacy project from Python 2.7 & Django 1.9 to Python 3.10 & Django 4.1. There is also a bunch of JavaScript code which I only have a general idea of. Stuck struggling with 403 Code with POST Request from url to another due to important CSRF protection: Help Reason given for failure: Origin checking failed - null does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a … -
Does anyone know how to deploy a Django project which has Postgres Database on minikube locally. any refrences i try all of them which i found in
here is My Deployment files #Depployment Django apiVersion: apps/v1 kind: Deployment metadata: name: django1 labels: app: django1 spec: replicas: 1 selector: matchLabels: app: django-container template: metadata: labels: app: django-container spec: containers: - name: todo image: jayantkeer/image-of-kubernets command: ["python manage.py makemigrations", "python manage.py migrate","python manage.py"] # runs migrations and starts the server ports: - containerPort: 8000 env: - name: POSTGRES_USER valueFrom: secretKeyRef: name: postgres-credentials key: user - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: postgres-credentials key: password - name: POSTGRES_HOST value: postgres-service And postgres service file apiVersion: v1 kind: Service metadata: name: todo labels: app: todo spec: type: NodePort selector: app: django-container ports: - port: 8000 targetPort: 8000 and postgres deployment apiVersion: apps/v1 kind: Deployment metadata: name: postgres-deployment spec: replicas: 1 selector: matchLabels: app: postgres-container template: metadata: labels: app: postgres-container tier: backend spec: containers: - name: postgres-container image: postgres:9.6.6 env: - name: DATABASE_USER valueFrom: secretKeyRef: name: postgres-credentials key: user - name: DATABASE_PASS valueFrom: secretKeyRef: name: postgres-credentials key: password - name: POSTGRES_DB value: kubernetes_django ports: - containerPort: 5432 volumeMounts: - name: postgres-volume-mount mountPath: /var/lib/postgresql/data volumes: - name: postgres-volume-mount persistentVolumeClaim: claimName: postgres-pvc -
Django bootstrap files missing when static changed
I have changed my django debug to false. I am now missing the bootstrap files, previously found in the static directory. The console output shows i'm getting 404s on the bootstrap files. debug output: Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. [23/Sep/2022 12:49:42] "GET /login/?next=/ HTTP/1.1" 200 2853 [23/Sep/2022 12:49:42] "GET /static/css/bootstrap.min.css HTTP/1.1" 404 179 [23/Sep/2022 12:49:42] "GET /static/orchestration/main.css HTTP/1.1" 404 179 [23/Sep/2022 12:49:42] "GET /static/js/jquery.min.js HTTP/1.1" 404 179 [23/Sep/2022 12:49:42] "GET /static/js/popper.min.js HTTP/1.1" 404 179 [23/Sep/2022 12:49:42] "GET /static/js/bootstrap.min.js HTTP/1.1" 404 179 [23/Sep/2022 12:49:42] "GET /static/js/bootstrap.min.js HTTP/1.1" 404 179 settings.py STATIC_URL = 'static/' #---- STATIC_ROOT = os.path.join(BASE_DIR, 'root') #---- STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'boot'), ] I have run python3 manage.py collectstatic. It has copied all these files to the root directory. I was expecting it just to look in the root directory to find them. -
QPainter::begin(): Returned false Error: Unable to write to destination
**QPainter::begin(): Returned false============================] 100% Error: Unable to write to destination Exit with code 1, due to unknown error.** def view_entry_pdf(request,id): standard_fields = ['user_username','user_email', 'form_id', 'entry_id', 'date_dmy','user_full_name'] try: entry = Entries.objects.get(pk=id) cert = Certificate.objects.filter(form_id=entry.form.id, is_active=1).first() get_cert = request.GET.get('cert_id','') if get_cert: cert = Certificate.objects.get(id=get_cert) if not cert: messages.warning(request, 'PDF template not found.') return HttpResponseRedirect(request.META.get('HTTP_REFERER')) valid_rules = validate_rules(entry,cert, cert.rules.all()) if valid_rules: pass else: messages.warning(request, 'Certificate rules not matched.') return HttpResponseRedirect(request.META.get('HTTP_REFERER')) entry.is_read = True entry.save() file_name = 'entry-certificate.pdf' if cert.file_name: file_name = cert.file_name res = re.findall(r'(\{\{[^}]+}\})', file_name) placeholders = {} standard_placeholders = {} #standard_fields for sf in standard_fields: sfv = '' if sf == 'user_username': sfv = entry.user.username elif sf == 'user_email': sfv = entry.user.email elif sf == 'form_id': sfv = str(entry.form.id) elif sf == 'entry_id': sfv = str(entry.id) elif sf == 'date_dmy': today = datetime.now().date() sfv = today.strftime("%d-%m-%Y") elif sf == 'user_full_name': sfv = f"{entry.user.first_name} {entry.user.last_name}" standard_placeholders['{{'+sf+'}}'] = sfv standard_placeholders = account_placeholders(request, standard_placeholders) if res: fields_all = entry.form.fields.all().order_by('sort_order') for f in fields_all: key = '{{'+f.label_name.replace(" ", "_").lower()+'}}' placeholders[key] = f.id for p in res: f_id = placeholders.get(p) if p and f_id: en_data = entry.columns.filter(field_id=f_id) val = '' if en_data.count() and en_data[0].value: val = en_data[0].value file_name = file_name.replace(p, val) elif standard_placeholders.get(p): file_name = file_name.replace(p, … -
Not Found The requested resource was not found on this server - Django-Cpanel
I'm trying to deploy the Django project.I don't know the problem is with the WHM&cpanel or my code I configured the python app from Cpanel passenger_wsgi.py import os import sys from selenium.wsgi import application urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('bulk.urls')) ] views.py from django.shortcuts import render def ime_bot(request): return render(request, 'Ibot.html') settings.py INSTALLED_APPS = [ 'bulk.apps.BulkConfig' ] TEMPLATES = [ {'DIRS': ['bulk/templates'],} ] bulk/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.ime_bot, name='bot_here'), ] Also I'm able to acces url.com/admin in the wierd html content I'm done with makemigrations,migrate,createsuper user and settings.py here is my error.log App 1193039 output: /opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/wsgi-loader.py:26: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses App 1193039 output: import sys, os, re, imp, threading, signal, traceback, socket, select, struct, logging, errno Please comment below if I need to update any kind of configuration -
Django and React: how to redirect to main page after successful login
I am building a login system webapp using react + django. My question is how can I redirect a user towards the main page, if the login credentials are successful. Right now I only managed to retrieve the authentication token from the backend. How can I modify this class to also check if the login is successful and then redirect towards the main page? class Login extends Component { state = { credentials: {username: '', password: ''} } login = event => { fetch('http://127.0.0.1:8000/auth/', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(this.state.credentials) }) .then( data => data.json()) .then( data => { this.props.userLogin(data.token); } ) .catch( error => console.error(error)) } register = event => { fetch('http://127.0.0.1:8000/api/users/', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(this.state.credentials) }) .then( data => data.json()) .then( data => { console.log(data.token); } ) .catch( error => console.error(error)) } inputChanged = event => { const cred = this.state.credentials; cred[event.target.name] = event.target.value; this.setState({credentials: cred}); } render() { return ( <div> <h1>Login user form</h1> <label> Username: <input type="text" name="username" value={this.state.credentials.username} onChange={this.inputChanged}/> </label> <br/> <label> Password: <input type="password" name="password" value={this.state.credentials.password} onChange={this.inputChanged} /> </label> <br/> <button onClick={this.login}>Login</button> <button onClick={this.register}>Register</button> </div> ); } } -
How to set session variable in Django template
How to set session variable within Django template, For example: <a href="{% url 'view' request.session.data.set("First data") %}">First Button</a> <a href="{% url 'view' request.session.data.set("Second data") %}">Second Button</a> <a href="{% url 'view' request.session.data.set("Third data") %}">Third Button</a> The Reason of doing this in the template not in the view: by clicking a certain button on the page the user should be redirected with different session data (that depends on the button being clicked) The Reason of not doing this with GET parameters: The data is sensitive -
How to use values of data in Foriegn key while importing in django import export
i want to ask how to use values of the foreign key while importing data from csv file in Django import export library.? Thanks in advance , the main issue i am having is I have to import a csv file containing the data of the model that has foreign keys in it. the overall architecture is something like this: the Main model is: class Reservation(models.Model): company = models.ForeignKey(company_models.CompanyProfileModel, null=True, blank=True, on_delete=models.CASCADE) reservation_status = models.CharField(max_length=35, null=True, blank=True, choices=status_types, default=REQUESTED) reservation_no = models.CharField(max_length=40, null=True, blank=True) client = models.ForeignKey(PersonalClientProfileModel, null=True, blank=True, on_delete=models.SET_NULL) service_type = models.ForeignKey(setting_models.ServiceType, on_delete=models.SET_NULL, null=True, blank=True) sales_tax = models.ForeignKey('setting.SalesTax', on_delete=models.CASCADE, null=True, blank=True) charge_by = models.CharField(max_length=50, choices=charge_by, null=True, blank=True) pay_by = models.CharField(max_length=50, choices=payment_type, null=True, blank=True, verbose_name='Payment Method') vehicle_type = models.ForeignKey(setting_models.VehicleType, on_delete=models.SET_NULL, null=True, blank=True) vehicle = models.ForeignKey(Vehicle, null=True, blank=True, on_delete=models.SET_NULL) driver = models.ForeignKey(EmployeeProfileModel, null=True, blank=True, on_delete=models.SET_NULL) accepted_by_driver = models.BooleanField(null=True, blank=True, default=False) pickup_address = models.ForeignKey(GeoAddress, on_delete=models.SET_NULL, related_name='pickup_address', null=True, blank=True) destination_address = models.ForeignKey(GeoAddress, on_delete=models.SET_NULL, related_name='destination_address', null=True, blank=True) # pickup_address = models.CharField(max_length=200, null=True, blank=True) # destination_address = models.CharField(max_length=200, null=True, blank=True) pick_up_date = models.DateField(blank=True, null=True) pick_up_time = models.TimeField(blank=True, null=True) distance_in_miles = models.FloatField(null=True, blank=True, default=0.0) distance_covered_in_ride = models.FloatField(null=True, blank=True, default=0.0) total_hours = models.CharField(max_length=10, null=True, blank=True) from_date = models.DateField(null=True, blank=True) to_date = models.DateField(null=True, blank=True) no_of_days = models.IntegerField(null=True, blank=True, … -
Django-->TypeError: __init__() got an unexpected keyword argument 'providing_args'
I'm running my django-app-api server on docker and I'm stuck at a particular place. The server doesnt spawn due to the following error : TypeError: init() got an unexpected keyword argument 'providing_args' I'm getting the following error trace while running my django-api docker container using docker-compose myproject-api-webserver | 2022-09-23 11:09:26,477 myprojectnetwork.settings INFO ALLOWED_HOSTS environment variable ignored. myproject-api-webserver | Traceback (most recent call last): myproject-api-webserver | File "manage.py", line 25, in <module> myproject-api-webserver | execute_from_command_line(sys.argv) myproject-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line myproject-api-webserver | utility.execute() myproject-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 420, in execute myproject-api-webserver | django.setup() myproject-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup myproject-api-webserver | apps.populate(settings.INSTALLED_APPS) myproject-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate myproject-api-webserver | app_config = AppConfig.create(entry) myproject-api-webserver | File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 193, in create myproject-api-webserver | import_module(entry) myproject-api-webserver | File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module myproject-api-webserver | return _bootstrap._gcd_import(name[level:], package, level) myproject-api-webserver | File "<frozen importlib._bootstrap>", line 1014, in _gcd_import myproject-api-webserver | File "<frozen importlib._bootstrap>", line 991, in _find_and_load myproject-api-webserver | File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked myproject-api-webserver | File "<frozen importlib._bootstrap>", line 671, in _load_unlocked myproject-api-webserver | File "<frozen importlib._bootstrap_external>", line 843, in exec_module myproject-api-webserver | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed myproject-api-webserver … -
Static files are not getting loaded in Django
Static files are not getting loaded when running on server. I have tried the whitenoise library and referred to the Documentation (http://whitenoise.evans.io/en/stable/django.html) as well, but no luck. I am new to Django, would appreciate any help. PS: I have also collected the static folder using- python manage.py collectstatic Below is what I have in my settings.py INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_celery_beat', 'django_extensions', 'haystack', 'users.apps.UsersConfig', 'rest_framework', 'rest_framework.authtoken', 'django_db_logger.apps.DbLoggerAppConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] WSGI_APPLICATION = 'server.wsgi.application' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static")