Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sentry is working on local but not working in server
I'm troubled with the sentry, I configured sentry in my Django application it's working fine and an error arrives in sentry UI from localhost, but in the same case, I run from the server it's not working, and no error arrives into sentry UI. DEBUG=False ALLOWED_HOSTS = ["*"] sentry_sdk.init( dsn="https://sentry-url", integrations=[DjangoIntegration(), CeleryIntegration(), RedisIntegration()], # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. # We recommend adjusting this value in production. traces_sample_rate=1.0, # If you wish to associate users to errors (assuming you are using # django.contrib.auth) you may enable sending PII data. send_default_pii=True, ) -
Not correct scope for accessing events
HttpError at /calendar <HttpError 403 when requesting https://www.googleapis.com/calendar/v3/calendars/primary/events?singleEvents=true&orderBy=startTime&alt=json returned "Request had insufficient authentication scopes.". Details: "[{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficientPermissions'}]"> Request Method: GET Request URL: http://localhost:8000/calendar Django Version: 3.2.9 Exception Type: HttpError Exception Value: Then does this after a while RefreshError at /calendar The credentials do not contain the necessary fields need to refresh the access token. You must specify refresh_token, token_uri, client_id, and client_secret. It seems I don't possess the right scope when accessing the calendar and it seems currently the access_token does appear. from google.oauth2.credentials import Credentials def get_user_events(request): credentials = Credentials(get_access_token(request), scopes=SCOPES) service = googleapiclient.discovery.build('calendar', 'v3', credentials=credentials) google_calendar_events = service.events().list(calendarId='primary', singleEvents=True, orderBy='startTime').execute() google_calendar_events = google_calendar_events.get('items', []) return google_calendar_events def get_access_token(request): social = request.user.social_auth.get(provider='google-oauth2') return social.extra_data['access_token'] -
attach domain name with lightsail instense and django
I have created static ip in lightsail and attached it to the django instanse. I bought domain name from godaddy. I then created domain zone in lightsail and created 2 DNS records type "A" with the following: @.drmahahabib.com www.drmahahabib.com Then i copied the name servers from the same page for my lightsail then took that to godaddy site and changed the name servers there. Now i get the page that confirms that the lightsail is working but not the site instense of django. do i need to do some modification? below is the screenshot or just visit the webpage. my site -
how go through and see the library source code
hello friends i code django and python in pycharm for a company .i have 2 project in one of them i can see the source code of django and django rest framework with "command + mose over" and in another one it doesnt work with django and other libraries except my code and python source code. i mean i can see the source of os in "import os " but i cant see and go through the for example "from rest_framework import authentication".... the senior tell me maybe the place of the env file ....I do not know what to do? can anyone help me ? this is the location of my "venv" and "bime" is the name of the project place of env and project -
django admin The outermost 'atomic' block cannot use savepoint = False when autocommit is off
When I try to delete an item from a table generated by django admin, it throws this error Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/sybase_app/packageweight/?q=493 Django Version: 1.8 Python Version: 3.6.9 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'sybase_app') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/home/pd/.local/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper 616. return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 110. response = view_func(request, *args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/contrib/admin/sites.py" in inner 233. return view(request, *args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 34. return bound_func(*args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 110. response = view_func(request, *args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func 30. return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/pd/.local/lib/python3.6/site-packages/django/contrib/admin/options.py" in changelist_view 1590. response = self.response_action(request, queryset=cl.get_queryset(request)) File "/home/pd/.local/lib/python3.6/site-packages/django/contrib/admin/options.py" in response_action 1333. response = func(self, request, queryset) File "/home/pd/.local/lib/python3.6/site-packages/django/contrib/admin/actions.py" in delete_selected 49. queryset.delete() File "/home/pd/.local/lib/python3.6/site-packages/django/db/models/query.py" in delete 537. collector.delete() File "/home/pd/.local/lib/python3.6/site-packages/django/db/models/deletion.py" in delete 282. with transaction.atomic(using=self.using, savepoint=False): File "/home/pd/.local/lib/python3.6/site-packages/django/db/transaction.py" in __enter__ 164. "The outermost 'atomic' block cannot use " Exception Type: TransactionManagementError at /admin/sybase_app/packageweight/ Exception Value: The outermost 'atomic' block cannot use savepoint = False when autocommit is off. How can I … -
Rewrite website from PHP YII to Python Django [closed]
Good afternoon. We have a corporate website at work, with a lot of data for a couple of years. It is written in PHP YII, my task now is to rewrite it in Python Django. The database is PosgresSQL, it has data coming in automatically and is generally well designed, so I want to keep it. Bottom line: What's the best way to rewrite the site in python and keep the old database. It turns out I will need to rewrite the models suitable for this database. Maybe there is some methodology for this? -
How to create two docker compose containers on one server
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 8a58a0898843 repo.com/test_nginx_dev "..." 3 seconds ago Up 2 seconds 80/tcp, 0.0.0.0:9000->9000/tcp test_nginx_dev a1fzd92a1c9d repo.com/test_django_dev "..." 3 seconds ago Up 2 seconds 8080/tcp, 0.0.0.0:8100->8100/tcp test_django_dev CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 7516491ae772 repo.com/test2_nginx_dev "..." 7 seconds ago Up 5 seconds 0.0.0.0:80->80/tcp test2_nginx_dev 59a344089c51 repo.com/test2_django_dev "..." 7 seconds ago Up 6 seconds 8080/tcp test2_django_dev First, test2_nginx_dev and test2_django_dev were created with docker-compose. After that, if I create test_nginx_dev and test_django_dev with docker-compose test2_nginx_dev and test2_django_dev disappear. how do i solve it -
how solve Error when run django app on server of heroku?
i create django app and now i run it on heroku app my procfile and other thing are as follow. but when i build it on heroku then it succesfully uploaded but not run on website. this app is run in localhost is good but not at online hear is procfile web: waitress-server --port=$PORT todoapp.wsgi:application hear is last logs 2022-01-24T07:20:24.200304+00:00 app[api]: Deploy 5e0ae6c8 by user zeelmehta.zm31@gmail.com 2022-01-24T07:20:24.200304+00:00 app[api]: Release v10 created by user zeelmehta.zm31@gmail.com 2022-01-24T07:20:33.000000+00:00 app[api]: Build succeeded 2022-01-24T07:20:40.938065+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=todoapp-zeel.herokuapp.com request_id=81d8bb3e-5f6c-4f37-8be0-90508cebef10 fwd="157.32.119.168" dyno= connect= service= status=503 bytes= protocol=https 2022-01-24T07:20:41.630709+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=todoapp-zeel.herokuapp.com request_id=87aff06b-aff3-4846-9abc-95b1db51d632 fwd="157.32.119.168" dyno= connect= service= status=503 bytes= protocol=https 2022-01-24T07:20:55.134817+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=todoapp-zeel.herokuapp.com request_id=9a920057-d443-4404-badd-493951c0c196 fwd="157.32.119.168" dyno= connect= service= status=503 bytes= protocol=https 2022-01-24T07:20:55.760932+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=todoapp-zeel.herokuapp.com request_id=0f0b6bfc-2181-4eb0-b0af-8e444058b163 fwd="157.32.119.168" dyno= connect= service= status=503 bytes= protocol=https``` please help me to solve this error -
How to change the file name when uploading an image field in Django
When uploading an image field (media file) in Django, it asks about renaming the file. The page url to upload the image contains the pk of the foreign key. I want to rename the image file to {pk}.png when uploading an image. When the code below works, it is saved as none. What's the problem? [urls.py] app_name = 'dataroom' urlpatterns = [ path('det/<int:research_id>/', views.detData, name='DataDet'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) [models.py] import .utils import rename_imagefile_to_uuid class protocol_upload(models.Model): trial = models.ForeignKey(Research, on_delete=models.SET_NULL, blank=True, null=True) protocol_file = models.FileField(upload_to='protocol/', null=True, blank=True) clusion= models.ImageField(upload_to='criteria/clusion/', null=True, blank=True) reference = models.ImageField(upload_to=rename_imagefile_to_uuid, storage=OverwriteStorage(), null=True, blank=True) def image_save(self, *args, **kwargs): if self.id is None: saved_image = self.reference self.reference = None super(protocol_upload, self).save(*args, **kwargs) self.reference = saved_image super(protocol_upload, self).save(*args, **kwargs) def __str__(self): return str(self.trial) [utils.py] import os from uuid import uuid4 def rename_imagefile_to_uuid(instance, filename): upload_to = 'reference/' ext = filename.split('.')[-1] uuid = uuid4().hex if instance: filename = '{}.{}'.format(instance.id, ext) else: filename = '{}.{}'.format(uuid, ext) return os.path.join(upload_to, filename) [views.py] def detData(request, research_id): research = Research.objects.get(id=research_id) protocol = protocol_upload.objects.all() for reference in request.FILES.getlist('reference'): protocol = protocol_upload() protocol.research = research_id protocol.reference = reference protocol.save() context = { 'protocol': protocol, 'research': research, } return render(request, '/detail.html', context) [detai.html] <form method="POST" action="{% url 'dataroom:DataDet' research_id=research.id … -
What is the average cost of hosting a django app?
Due to current RBI guidelines on recurring payments for standing instructions I am unable to use Heroku which is great for small apps. Therefore I have to choose other platoforms. I have narrowed down my choice to two platforms aws and digital ocean. overview of my django website : The website which I made for my client is not that big. In this website a user registers, chooses some plan and then book an intructor to teach him/ her driving. A user after loging in has to accept an agreement and also has an udate plan page. Thats it on the user side. Now I use celery which uses redis, to send emails such as otp, registration successful, change password, contracts and updated contracts (the contracts' email are send both to the client and the user as per the clients demand). As you can see I have to use celery and redis because there is a lot email work that has to be done by the website. And the database i am using is Postgresql. Now comming to traffic, we cannot predict what will be the number of visitors on the site, but we accept maximum of 10 registrations per … -
Displaying the Custom model field in the Post method
I am facing some problems regarding Django-Rest-Framework, post method. There are two things I want to accomplish: Adding fields in the view of the Post method. --> Here instead of sending the data in Json format, I want to replace the filed names with the Custom model's fields And when using '@renderer_classes([BrowsableAPIRenderer])' decorator in a view, the view page shows '[No renderers were found]'. Here are snippets of my code and the screenshots of the errors I got... serializers.py class CreateTodoSerailizer(serializers.ModelSerializer): class Meta: model = Todos fields = ('title', 'user', 'desc', 'todo_date', 'is_completed',) def save(self): todo = Todos( title = self.validated_data['title'], user = self.validated_data['user'], desc = self.validated_data['desc'], todo_date = self.validated_data['todo_date'], is_completed = self.validated_data['is_completed'], ) todo .save() return todo models.py class Todos(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) title = models.CharField(max_length=30) slug = models.SlugField(max_length=50, blank=True) desc = models.TextField(blank=True) date_created = models.DateTimeField(auto_now_add=True) todo_date = models.DateField(default=date.today) is_completed = models.BooleanField(default=False) class Meta: verbose_name = _("Todos") verbose_name_plural = _("Todos") ordering = ['-date_created'] def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) return super(Todos, self).save(*args, **kwargs) views.py @api_view(['POST']) def createTodo(request, format=None): if request.method == 'POST': serializer = CreateTodoSerailizer(data=request.data) data = {} if serializer.is_valid(): todo = serializer.save() data['response'] = 'Successfully added' data['title'] = todo.title data['username'] = todo.user … -
Creating a database using python and Django and populating that database from HubSpot API Data
I am trying to populate the database using HubSpot's Companies API data. I have created a table in models.py. In views.py file I have called API data, however I am not able to save that data in the Database. I do not understand if there an issue in my code or anything else? your help on this task would be really appreciated. views.py def index(request): url = "https://api.hubapi.com/companies/v2/companies?" headers = {} r = requests.get(url = url, headers ={'Authorization':'Bearer %s' %os.getenv('access_token')}) try: response_dict = json.loads(r.content) companies_list= response_dict['companies'] for company in companies_list: Company.update_or_create( companyID = company['companyId'], sourceID = company['sourceId'], portalID = company['portalId'], country = company['country'] ) except Exception as e: response_dict= "Data not found:" return render(request, 'Apihub/index.html', {'response_dict': response_dict} In models class: models.py class Company(models.Model): companyID = models.CharField(max_length=50, blank=True, null=True) sourceID = models.CharField(max_length=20, blank=True, null=True) portalID = models.IntegerField(default=0) country = models.CharField(max_length=50, blank=True, null=True) -
Django forms hidden field value assignation with a var after 'forms.is_valid()' doesn't save it
I have a form with an hidden input called social_color where I want nothing in, I need this input to assign a value after validating the form content to use one of the field content to do stuff and then assign the results to the hidden input. According to this answer: https://stackoverflow.com/a/813474/15352101 I can simply do : if form.is_valid(): form.cleaned_data['Email'] = GetEmailString() but for me using : form.cleaned_data["social_color"] = icon_main_color icon_main_color is the results of the stuff I had to do, it's a tuple containing 3 values but when I check the created object with the form, the value of social_color is still empty. -
Adding a variable in Django templates static tag {% %} enclosure
I have a project in Django Python. And, I am trying to figure out how to add a variable in a {% %} enclosure I'ved got variables set in this way: CP_ENV_SMALLAPPNAME_CAPITALIZE <-- meta title variable CP_ENV_FAVICON_PATH <-- favicon variable path <title>{{ CP_ENV_SMALLAPPNAME_CAPITALIZE }}</title> <-- this works <link rel="icon" type="image/png" sizes="16x16" href="{% static 'img/{{CP_ENV_FAVICON_PATH}}/favicon-16x16.png' %}"> <--- this doesnt work How can I insert CP_ENV_FAVICON_PATH into {% static %} enclosure in django ? -
storing large data into mongodb collection using python
I am working on a Django project where I have to create 10 years of data and store them in MongoDB retrieve it and display it on the HTML page. I am trying to divide 10 years of data into 1 year and then store it in MongoDB collection but whenever I try to do so only two documents get stored and this error is shown in pymongo. errors.DocumentTooLarge: BSON document too large (29948865 bytes) - the connected server supports BSON document sizes up to 16793598 bytes. my python code is now=start workdate=now.date() nowtime=now.time() endt=end ktime=start times=[] states=[] level=[] #generating random level of water in the tank while (now!=endt): # loop for creating data for given time ktime=ktime+relativedelta(months=5) print(current_level) def fill(): global df global now global workdate global nowtime global ktime global current_level global flag global times global states global level while x=='on' and current_level<=450: times.append(now) states.append(x) level.append(current_level) current_level+=filling current_level=round(current_level,2) now=now+timedelta(minutes=1) nowtime=now.time() workdate=now.date if now==ktime: times.append(now) states.append(x) level.append(current_level) print("true") flag='red' break def drain(): global df global now global workdate global nowtime global ktime global current_level global flag global times global states global level while x=='off' and current_level>50: times.append(now) states.append(x) level.append(current_level) print(current_level) current_level-=emptyrate current_level=round(current_level,4) now=now+timedelta(minutes=1) nowtime=now.time() workdate=now.date() if now==ktime: times.append(now) states.append(x) … -
How to send array of django model objects in post api?
class Product(models.Model): name = models.CharField(max_length=255) class Image(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to="images") class ProductViewSet(ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer How can I make my serializer and views? My post api request payload will be: [{"name":"Laptop", "images":[array of image files]}, {"name":"Shoes", "images":[array of images]}] -
Telegram Oauth2 with Django
I am exploring ways to send telegram messages to the users using Telegram bot from my Django application. The bot should be able to initiate the conversation - these messages are more like alerts and updates but not conversations. From Telegram developer documentation I could not find a standard OAuth2 implementation with Telegram to get access tokens for sending messages to the users using REST APIs. Does anyone know Oauth flow implementation for Telegram if at all it exists Sending messages using API - I am not planning to run a bot server. The messages just need to be pushed to the user - more like push notifications. Appreciate your help. -
Annotating the value difference from given Time Range Django
Considering a simple model class Event(models.Model): title = models.CharField(max_length=100) amount = models.IntegerField() What I want to achieve I'm trying to somehow use annotate to give me the difference b/w the last_entry(created for event) - first_entry(created for event) and ignore the rest in between I think we should be able to do this but if not possible please provide basis of telling so and thanks in advance -
why uploaded files is not deleting
I am new in Django, Here I have added a correct code but it is not deleting the file. Please help me someone. views.py: def control_upload(request): if request.method == 'POST': form = ControlForm(request.POST, request.FILES) if form.is_valid(): model_instance = form.save() model_instance.save() else: form = ControlForm() controlmachiness = Controlmachine.objects.all() return render(request,'usermaster/control_uploadfile.html',{'form':form,'controlmachiness':controlmachiness}) def control_index(request): controlmachines = Controlmachine.objects.all() return render(request,"usermaster/control_show.html",{'controlmachines':controlmachines}) def control_destroy(request, id): if request.method == 'POST': controlmachine = Controlmachine.objects.get(id=id) controlmachine.delete() return HttpResponseRedirect('/usermaster/controlfile/') models.py: class Controlmachine(models.Model): machine_name = models.CharField(max_length=100) operation_no = models.IntegerField() control_uploadfile = models.FileField(upload_to='control_files/') class Meta: db_table = "controlmachine" def delete(self, *args, **kwargs): self.machine_name.delete() self.operation_no.delete() self.control_uploadfile.delete() super.delete(*args, *kwargs) forms.py: class ControlForm(forms.ModelForm): class Meta: model = Controlmachine fields = ['machine_name', 'operation_no', 'control_uploadfile'] #https://docs.djangoproject.com/en/3.0/ref/forms/widgets/ widgets = { 'machine_name': forms.TextInput(attrs={ 'class': 'form-control' }), 'operation_no': forms.TextInput(attrs={ 'class': 'form-control' }), 'control_uploadfile': forms.ClearableFileInput(attrs={ 'class': 'form-control' }), } urls.py: path('controlfile/',views.control_index,name='control_index'), path('cdelete/<int:id>',views.control_destroy,name='control_destroy'), path('controlupload/',views.control_upload,name='control_upload'), path('upload/',views.upload,name='upload'), path('save',views.save_machine,name='save_machine'), control_show.html: {% extends 'usermaster/home.html' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script> </head> {% block body %} <body> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="table-responsive"> <table id="bootstrapdatatable" class="table table-striped table-bordered" width="90%"> <thead> <th><input type="checkbox" id="checkall" /></th> <th>ID</th> <th>Machine Name</th> <th>Operation Number</th> <th>File</th> <th>Delete</th> </thead> <tbody> … -
Error when running heroku run manage.py migrate
If you run python manage.py migrate in Heroku, python: can't open file 'manage.py': [Errno 2] No such file or directory I am getting this error. How can I fix this error? If i run heroku run ls accounts config db.sqlite3 manage.py media photo Procfile requirements.txt runtime.txt templates rqueirments.txt asgiref==3.5.0 dj-database-url==0.5.0 Django==3.2.11 django-heroku==0.3.1 django-storages==1.12.3 gunicorn==20.1.0 Pillow==9.0.0 psycopg2==2.9.3 psycopg2-binary==2.9.3 pytz==2021.3 sqlparse==0.4.2 typing-extensions==4.0.1 whitenoise==5.3.0 Procfile `web: gunicorn config.wsgi` runtime `python-3.7.12` -
New superuser unable to log in to CMS
I'm new to Wagtail and django. I've completed the https://learnwagtail.com/wagtail-for-beginners/ course and managed to get my site up and running on Digital ocean, however I'm unable to login to the admin area. I have tried using the superuser credentials that were used locally. I have also tried multiple times to create a new superuser with: python manage.py createsuperuser and while the process appears to work successfully in the terminal (I'm logged in via SSH to my DO droplet), I continually receive the 'Your username and password didn't match. Please try again.' message when attempting to log in with the newly created username and password. If I use the shell to check users I can see my newly created user exists. I have also tried using python manage.py changepassword myusername to change the password on the previously created superusers, but again, while the process appears to work successfully in the terminal I continue to receive the error message when attempting to log in. Can anyone point me in the right direction as to what I might be missing or doing wrong here? And / or how I might best debug the issue? Thanks in advance! -
Error while adding records by admin panel django
So, lately I have been using Termux app in my android device to build django app. while I was using admin panel it opened but when I tried to add any records in my database tables through it It just prompted this error in the Termux terminal. Internal Server Error: /admin/travello/destination/add/ Traceback (most recent call last): File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/core/files/move.py", line 61, in file_move_safe locks.lock(fd, locks.LOCK_EX) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/core/files/locks.py", line 111, in lock fcntl.flock(_fd(f), flags) OSError: [Errno 38] Function not implemented During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/contrib/admin/options.py", line 622, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/contrib/admin/sites.py", line 236, in inner return view(request, *args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1670, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1549, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1599, in … -
List Class View didn't return an HttpResponse
I've been trying to get a class-based list view to display all entries under a user's account (applicant), but when loading the page I'm given the following error: The view jobassessment.views.view didn't return an HttpResponse object. It returned None instead. To me that sounds like the URL dispatcher isn't running the correct view, but this is my URL file for both the whole site and the jobassessment application and I can't seem to spot the fault. Site URL.py: urlpatterns = [ path('admin/', admin.site.urls, name="admin"), path('accounts/', include('django.contrib.auth.urls'), name="accounts"), path('applicant/', include('userprofile.urls'), name="applicant"), path('assessments/', include('jobassessment.urls')), ] JobAssessment App's URL.py: from django.urls import path from . import views urlpatterns = [ path("", views.AssessmentListView.as_view(), name="assessment"), ] This is my ListView that is called: class AssessmentListView(LoginRequiredMixin, generic.ListView): model = Assessment template_name ='assessments_index.html' paginate_by = 5 def get(self, request, *args, **kwargs): # Ensure they have first created an Applicant Profile if not Applicant.objects.filter(user=self.request.user).exists(): messages.info(request, "You must create a profile before you can view any assessments.") return redirect('profile_create_form') def get_queryset(self): return Assessment.objects.all().filter(applicant=Applicant.objects.filter(user=self.request.user)).order_by('-assessment_stage') -
selenium test doesn't display static files and data objects
Everything works perfectly on the local server and in the production but when trying to run the selenium test, the static files don't load. Even created data objects been displayed on the template is not also displayed. Here are the static setting in the settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' -
How to make auto-genertion(auto-fill and increment) in django admin
I want to make code field should be auto filled and auto increment in django admin. models.py class GeneralDocumentType(models.Model): code = models.CharField(max_length=10, null=False, unique=True) name = models.CharField(max_length=100, null=False, unique=True) description = models.TextField(blank=True, null=True) def __str__(self): return self.name I want to show my code field default=DOC001, and it will show increment by 1 before adding data by user.How can I achieve this?..