Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot install Postgis on Heroku CI
I am getting the following error when deploying my app for a test in Heroku: self = <django.db.backends.utils.CursorWrapper object at 0x7f634cc50a00> sql = 'CREATE EXTENSION IF NOT EXISTS postgis', params = None ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0x7f635095d2b0>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0x7f634cc50a00>}) def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: # params default might be backend specific. > return self.cursor.execute(sql) E django.db.utils.OperationalError: could not open extension control file "/app/.indyno/vendor/postgresql/share/extension/postgis.control": No such file or directory .heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py:82: OperationalError I have the following code in my app.json file: { "buildpacks": [ { "url": "https://github.com/heroku/heroku-geo-buildpack.git" }, { "url": "heroku/python" } ], "environments": { "test": { "addons": [ "heroku-postgresql:in-dyno" ], "scripts": { "test": "pytest" } } } } From what I concluded, I see that the error happens when the SQL command 'CREATE EXTENSION IF NOT EXISTS postgis' is executed. -
DjangoAdmin TypeError: '<' not supported between instances of 'str' and 'int'
In a normal python program, I understand what this problem means but I am not able to find the reason behind this error while saving posts from admin in Django. Have I given any invalid data according to field? So while saving it gives the following error: Environment: Request Method: POST Request URL: http://localhost:8000/admin/blog/post/add/ Django Version: 3.2.4 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'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 232, in inner return view(request, *args, **kwargs) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1657, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1540, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1579, in _changeform_view form_validated = form.is_valid() File "/home/prython/2021/Django_thrpracticalGuide/venv/lib/python3.6/site-packages/django/forms/forms.py", line 175, in … -
Why django-mptt shows error: unsupported operand type(s) for -: 'str' and 'str'?
models.py -> class Category(MPTTModel): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) parent = TreeForeignKey( 'self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class MPTTMeta: order_insertion_by = ['title'] class Card(models.Model): categories = TreeManyToManyField(Category, related_name='category_cards', blank=True, default=None) admin.py -> @admin.register(Category) class CategoryAdmin2(DraggableMPTTAdmin): list_display = ('tree_actions', 'indented_title',) list_display_links = ('indented_title',) In admin interface, I get this error: TypeError at /admin/myapp/category/3/change/ unsupported operand type(s) for -: 'str' and 'str' How to solve it? -
PYTHON REQUEST.SESSION VARIABLES ARE DISAPPEARING ON ITS OWN
I am setting a session variables everytime I logged in. The thing is, if I use the local ip '127.0.0.1:8000' to run my python-django web, the session variables is working properly. But if I use my original IP '192.168.2*.***' after I set the value of every session variables, after seconds the variables itself cannot be called, I mean I got an error the session variables isn't declared 'KeyError: username' This is my codes in logging in, I use ajax and replace the document.location.href to Home url if the ajax data returns 'valid' @csrf_exempt def CheckLogin(request): if request.method == 'POST': id = request.POST['id'] query = query_api( "SELECT * FROM user_tbl WHERE employee_id='" + id + "';") if len(query) == 0: return JsonResponse({"data": "Invalid username"}, safe=False) request.session['test'] = "asdjkahsdkjhk" request.session['logged_in'] = True request.session['username'] = id request.session['password'] = "1234" request.session['role'] = query[0]["role"] test = json.dumps(query, indent=4, cls=DateTimeEncoder) return JsonResponse({"data": "valid", "password": test, "role": query[0]["role"]}, safe=False) return JsonResponse({"data": "invalid ajax"}, safe=False) While these are my codes in checking whether it is for log in or already logged-in. @csrf_exempt def CheckifLoggedin(request): if 'logged_in' in request.session: return JsonResponse({"data": "logged_in"}, safe=False) return JsonResponse({"data": "for log-in"}, safe=False) If I try to get the username using this code: username … -
Django Error AttributeError: module 'something' has no attribute 'function'
I am Getting error in changing the Default page of my Django app I am doing it with help of function based view, by importing a function from a view of an app of my project My code in urls.py of project is: from page import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.op1,name='home'), ] Please help me in finding the mistake..... -
How to await a channel_layer.group_send (with @database_sync_to_async) inside a Celery shared_task?
I have a AsyncWebsocketConsumer where one method uses @database_sync_to_async to save the connected user data to the database. Now I want to call this from outside (in a celery shared_task) via channel_layer.group_send. But how can I wait for all the connected users db-operations to go through before continuing the task? Later in the shared_task I want to get all the updated db-records and brodcast it to the same group. I thought a async_to_sync wrapping the channel_layer.group_send would do this. But it sends immediately before all db-operations is done. (A work around is by putting a time.sleep(8) in between but I don't like this approach because I really dont know how long exactly it would take.) -
Django Queries Count and update
I have the following two models ASPBoookings and Athlete. The Athlete model is linked to the ASPBookings model by the foreign key named athlete. I was recently shown queries/subqueries with Views and I have been trying to use them (still learning) to provide a count of all bookings assigned to each athlete within the ASPBookings table. Once I then have the information I need the "number_of_asp_sessions" within the Athlete model to be automatically updated with each of the athletes bookings count. e.g. Athlete ID 1, may have two bookings assigned. Athlete ID 2, may have one booking assigned. The number_of_asp_sessions should then show these numbers for each of the athletes. Hope this makes sense and thanks for advance for any help. Appreciate it. Below is the code: ASPBookings Model class ASPBookings(models.Model): asp_booking_ref = models.CharField(max_length=10, default=1) program_type = models.CharField(max_length=120, default='asp') booking_date = models.DateField() booking_time = models.CharField(max_length=10, choices=booking_times) duration = models.CharField(max_length=10, choices=durations, default='0.5') street = models.CharField(max_length=120) suburb = models.CharField(max_length=120) region = models.CharField(max_length=120, choices=regions, default='Metro') post_code = models.CharField(max_length=40) organisation_type = models.CharField(max_length=120,choices=organisation_types, default='Government School') audience_number = models.CharField(max_length=10) presentation_form = models.CharField(max_length=120, choices=presentation_form_options, default='Face to Face') contact_name = models.CharField(max_length=80) email = models.EmailField() phone_number = models.CharField(max_length=120) comments = models.TextField() status = models.CharField(max_length=80, choices=statuses, default='TBC') email_sent = models.BooleanField(default=False) … -
problem with applying migrations in the project
I want to make a move in my project, I write python3 manage.py makemigrations and I get this error Traceback (most recent call last): File "/Users/work/Projects/ims/api/manage.py", line 21, in <module> main() File "/Users/work/Projects/ims/api/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'corsheaders' for more details on how I arrived at this error, you can go to my previous question [https://stackoverflow.com/questions/68228238/cant-make-migrations/68228429?noredirect=1#comment120585207_68228429] init.py """A pure Python implementation of import.""" __all__ = ['__import__', 'import_module', 'invalidate_caches', 'reload'] # Bootstrap help ##################################################### # Until bootstrapping is complete, DO NOT import any modules that attempt # to import importlib._bootstrap (directly or indirectly). Since this # partially initialised package would be present in sys.modules, those # modules would get an uninitialised copy of the source version, instead # of a fully initialised version (either the frozen one or … -
Django REST API POST to Python script
Is it possible to run a Python script with the POST data as soon as a POST request is triggered or a new entry added to the Django REST API ? I'm very new to Django, please explain in detail for answer. -
Django receiving duplicate signals when updating content from HTML page
I am getting duplicate of each content when updating content from html page. see the picture: I am not getting any duplicate when updating from Django admin panel. How to avoid duplicate when updating from HTML template? here is my code I think I am doing any mistake in my views. here is my views.py class ApproveCommentPage(UpdateView): model = BlogComment template_name = "blog/approve_comment.html" form_class =AdminComment def form_valid(self, form): self.object = form.save() status = self.object.is_published name = self.object.name[0:20] messages.success(self.request, f"{name} comment status {status}") return super().form_valid(form) -
django.db.utils.ProgrammingError: relation "testingland_mapcafes" does not exist
So I am having major Postgres/Django dramas. I kept getting the following error: django.db.utils.ProgrammingError: relation "testingland_mapcafes" does not exist I tried deleting migrations cache, checking and rechecking make migrations, running python3 manage.py migrate testingland zero and then running migrate I have no idea what is going wrong when I check tables in PSQL (db is called vygr) i see the following: Schema | Name | Type | Owner --------+----------------------------+-------+-------------- public | auth_group | table | x public | auth_group_permissions | table | x public | auth_permission | table | x public | auth_user | table | x public | auth_user_groups | table | x public | auth_user_user_permissions | table | x public | django_admin_log | table | x public | django_content_type | table | x public | django_migrations | table | x public | django_session | table | x public | spatial_ref_sys | table | x My settings.py are set up like this: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'vygr', 'USER': 'xxx', 'PASSWORD': 'xxxx', 'HOST': 'localhost', 'PORT': '5432' } } Here is the model in question which does exist but not as a table in my db (yet?): class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = … -
Field 'id' expected a number but got [<django.db.models.sql.query.Query object at 0x000002CFD4506EC8>]
I am building a BlogApp and I am trying to exclude posts with another another model field. BUT when i go to browser then this error is keep showing Field 'id' expected a number but got [<django.db.models.sql.query.Query object at 0x000002CFD4506EC8>]. models.py class Post(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') tags = TaggableManager() class AddFav(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='parent_user') favourite_users = models.ManyToManyField(User, related_name='favourite_users', blank=True) blocked_tags = TaggableManager() views.py def posts(request): block_or_not = AddFav.objects.filter(favourite_users=request.user) exclude_this_list = [] for excluding in block_or_not: exclude_this = excluding.blocked_tags.all() exclude_this_list.append(exclude_this) posts = Post.objects.filter(date_added__lte=now).exclude(tags=exclude_this_list) I have no idea what is wrong in this. Any help would be much Appreciated. Thank You in Advance. -
Django sort by annotate in model Meta
Is there a way to set ordering in a models Meta class by an annotated field? i.e. class ModelA(models.Model): name = models.CharField() class ModelB(models.Model): name = models.CharField() model_a = models.ForeignKey(ModelA) This is what i can do for queryset but need same way to do on class Meta if possible ModalA.objects.all() .annotate( count_b=Count("modal_a") ) .order_by("count_b") -
Creating Django Models
I have been working on Django. But it’s quite new to me can you guys please help me actually I am trying to create a backend work using Django which has 2 models but how do I create I am not able to understand and add it to the admin page. The image shows 2 models 1st model stores the basics over the layout of jobs and while clicking on them it is transferred to the 2nd model which stores detail of that info. Please help me with it code guys. enter image description here -
load csv into sqlite3 db (django)
I am trying to load the csv files I upload to my sqlite3 db. I am able to upload the csv into a folder but it doesn't appear on my db. The db table structure contains as many columns as the csv with the corresponding data types; but the column names in the db table structure are different as in the csv, as some of the columns names in the csv contain spaces and special characters (like accents for example). My goal is to allow the user to upload a csv file that will be loaded to the db. I was also wondering if its possible to increment the db each time a new csv is loaded (for example: I upload a file now which is loaded to the db then the second time I add, the newer details are added to the db without deleting the previous ones). Apologies if I am unclear and asking too many things at once. Here is my model, form, function (handle upload) & views .py files: models.py class UploadForm(models.Model): file = models.FileField() class Meta: db_table = "db_table" forms.py class UploadForm(forms.ModelForm): class Meta: model = UploadForm fields = "__all__" functions.py def handle_uploaded_file(f): with open('vps_app/static/upload/'+f.name, … -
How to access two fields in two separate HTML pages to carry out a JavaScript function in a Django project?
I have two models: class Package(models.Model): rt_number=ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=ForeignKey(Treatment, on_delete=CASCADE) patient_type=ForeignKey(PatientType, on_delete=CASCADE) date_of_admission=models.DateField(default=None) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) class Receivables(models.Model): rt_number=ForeignKey(Patient, on_delete=CASCADE) discount=models.DecimalField(max_digits=9, decimal_places=2, default=None) approved_package=models.DecimalField(max_digits=10, decimal_places=2, default=None) proposed_fractions=models.IntegerField() done_fractions=models.IntegerField() base_value=models.DecimalField(max_digits=10, decimal_places=2) expected_value=models.DecimalField(max_digits=10, decimal_places=2) forms.py: class PackageForm(ModelForm): class Meta: model=Package fields='__all__' widgets={ "patient_type" : forms.Select(attrs={"onblur":"mf();"}), "max_fractions" : forms.NumberInput(attrs={"onfocus":"mf();", "onblur":"tp();"}), "total_package" : forms.NumberInput(attrs={"onfocus":"tp();", "onblur":"onLoad();"}), } class ReceivablesForm(ModelForm): class Meta: model=Receivables fields='__all__' widgets={ "approved_package":forms.NumberInput(attrs={"onfocus":"onLoad();"} ) } views.py: def package_view(request): if request.method=='POST': fm_package=PackageForm(request.POST, prefix='package_form') if fm_package.is_valid(): fm_package.save() fm_package=PackageForm(prefix='package_form') return render (request, 'account/package.html', {'form5':fm_package}) else: fm_package=PackageForm(prefix='package_form') return render (request, 'account/package.html', {'form5':fm_package}) def receivables_view(request): if request.method=='POST': fm_receivables=ReceivablesForm(request.POST) if fm_receivables.is_valid(): fm_receivables.save() fm_receivables=ReceivablesForm() return render(request, 'account/receivables.html', {'form6':fm_receivables}) else: fm_receivables=ReceivablesForm() return render(request, 'account/receivables.html', {'form6':fm_receivables}) templates-package: <!DOCTYPE html> {% load static %} <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>Package Form</title> </head> <body> <form action="" method="post" novalidate> {% csrf_token %} {{form5.as_p}} <button onclick="tots()" type="submit">Save</button> </form> <script src="{% static 'account/js/myjs.js' %}"></script> <script src="{% static 'account/js/test.js' %}"></script> </body> </html> Its source page view for total package field: <p><label for="id_package_form-total_package">Total package:</label> <input type="number" name="package_form-total_package" onfocus="tp();" onblur="onLoad();" step="0.01" required id="id_package_form-total_package"></p> <button onclick="tots()" type="submit">Save</button> templates-receivables: <!DOCTYPE html> {% load static %} <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>Receivables</title> </head> <body> <form action="" method="post"> … -
problem with applying migrations in the project
я хочу сделать миграции в своем проекте, прописываю python3 manage.py makemigrations и получаю такую ошибку Traceback (most recent call last): File "/Users/work/Projects/ims/api/manage.py", line 21, in <module> main() File "/Users/work/Projects/ims/api/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'corsheaders' for more details on how I arrived at this error, you can go to my previous question [https://stackoverflow.com/questions/68228238/cant-make-migrations/68228429?noredirect=1#comment120585207_68228429] init.py """A pure Python implementation of import.""" __all__ = ['__import__', 'import_module', 'invalidate_caches', 'reload'] # Bootstrap help ##################################################### # Until bootstrapping is complete, DO NOT import any modules that attempt # to import importlib._bootstrap (directly or indirectly). Since this # partially initialised package would be present in sys.modules, those # modules would get an uninitialised copy of the source version, instead # of a fully initialised version (either the frozen one or the one # initialised … -
empty pdf is my export result of xhtml2pdf library
empty pdf is my export result of xhtml2pdf library while it works properly on my coworkers machine. I'm defiantly sure that code is not the problem (it works on others machine with exact dependencies and I'm purely using the simple xhtml2pdf's doc example) there is no errors I have dual boot windows10 and I have this result on both my operating systems I even think maybe it's bios thing dajngo 3.0.8 python 3.8 xhtml2pdf 0.2.5 -
Using Barba with Django
My Issue After incorporating Barba js animation library into my Django Project, it started to break. My current login will randomly be logged out when I click on a navigation link. This said navigation link is triggering the animation. My script.js function pageTransition() { var tl = gsap.timeline(); tl.to('#main-wrapper', { duration: 0.1, opacity: 1, transformOrigin: "bottom"}) } function contentAnimation() { var tl = gsap.timeline(); tl.from('#content-wrapper', {duration: 0.8, translateY: 50, opacity: 0}) tl.from('#header-wrapper', {duration: 0.8, translateY: 50, opacity: 0}, "-=0.6") tl.from('#instructions-wrapper', {duration: 0.8, translateY: 50, opacity: 0}, "-=0.6") tl.from('#messages-wrapper', {duration: 0.8, translateY: 50, opacity: 0}, "-=0.6") } function delay(n) { n = n || 2000; return new Promise(done => { setTimeout(() => { done(); }, n); }); } barba.init({ sync: false, transitions: [{ leave(data) { const done = this.async(); pageTransition(); delay(100); done(); }, enter(data) { contentAnimation(); }, once(data) { contentAnimation(); }, }] }) My base.html The nav is redacted but do let me know if you'd like to see the full nav. <body data-barba="wrapper"> <main data-barba="container" role="main" id="main-wrapper" class="container content-wrapper"> <nav> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" data-menu="logout" href="{% url 'logout' %}"> Logout </a> </li> <li class="nav-item"> <a class="nav-link" data-menu="settings" href="{% url 'settings' request.user.userprofile.id %}"> Settings </a> </li> </ul> </nav> … -
Make React pages only visible to authenticated users? (Using Django DRF for backend)
I have my JWT authentication working and I can sign up and log in via my React project, and I want to redirect the authenticated users to the homepage, where the Nav Bar will say 'log out' rather than 'log in' and 'sign up'. In Django, I would just place a {% if user.is_authenticated %} in my template, but I'm not sure how to approach this from React itself. Thanks in advance! -
Django/Docker/Logging: ValueError: Unable to configure handler 'files_debug''
I try to implement logging in my django project (Django/Postgresql/Docker/Celery) but got an error when I deploy my project in linux server (but it work locally) FileNotFoundError: [Errno 2] No such file or directory: '/usr/src/app/logs/debug.log' I've read about a solution in this SO post: Django: Unable to configure handler 'syslog' but fisrt I do not even understand why this solution should works and I do not manage to implement it in my project. I use Docker/docker-compose so I install netcat with Dockerfile and then try to RUN nc -lU /logs/debug.log /logs/info.log but it failed (no such file or directory) Dockerfile # Pull the official base image FROM python:3.8.3-alpine # Set a work directory WORKDIR /usr/src/app # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update && apk add postgresql-dev gcc g++ python3-dev musl-dev netcat-openbsd # create UNIX socket for logs files #RUN nc -lU /logs/debug.log /logs/info.log ... settings.py ... LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'loggers': { 'django': { 'handlers':['files_info','files_debug'], 'propagate': True, 'level':'INFO', }, }, 'handlers': { 'files_info': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': './logs/info.log', 'formatter': 'mereva', }, 'files_debug': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': './logs/debug.log', 'formatter': 'mereva', }, }, 'formatters': { … -
I have a confusion between profile model and User object in Django
forms.py class UserForm(UserCreationForm): ## email = forms.EmailField() class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email'] class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['mobile', 'address', 'image'] models.py class Profile(models.Model): name = models.OneToOneField(User,on_delete=models.CASCADE) mobile = models.IntegerField(null=True) address = models.CharField(max_length=350,null=True) image = models.ImageField(upload_to='profile_pics', default='default.png',null=True) def __str__(self): return str(self.name.username)+' Profile' @receiver(post_save,sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User, dispatch_uid='save_new_user_profile') def save_profile(sender, instance, created, **kwargs): user = instance if created: profile = Profile(user=user) profile.save() views.py @login_required def profile_page(request,name): user = User.objects.filter(username=name) if request.method == 'POST': user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST,request.FILES) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() Profile.objects.create(user=request.user) messages.success(request,'Your profile has been updated successfully!') return redirect('homepage') else: profile_form = ProfileForm() context = { 'user':request.user, 'user_form':user_form, 'profile_form':profile_form, } return render(request,'profile.html',context) Here I have a confusion within the differences in User object and the Profile model that I defined myself. For the fields in Profile that I created is it possible to use together with the UserCreationForm so I do not need to separate two different kinds of forms? Also, could someone help me explain when and how to use the signals in order to create or update the user profile page? Should I provide an instance if … -
Show secret key of django-otp TOTPDevice
I am using django-otp for 2FA on my Django app. In the docs we are given TOTPDevice.config_url, which can be used to generate a QR code or as a link to set up 2FA with Google Auth or similar. How can I get ONLY the secret key from a TOTPDevice object? A workaround would be to get the parameter from the URL, but it sounds odd there is not built-in way to get it? I noticed a TOTPDevice.key which is in hex format, but converting into ascii or utf-8 does not give the correct secret key. -
Django filter when value none or not or certain value
I want to filter my model values. I have three fields. This fields can be null or None or certain value. How to prevent filter error when value null or not: queryset = Info.objects.filter(tag_id=tag.objects.get(pk=tag_id), entryDate__gte=startDate, exitDate__lte=endDate) -
How to pass environment variables to Azure deployment?
I'm trying to get my API to work when deploying to Azure. My problem at the moment is that for some reason my Django app doesn't find the environment variables defined in my be-configmap.yaml -file. It tries to use a .env file (which doesnt exist) when executing python manage.py runserver 0.0.0.0:8000;. Here is my backend-deployment.yaml: apiVersion: apps/v1 kind: Deployment metadata: name: backend spec: replicas: 1 selector: matchLabels: name: backend strategy: {} template: metadata: labels: name: backend spec: containers: - args: - sh - -c - ls; python manage.py makemigrations; python manage.py migrate; python manage.py runserver 0.0.0.0:8000; env: - name: POSTGRES_USER value: xxx - name: POSTGRES_PASSWORD valueFrom: configMapKeyRef: key: DATABASE_PASSWORD name: backendSecrets - name: DATABASE_PASSWORD valueFrom: configMapKeyRef: key: DATABASE_PASSWORD name: backendSecrets image: myappcrwe.azurecr.io/backend:latest imagePullPolicy: Always name: container-backend ports: - containerPort: 8000 restartPolicy: Always serviceAccountName: "" volumes: null status: {} And this is my be-configmap.yaml: apiVersion: v1 kind: ConfigMap metadata: name: backendSecrets data: DEBUG: xxx SECRET_KEY: xxx DATABASE_NAME: xxx DATABASE_USER: xxx DATABASE_PASSWORD: xxx DATABASE_PORT: xxx Could someone look at these if there are some errors why it doesn't fin the variables?