Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I sync a docker volume to update when my local files are updated? Django, nginx
Sorry, it seems like answered question, but I couldn't find not outdated solution or the one that could help me (especially with django). I have to manually re-make volume so my docker server will update. My php friend told me I should make a synchronized volume, but I just don't understand how compose.yml volumes services: back: volumes: - blog-django:/usr/src/app - blog-static:/usr/src/app/static nginx: volumes: - blog-static:/usr/src/app/static db: volumes: - pgdata:/var/lib/postgresql/data/ volumes: blog-django: blog-static: pgdata: Project copied in volume by COPY . . -
Page not found (404)The current path, {% url 'post_detail' post.pk % }, didn’t match any of these
[hi i am new to django and i am facing a problem when using primary keys.project name is blog project and app is blog this is my code.] this is the screenshot of the error when i click on a heading:1 please help me #blog/urls.py from django.urls import path from .views import BlogListView,BlogDetailView urlpatterns = [ path("post/<int:pk>/",BlogDetailView.as_view(),name = "post_detail"), path('', BlogListView.as_view(), name = "home"), ] #blog/templates/home.html {% extends 'base.html' %} <style> .post-entry{ color:antiquewhite; } </style> {% block content %} {% for post in object_list %} <div class = "post-entry"> <h2><a href = "{% url 'post_detail/' post.pk % }">{{post.title}}</a></h2> <p>{{post.body}}</p> </div> {% endfor %} {% endblock content %} -
Can we add add objects to django queryset like we do to python list. I have an empty django queryset, now I want to add objects to it
This is how I have initialized an Empty Queryset now I want to add objects to it. How can I do that. from django.db.models.query import EmptyQuerySet -
Get requests are regularly (every 2 s) sent on / when enabling SSL with a Django app
I have a dockerized Django application which is working well on port 80. nginx is running on my server with a basic rule, catching traffic on port 80 and redirecting it to the exposed port of my app container. Everything works fine. Now I enabled SSL, added a listen 443 default_server ssl; to my nginx server, but from now, my container logs are showing, every 2 seconds, requests like this: djangotutorial-app-1 | 2022-10-06T14:58:29.131231656Z Not Found: / djangotutorial-app-1 | 2022-10-06T14:58:29.133263459Z [06/Oct/2022 14:58:29] "GET / HTTP/1.0" 404 2167 ... so it's bloating the logs. This didn't happen without SSL. As I don't know where to search from here, because there is obviously no error message or whatever useful information, I would be glad if someone has an idea on how to debug that. -
no such table: main_uploadfile after uploading file
I have a django app. and I try to upload image. So I have this view.py: from .forms import ProfileForm from .models import UploadFile # Create your views here. """ def store_file(file): with open("temp/hello.png", "wb+") as dest: for chunk in file.chunks(): dest.write(chunk) """ class CreateProfileView(View): def get(self, request): form = ProfileForm() return render(request, "main/create_profile.html", { "form": form }) def post(self, request): submitted_form = ProfileForm(request.POST, request.FILES) if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) uploadfile.save() return HttpResponseRedirect("/main") return render(request, "main/create_profile.html", { "form": submitted_form }) and this form.py: class ProfileForm(forms.Form): upload_file = forms.FileField() and this model.py: class UploadFile(models.Model): image = models.FileField(upload_to="images") and yes, I did this: python manage.py makemigrations and python manage.py migrate that created this file: class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='UploadFile', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.FileField(upload_to='images')), ], ), ] but still after uploading I get this error: OperationalError at / no such table: main_uploadfile Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 4.1.1 Exception Type: OperationalError Exception Value: no such table: main_uploadfile Exception Location: C:\Python310\lib\site-packages\django\db\backends\sqlite3\base.py, line 357, in execute Raised during: main.views.CreateProfileView Python Executable: C:\Python310\python.exe Python Version: 3.10.6 Python Path: ['C:\\Users\\engel\\Documents\\NVWA\\software\\blockchainfruit\\schoolfruitnvwa', 'C:\\Python310\\python310.zip', 'C:\\Python310\\DLLs', 'C:\\Python310\\lib', 'C:\\Python310', 'C:\\Python310\\lib\\site-packages'] Server time: Thu, 06 Oct 2022 … -
Django: How to use User ModelForm for log in?
I'm trying to use a modelForm for a login rather than a Form (to avoid repetition): class LoginForm(forms.ModelForm): class Meta: model = get_user_model() widgets = { "password": forms.PasswordInput(), } fields = ("email", "password") However, since the email field has a unique=True, and since forms can be used to create objects, when running is_valid() method on the form, I get an error: User with this E-mail already exists. What is the right way to handle this? Thanks. -
Docker on windows Vmmem grows with each rebuild of container
I have a Django + Gunicorn + Nginx website running in a docker container on windows 10 that's been working wonderfully. Every time that I update my source code I run the following command to rebuild the container: docker-compose up -d --build [servicename] This runs as expected, builds the container detached and then swaps them out when complete, Nginx stays running and looses connection for a second then boom, back up and running. Ill do this maybe 5-20 times a week depending on what I'm adding/fixing and pushing to production. the issue that I just came across was that the Vmmem process is growing by a factor of 1 each time, so when I run docker-compose up for the first time, memory usage will be about 3,000MB. When I run my rebuild, it will grow to 6,000 MB. and on and on.... Since the system I'm running on has 32GB of RAM, I didn't notice the mass amount of buildup until a few months in of running. Is this normal behavior from docker? and if so is there anything I can do to to alleviate the build up other than restarting the computer? -restarting docker does not solve the issue … -
django filter by fields that can change
I have this model : class Project(models.Model): state = models.CharField(max_length=7, default='#FFFF00') name = models.CharField(max_length=200, default="") price = models.FloatField(default=0) decision = models.TextField(blank=True, null=True) For example, if I want to filter all the projects named 'hello_project' with a price of 10, I can do this : projects = Project.objects.filter(Q(name='hello_project') & Q(price=10)) What I want to do is filter by lists that can change : fields = ["name", "price"] filters = ["hello_project", 10] Is there a way to do something like this that works ? (lists size can change) : projects = Project.objects.filter(Q({fields[0]}={filters[0]}) & Q({fields[1]}={filters[1]}) I've done this: def filter_projects(fields, filters): all_projects = Project.objects.all() filtered_projects = [] for i in range(len(fields)): for project in all_projects: if str(functions[fields[i]](project)) == str(filters[i])): filtered_projects.append(project) all_projects = filtered_projects filtered_projects = [] return all_projects It works but it's very long with a lot of projects so I want to know if I can do this in one line -
Annotating frequency of many to many objects in a query (Django)
I'm trying to annotate a product reports with the frequency at which a product appears on the report. I have the below so far which works, but it's counting the frequency products appear across all users reports, rather than the specific user. BarcodeScanProduct's are linked via m2m to barcodescanproduct and Products are linked by foreign key to BarcodeScanProduct's. user = request.user report, created = BarcodeScanReport.objects.get_or_create(user=user, complete=False) report_products = report.barcodescanproduct_set.all( ).annotate(instance_count=Count('product__barcodescanproduct__id') ).order_by('-product__status') Any ideas? -
Why do I get this TypeError in Django Cloudinary when running Debug=False?
So I have this Django project using django-cloudinary-storage for media files, deployed with Heroku. I know it's silly but I've been running the app with Debug=True. Everything was fine, all static and media files were served perfectly. But then I realized doing so is critical to the security of my app, so I re-deployed it with Debug=False. This is when I got this error message saying TypeError: expected str, bytes or os.PathLike object, not NoneType (Full traceback at the bottom) Let me show you my settings.py. I don't see what I've done wrong, but I keep getting the error. What do you think is the problem? (...) STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_STORAGE = 'cloudinary_storage.storage.StaticHashedCloudinaryStorage' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CLOUDINARY_STORAGE = { 'CLOUD_NAME' : '', # some string 'API_KEY' : config("CLOUDINARY_API_KEY"), 'API_SECRET' : config("CLOUDINARY_API_SECRET"), } DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' And I also have this in my urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Full traceback. Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/opt/homebrew/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/ryanoh/Projects/crysenv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) … -
Django models - inherit from two classes: each with a custom Manager?
I've got an issue where I have a Model that is inheriting from two other AbstractModel classes. Both of the AbstractModel use a custom Manager to to point all queries to a particular database. Here is the first Model: # appA / models.py class AbstractA(models.Model): objects = managers.AManager() class Meta: abstract = True # appA / managers.py class AManager(models.Manager): def get_queryset(self): return super(AManager, self).get_queryset().using("database_a") This is the secondary Model that I utilize in order to do 'soft deletions' (from this article) # appA / models.py class ASoftDeletionModel(models.Model): deleted_at = models.DateTimeField(blank=True, null=True) objects = SoftDeletionManager() all_objects = SoftDeletionManager(alive_only=False) class Meta: abstract = True def delete(self): self.deleted_at = timezone.now() self.save() def hard_delete(self): super(ASoftDeletionModel, self).delete() # appA / managers.py class SoftDeletionManager(models.Manager): def __init__(self, *args, **kwargs): self.alive_only = kwargs.pop("alive_only", True) super(SoftDeletionManager, self).__init__(*args, **kwargs) def get_queryset(self): if self.alive_only: return ( SoftDeletionQuerySet(self.model) .using("database_a") .filter(deleted_at=None) ) return SoftDeletionQuerySet(self.model).using("database_a") def hard_delete(self): return self.get_queryset().using("database_a").hard_delete() class SoftDeletionQuerySet(models.QuerySet): def delete(self): return super(SoftDeletionQuerySet, self).update( deleted_at=timezone.now(), using="database_a", ) def hard_delete(self): return super(SoftDeletionQuerySet, self).delete(using="database_a") def alive(self): return self.using("database_a").filter(deleted_at=None) def dead(self): return self.using("database_a").exclude(deleted_at=None) I've created another simple model for making comments on a thing that inherits from both of those models like so: class Comment( ASoftDeletionModel, AbstractA ): thing = models.ForeignKey( Thing, on_delete=models.PROTECT, related_name="%(class)ss" ) … -
How can I get count of pages in LimitOffsetPagination django rest framework?
If my code looks like this: class SimpleLimitOffsetPagination(LimitOffsetPagination): offset_query_param = 'page' max_limit = 100 default_limit = 5 def get_paginated_response(self, data): return Response({ 'count': self.count, 'max_page': 'needs count of pages', 'results': data }) Is that possible to get count of pages? or do we have another solution? It's important to have an opportunity using limit filed. -
Problem with add and change instanse in django admin
I try from admin to add or change instance of model - CompletedWork. Error is: TypeError at /admin/ReportingTool/completedwork/68/change/ init() missing 1 required positional argument: 'user' my model: class CompletedWork(models.Model): period = models.ForeignKey(directory.Period, on_delete=models.SET('deleted date'), ) worker = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET('deleted worker'), related_name='worker_do', default=settings.AUTH_USER_MODEL ) work_done = models.ForeignKey(directory.WorksType, on_delete=models.SET('deleted works type')) work_scope = models.FloatField(blank=True, null=True) work_notes = models.CharField(_("Comments"), max_length=70, blank=True, null=True, ) record_author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET('deleted user'), related_name='record_author', auto_created=True, ) record_date = models.DateTimeField(auto_now=True) checked_by_head = models.BooleanField(default=False) active = models.BooleanField(default=True) def __repr__(self): return f'{self.period}, {self.worker}, {self.work_done}' def __str__(self): return self.__repr__() def is_active(self): if self.active: return True return False my form: class CompletedWorkForm(forms.ModelForm): class Meta: model = CompletedWork fields = ( 'period', 'worker', 'work_done', 'work_scope', 'work_notes', ) def __init__(self, user, *args, **kwargs): if kwargs.get('record_author'): self.user = kwargs.pop('record_author') super(CompletedWorkForm, self).__init__(*args, **kwargs) if user.struct_division: if user == user.struct_division.head: self.fields['worker'] = forms.ModelChoiceField( queryset= CustomUser.objects.filter(struct_division= user.struct_division).order_by('last_name') | CustomUser.objects.filter(struct_division__management_unit= user.struct_division).order_by('last_name') ) elif StructuralDivisions.objects.filter(curator=user): sd_user_curator = StructuralDivisions.objects.filter(curator=user) self.fields['worker'] = forms.ModelChoiceField( queryset= CustomUser.objects.filter(struct_division__in=sd_user_curator) | CustomUser.objects.filter(id=user.pk) ) else: self.fields['worker'] = forms.ModelChoiceField( queryset=CustomUser.objects.filter(id=user.pk) ) self.fields['work_done'] = forms.ModelChoiceField( queryset=WorksType.objects.filter(available_to=user.struct_division) ) def save(self, commit=True): obj = super(CompletedWorkForm, self).save(commit=False) if commit: obj.user = self.instance.record_author obj.save() return obj my view: class EditCompletedWorkView(LoginRequiredMixin, SuccessMessageMixin, UpdateView): model = CompletedWork form_class = CompletedWorkForm template_name = 'completed_work_edit.html' context_object_name = … -
Using the URLconf defined in , Django tried these URL patterns, in this order:
I have a django app. And some upload functionaliteit. The page with the upload function is loading correct. But after I do a submit. I get this errror: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/main/ Using the URLconf defined in schoolfruitnvwa.urls, Django tried these URL patterns, in this order: admin/ The current path, main/, didn’t match any of these. so this is the views.py from .forms import ProfileForm from .models import UploadFile # Create your views here. """ def store_file(file): with open("temp/hello.png", "wb+") as dest: for chunk in file.chunks(): dest.write(chunk) """ class CreateProfileView(View): def get(self, request): form = ProfileForm() return render(request, "main/create_profile.html", { "form": form }) def post(self, request): submitted_form = ProfileForm(request.POST, request.FILES) if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) uploadfile.save() return HttpResponseRedirect("/") return render(request, "main/create_profile.html", { "form": submitted_form }) urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.CreateProfileView.as_view()) ] forms.py: class ProfileForm(forms.Form): upload_file = forms.FileField() So my question is: what I have to change? -
Django to Postgres connection issues on AWS server
I'm setting up an Amazon AWS test server with Django on which I use Postgres as a database. This was my way here: $ sudo apt update $ sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib I downloaded my files from Github and created a virtual environment for it and inside I installed psycopg2. $ pip install psycopg2 How I configured Postgres: $ sudo -i -u postgres $ psql $ createuser --interactive (super user); $ createdb Filme; Some other information that may be useful about Postgres: $ service postgresql status > postgresql.service - PostgreSQL RDBMS Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset:> Active: active (exited) since Wed 2022-10-05 17:08:25 UTC; 20h ago Main PID: 977 (code=exited, status=0/SUCCESS) CPU: 1ms Oct 05 17:08:25 ip-172-31-29-151 systemd[1]: Starting PostgreSQL RDBMS... Oct 05 17:08:25 ip-172-31-29-151 systemd[1]: Finished PostgreSQL RDBMS. $ pg_lsclusters > Ver Cluster Port Status Owner Data directory Log file 14 main 5432 online postgres /var/lib/postgresql/14/main /var/log/postgresql/postgresql-14-main.log In my settings.py file of my project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'Filme', } } O erro ocorre quando eu tento rodar a migração para o novo banco de dados: $ (env) $ python3 manage.py migrate > Traceback (most recent call last): File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/backends/base/base.py", … -
Is it possible to use ImageFields from other models via inheritance? (django)
I have two models with imageFields, and want to have the same images there, to display them at the admin-page... My two models: class Produkt(models.Model): STATUS_CHOICES = ( ('draft', 'offline'), ('published', 'online'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') image = models.ImageField(upload_to='images', height_field=None, width_field=None, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') class Meta: ordering = ('-publish',) def __str__(self): return self.title objects = models.Manager() published = PublishedManager() def get_absolute_url(self): return reverse('app:produkt_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) tags = TaggableManager() class Bestellung(models.Model): def two_week_hence(): return timezone.now() + timezone.timedelta(weeks=2) produkt = models.ForeignKey(Produkt, on_delete=models.CASCADE, related_name='bestellung') def get_image(self): return self.produkt.image versand_bis = models.DateTimeField(default=two_week_hence) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'hat Produkt {self.produkt} bestellt' and my admin.py looks like this: @admin.register(Produkt) class ProduktAdmin(admin.ModelAdmin): def image_tag(self, obj): return format_html('<img height="100" src="{}" />'.format(obj.image.url)) image_tag.short_description = 'Image' list_display = ('title', 'image_tag', 'image', 'kategorie', 'price', 'publish', 'status') list_filter = ('created', 'publish', 'status', 'price',) search_fields = ('title',) prepopulated_fields = {'slug': ('title',)} date_hierarchy = 'publish' @admin.register(Bestellung) class BestellungAdmin(admin.ModelAdmin): def image_tag(self, obj): return format_html('<img height="100" src="{}" />'.format(obj.get_image.url)) image_tag.short_description = 'Image' list_display = ('produkt', 'image_tag', 'versand_bis', 'created', 'active') list_filter = … -
how can I import one model from one app to another?, been doing it the standard way but its not working [closed]
This is the directory layout/related files and settings: When I run migrations I get this error message : I just want to import the group class from the models.py in group directory to my post models.py. I have tried many changes to the structure of the import code with no success. I tried : from simplescoial.groups.models import Groups This seems to have no issue with Pycharm (no red underlines and picks up autocomplete at all stages) but on the terminal I get a NoModuleFoundError it cant find simplesocial.groups. -
Creating a single-column dataframe in Pandas from a Django queryset
I'm trying to create a dataframe containing the values from field_1 and field_2 in a single column. I haven't used pandas a whole lot before, so I'm sure this is naive. # Create a dataset in CSV format field_names = ["work_description", "comments"] writer = csv.writer(open("dataset.csv", "w"), quoting=csv.QUOTE_ALL, delimiter=",") writer.writerow(field_names) for instance in WorkOrder.objects.all(): writer.writerow([str(getattr(instance, f)) for f in field_names]) # Read CSV data_frame = pd.read_csv("dataset.csv", index_col=0) # Combine columns df2 = data_frame.apply(lambda x: ", ".join(x[x.notnull()]), axis=1) If I'm working with a fairly large dataset, is there a way I can make this more efficient? I would like to eliminate the step that creates the CSV entirely, if possible. If anybody can point me in the right direction, that'd be fantastic. -
Django Error: __init__() takes 1 positional argument but 2 were given
I am new to Django and I'm trying to create my first project following a tutorial from Udemy, but I encounter this error. My project has the following folder structure: -demo __ init__.py admin.py apps.py models.py tests.py urls.py -views.py -first __ init__.py asgi.py settings.py urls.py wsgi.py views.py: from django.shortcuts import render from django.http import HttpRequest def first(request): return HttpRequest('1st message from views') demo/urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.first), ] first/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('demo/', include('demo.urls')), path('admin/', admin.site.urls), ] Both __ init__.py files are empty error: TypeError at /demo/ __init__() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/demo/ Django Version: 3.2.16 Exception Type: TypeError Exception Value: __init__() takes 1 positional argument but 2 were given Exception Location: D:\Python\DJANGO\first-project\demo\views.py, line 6, in first Python Executable: D:\Python\DJANGO\first-project\venv\Scripts\python.exe Python Version: 3.7.6 Python Path: ['D:\\Python\\DJANGO\\first-project', 'D:\\Python\\DJANGO\\first-project', 'C:\\Users\\biavu\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip', 'C:\\Users\\biavu\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\biavu\\AppData\\Local\\Programs\\Python\\Python37\\lib', 'C:\\Users\\biavu\\AppData\\Local\\Programs\\Python\\Python37', 'D:\\Python\\DJANGO\\first-project\\venv', 'D:\\Python\\DJANGO\\first-project\\venv\\lib\\site-packages'] Server time: Thu, 06 Oct 2022 12:34:45 +0000 -
Im getting error 'str' object has no attribute 'status_code' [closed]
I've seen every thread i could find for that problem and there a acutally quite a lot but i cant figure out the problem. Im trying some unit testing on one of my django views. It used to pass the test but now it breaks and prints: AttributeError: 'str' object has no attribute 'status_code' unit test: def test_delete_flight(self): self.client.force_login(self.user) response = self.client.get('/agriculture/delete_flight/' + str(self.flight)) self.assertEqual(response.status_code, 302) self.assertRedirects(response.url, '/agriculture/flights') The error occurs on assertEqual for some reason. I tried printing out response.status_code, 302 and everything seems normal, its basically (302, 302) so i cant figure out where it is breaking. error ERROR: test_delete_field Traceback (most recent call last): File "/home/dukis/Documents/agrominds/src/agriculture/tests/test_views.py", line 329, in test_delete_flight self.assertRedirects(response.url, '/agriculture/flights') File "/home/dukis/Documents/venv-agrominds/lib/python3.10/site-packages/django/test/testcases.py", line 358, in assertRedirects response.status_code, status_code, AttributeError: 'str' object has no attribute 'status_code' -
Heroku : (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)"
I am trying to deploy my django app on heroku. While deploying I am getting this error. I am not sure if there is something wrong with my settings file or heroku setup. Python 3.10, Django 4.1.2 Here is the database settings I am using import dj_database_url DATABASES = { 'default': dj_database_url.config(conn_max_age=500) } This is the database url from heroku config DATABASE_URL: postgres://ewdtekjzxnzuuo:b16a983b5c9cfb7fe1f9aaab58f1ac21bea073fdb059c0fa7356600c4a19030b@ec2-34-200-205-45.compute-1.amazonaws.com:5432/da0ttf53ppludi Error message -> MySQLdb.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 97, in handle self.check(databases=[database]) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 475, in check all_issues = checks.run_checks( File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/model_checks.py", line 36, in check_all_models errors.extend(model.check(**kwargs)) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/base.py", line 1533, in check *cls._check_indexes(databases), File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/base.py", line 1952, in _check_indexes connection.features.supports_expression_indexes File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/functional.py", line … -
How to delete virtual environment completely on Docker?
I am trying to make a Django and Postgre container using docker-compose. I followed this tutorial: https://docs.docker.com/samples/django/. I am using Windows and executed the following command: docker-compose run web django-admin startproject composeexample . After that, I modified my Dockerfile to include some apt-get update # syntax=docker/dockerfile:1 FROM python:3 RUN apt-get update RUN apt-get install -y libgdal-dev ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /usr/src/app COPY requirements.txt /usr/src/app/ RUN pip install -r requirements.txt COPY . /usr/src/app/ I deleted the created composeexample folder and data folder, and run the command again. docker-compose run web django-admin startproject composeexample . This time. I get the following error: CommandError: /usr/src/app/manage.py already exists. Overlaying a project into an existing directory won't replace conflicting files. ERROR: 1 Somehow Docker thinks the files still exist from the 1st execution. Even if I change the name of the parent directory to change the container name, I still get the error. How can I remove the environment completely from my 1st execution? -
Django RetrieveAPIView where is the rights place to do some small db update
I'm using Django REST framework, and still quite new to it.. I Want to retrieve a message from db with generics.RetrieveAPIView method, which I did.. But I want to also set the read field to true at the database. Where is the place to do it (maybe in the serializer)? This is the idea: class MessageDetail(generics.RetrieveAPIView): serializer_class = MessageSerializer permission_classes = [IsAuthenticated] queryset = AppUserMessage.objects.all() AfterTheRequst(self) # This is what I want to do obj.read_at = time.now() -
Django, no module named 'polls' - Django reusable apps
I am at the end of the getting started of the Django project, I built the package as described in the Advanced tutorial: How to write reusable apps. I got a tar.gz file that I installed not in a virtual environment using the command python.exe -m pip install --user C:\Users\[PRIVACY AMEND]\Documents\python\mysite\django-polls\dist\django-polls-0.1.tar.gz. The module is installed as shown in the output of python.exe -m pip list below. Package Version ------------ ------- asgiref 3.5.2 Django 4.1.1 django-polls 0.1 lxml 4.9.1 sqlparse 0.4.2 tzdata 2022.2 But when I migrate, I get the error no module named polls... I have done all steps of the tutorial on Windows and Debian (on WSL), using explicitly python.exe -m pip when interacting with pip, checked the logs for any other error, and checked the PYTHONPATH and where the package is installed given by python.exe -m pip show django-polls, the output is just below. Name: django-polls Version: 0.1 Summary: A Django app to conduct web-based polls. Home-page: https://www.example.com/ Author: Your Name Author-email: yourname@example.com License: BSD-3-Clause # Example license Location: c:\users\[PRIVACY AMEND]\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages Requires: Django Required-by: Does anyone have a hint ? -
encrypt and decrypt Django rest framework field as superuser?
I read the answers here: plaintext API secret and have read about encryption and decryption of API keys and secrets. In django Rest Framework, 1- store the API key and Secret in plain text in Django REST framework DB. 2- An endpoint, only accessible by superuser(I could limit this further to IP address), gives all users API keys and secrets to be used in another script. TLS communication. I am not sure if this is the best approach.