Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Images in django not showing up in react
This is an application in which I'm using django backend and react frontend. The images display in react when I keep react and django separate and communicate simply with the APIs. However, I want to deploy both the frontend and backend together. I'm trying to use django re_path to redirect any url that does't match with the urls specifiled in django urls.py. Whenever I do this the images from react and django stop displaying. Both django and react lose track of the path of the images. project structure >backend ... settings.py urls.py >blog ... urls.py serializers.py views.py >frontend ... build src package.json manage.py >static urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('djoser.urls')), path('api/', include('djoser.urls.jwt')), path('api/', include('accounts.urls')), path('summernote/',include('django_summernote.urls')), path('api/blog/', include('blog.urls')), re_path('*', TemplateView.as_view(template_name='index.html')), ] settings.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'frontend/build') ], 'APP_DIRS': True, }, ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static',), os.path.join(BASE_DIR, 'frontend/build/static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Also, whenever I use re_path to redirect unmatched urls from django to react the images in react such as the logo stop displaying but withouy setting re_path all the images in react, … -
Django - How to add annotation to queryset for request.user
I want to add new field to queryset (by annotate()) according to request.user. I have following models: class Tweet(models.Model): ... class Like(models.Model): tweet = models.ForeignKey(Tweet, related_names='likes') user = models.ForeignKey(AUTH_USER_MODEL, related_name='my_likes') type = models.CharField( choices=( ('like', _"Like"), ('dislike', "Dislike") ), ... ) Now I want to execute following query: tweets = Tweet.objects.all().annotate(user_reaction=some_method(request.user)) And I want to this annotated_field(user_reaction), reaction of user to the tweet. user_reaction has 3 states: 1- Like 2- Dislike 3- None (user hasn't like/dislike the tweet) I want to have something like tweets[10].user_reaction, and after that get one of 3 states that came before. (just like, dislkie or None) How can I do this? thanks. -
What would be the best design to manage multiple markets
I have one project, frontend used as Angular and backend used as Django. The project was used for multiple markets, for example, Japan, Mexico, Canada, etc. The database data columns vary for all markets and also the feature is changed for all the markets. For this reason, we have kept the code in different branches like master_uk, master_jp etc. Here is the problem: if I have any issues with the base code. I need to fix all the branches and test all the markets. If I manage one code for all the markets and configurable(Need to think). if I move any change to one market that might be affecting all other markets. What would be the best design to manage multiple markets? -
I get an invalid hosts error when installing ssl certification on django web app [closed]
recently I’ve launched a web app and I went through the process of installing an ssl certificate through the command prompt. While the site is shown as secure, I get a constant invalid hosts error despite including the domain name and IP address in the allowed hosts list in settings.py. Can anyone who has gone through this before guide me on what to do? Thank you! -
Repository does not have a Release file. for Ubuntu 16.04
Here in my dev server i am upgrading from python 2.7 to python 3.7 when using the command python --version 2.7.14 python3 --verison 3.5.2 python3.7 --version 3.7.10 and when running the command sudo apt-get update this is what i am getting Err:15 https://dl.bintray.com/rabbitmq/debian xenial/main amd64 Packages 502 Bad Gateway Fetched 325 kB in 4s (78.1 kB/s) Reading package lists... Done W: The repository 'https://dl.bintray.com/rabbitmq/debian xenial Release' does not have a Release file. N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use. N: See apt-secure(8) manpage for repository creation and user configuration details. E: Failed to fetch https://dl.bintray.com/rabbitmq/debian/dists/xenial/main/binary-amd64/Packages 502 Bad Gateway E: Some index files failed to download. They have been ignored, or old ones used instead. here is Output of cat /etc/apt/sources.list ## Note, this file is written by cloud-init on first boot of an instance ## modifications made here will not survive a re-bundle. ## if you wish to make changes you can: ## a.) add 'apt_preserve_sources_list: true' to /etc/cloud/cloud.cfg ## or do the same in user-data ## b.) add sources in /etc/apt/sources.list.d ## c.) make changes to template file /etc/cloud/templates/sources.list.tmpl # See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to # newer versions … -
How does one include static information as part of a Django Model?
I have spent the last few hours trying to create something which I thought would have been very trivial, but alas, it was not… I am creating a Django model that asks the user a random question from a list: prompts. Inside my models.py file I have: from django.db import models from .prompts import prompts class Entry(models.Model): question = str(random.choice(prompts)) answer = models.CharField(max_length=240) I'm using the generic CreateView to create the a form, and my views.py contains the following: from django.views.generic.edit import CreateView from .models import Entry class NewEntry(CreateView): model = Entry success_url = reverse_lazy('detail') fields = ['question', 'answer'] Everything migrates correctly, but when I navigate to the relevant page in the browser, Django complains: FieldError at /create/ | Unknown field(s) (question) specified for Entry I understand that question is not a field per se, but I do need it to be saved as part of the Entry instance so that in the future I may read both the answer and the question that was asked at the time. Naturally, I also need it to display in a template as part of the form which is produced by CreateView. Setting the question to be a CharField that is uneditable also … -
Django with pandas
I want display dataframe with info from pandas df.info() this display to output in the command prompt but in html display None !! Views.py my_file = pd.read_csv(filename, engine='python') data = pd.DataFrame(data=my_file) mydict = { "data": data.to_html(), "dinfo": data.info(), } <div><h6 class="major">Data </h6>{{data|safe}}</div> <div><h6 class="major">Data Info:</h6>{{dinfo|safe}}</div> -
Django-AWS S3, unable to delete bucket objects
I have a Django project with MySQL storage and media objects (images) are being stored in AWS S3 simple storage. Admin can upload images through admin panel and its being displayed in website too. When admin delete objects , it gets deleted in MySQL but it's associated images persists in S3 bucket. SETTINGS.PY AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' AWS_STORAGE_BUCKET_NAME = '' AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.me-south-1.amazonaws.com" AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'news.storage_backends.MediaStorage' STORAGE_BACKENDS.PY from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class MediaStorage(S3Boto3Storage): location = 'media' default_acl = 'public-read' file_overwrite = False I am user details as attached, -
How to implement Djnago-internation into models
I need to make dropdownlist using currency name of all countries. I found documents which are not mentioned how to use properly. international.models.currencies This is atuple of tuples compatible with choices argument passed to Django’s model/form fields. The values are ISO 4217 3-letter currency codes, and display values are the same codes with full currency names. For example: ('USD', 'USD - United States Dollar') This tuple is used as choices argument for the ChoicesField in the currency form. here i have given link: https://pypi.org/project/django-international/ Please, If anyone knows how to do just do reply,.. -
Show number of items in Django in list view
I am trying to show the number of each category in Leads. But i am unable to show it. Appriciate your help. I am learning django and python. Tried many opiton, but failed. Below is my code. Model: class Leads(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) age = models.IntegerField(default=0) orginasation = models.ForeignKey(UserProfile, on_delete=models.CASCADE) agent = models.ForeignKey("Agent",null=True, blank= True ,on_delete=models.SET_NULL) category = models.ForeignKey("Category", related_name="leads", on_delete= models.SET_NULL, null=True, blank=True) def __str__(self): return f"{self.first_name} {self.last_name}" class Category(models.Model): name = models.CharField(max_length=30,) # New, Contact, Converted, Unconverted orginasation = models.ForeignKey(UserProfile, on_delete=models.CASCADE) def __str__(self): return self.name View: class CategoryListView(LoginRequiredMixin, generic.ListView): template_name = "leads/category_list.html" context_object_name = "category_list" def get_queryset(self, **kwargs): user = self.request.user #initial query set for entire organisation if user.is_organisor: queryset = models.Category.objects.filter(orginasation=user.userprofile) else: queryset = models.Category.objects.filter(orginasation=user.agent.orginasation) # count = models.Leads.objects.filter(category = 3).count() return queryset template {% for category in category_list %} <tr> <td>{{category.name}}/td> <td>{{category.count}}</td> </tr> {% endfor %} -
Django ORM Optimal solution for bulk stock data store?
i am working on django project in my project i am have created models product,branch,stock i and one of database server there to i am fetch 4 lack around records of stock data and storing in my project database but problem is i am storing through orm its taking 50 min to storing 4 lac records is there best solution to reduce the time. you can see below model class which i am storing stock data. thankyou i advance. class Stock(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) branch = models.ForeignKey(Branch, on_delete=models.CASCADE, null=True, blank=True) quantity = models.PositiveIntegerField(default=1) updated_on = models.DateTimeField(blank=True, null=True) created = models.DateTimeField(editable=False,blank=True, null=True) updated = models.DateTimeField(editable=False,blank=True, null=True) -
Uploading a `FileField` to a specific folder in Django Python
How can I use the django FileField to upload the file to the specified folder directly without going through the admin panel or using the form for normal user? -
How to detect and get the changes from past 24 hours in database using django?
I am having around 5000 user records and I also have an external intercom API for posting user data. Every time I run that API it takes hours to complete because it has to compare every user again and again to insert the created or updated data in the database. so, I wanted to send the latest created or updated data from the database to an external API like an intercom. -
How to get variables between the curly brackets in django template in django views?
I have django template file. Now i want to get all the variables list that are between curly brackets. I think it is possible with the regular expressions. And i read about regular expressions. But there is no function i found to be helpful. template code snippet: <tr><td> Dear Candidate,<br/> Welcome to Creative Talent Management!<br/> We have created an account for you. Here are your details:<br/> Name:{{name}}<br/> Email:{{email}}<br/> Organization:{{organization}}<br/> Password:{{password}}<br/> </td></tr> I want to get name,email,organization,password in my python function. -
django - Unable to set delimiter in raw sql (MySQL)
I want to define a stored procedure by a migration. Before this I'm trying to set delimiter but getting django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER $$' at line 1") Code: from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('...', '...'), ] operations = [ migrations.RunSQL("DELIMITER $$"), # ... migrations.RunSQL("DELIMITER ;"), ] I've found information about DELIMITER is a client keyword which might not be supported by specific tool but what is the right way in django? -
Django: one of pages is not opening
I have created two pages locally for Django site: http://127.0.0.1:8080/portfolio/ http://127.0.0.1:8080/about_me/ when I want to open "http://127.0.0.1:8080/about_me/" always opens this one "http://127.0.0.1:8080/portfolio/". Do you know reason for this? project urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('portfolio/', include('blog.urls')), path('about_me/', include('blog.urls')), ] app urls.py: from . import views from django.urls import path from django.conf.urls import include urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('about_me/', views.Portfolio.as_view(), name='about_me'), path('portfolio/', views.Portfolio.as_view(), name='portfolio'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), path('summernote/', include('django_summernote.urls')), ] # to jest dla wysiwyg # add condition in django urls file from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) -
Wagtail isssues: ImportError: cannot import name 'filter_page_type' from 'wagtail.admin.views.chooser'
I upgraded to Wagtail==2.15.2 and Django==3.0.5 When I run python manage.py runserver I get the error below Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/me/.local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/me/.local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/me/.local/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = self._run_checks( File "/home/me/.local/lib/python3.8/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/home/me/.local/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/me/.local/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/me/.local/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/me/.local/lib/python3.8/site-packages/django/urls/resolvers.py", line 407, in check for pattern in self.url_patterns: File "/home/me/.local/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/me/.local/lib/python3.8/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/me/.local/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/me/.local/lib/python3.8/site-packages/django/urls/resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line … -
JSONField filter doesn't show up anything
I am trying to filter a JSONField database according to the country code of the database objects. I have the following JSON dictionary in my JSON field database: "[{\"date\":\"2020-01-01\",\"localName\":\"Neujahr\",\"name\":\"New Year's Day\",\"countryCode\":\"DE\",\"fixed\":true,\"global\":true,\"counties\":null,\"launchYear\":1967,\"type\":\"Public\"},{\"date\":\"2020-01-06\",\"localName\":\"Heilige Drei K\u00f6nige\",\"name\":\"Epiphany\",\"countryCode\":\"DE\",\"fixed\":true,\"global\":false,\"counties\":[\"DE-BW\",\"DE-BY\",\"DE-ST\"],\"launchYear\":1967,\"type\":\"Public\"},{\"date\":\"2020-03-08\",\"localName\":\"Internationaler Frauentag\",\"name\":\"International Women's Day\",\"countryCode\":\"DE\",\"fixed\":true,\"global\":false,\"counties\":[\"DE-BE\"],\"launchYear\":2019,\"type\":\"Public\"},{\"date\":\"2020-04-10\",\"localName\":\"Karfreitag\",\"name\":\"Good Friday\",\"countryCode\":\"DE\",\"fixed\":false,\"global\":true,\"counties\":null,\"launchYear\":null,\"type\":\"Public\"},{\"date\":\"2020-04-12\",\"localName\":\"Ostersonntag\",\"name\":\"Easter Sunday\",\"countryCode\":\"DE\",\"fixed\":false,\"global\":false,\"counties\":[\"DE-BB\",\"DE-HE\"],\"launchYear\":null,\"type\":\"Public\"},{\"date\":\"2020-04-13\",\"localName\":\"Ostermontag\",\"name\":\"Easter Monday\",\"countryCode\":\"DE\",\"fixed\":false,\"global\":true,\"counties\":null,\"launchYear\":1642,\"type\":\"Public\"},{\"date\":\"2020-05-01\",\"localName\":\"Tag der Arbeit\",\"name\":\"Labour Day\",\"countryCode\":\"DE\",\"fixed\":true,\"global\":true,\"counties\":null,\"launchYear\":null,\"type\":\"Public\"},{\"date\":\"2020-05-08\",\"localName\":\"Tag der Befreiung\",\"name\":\"Liberation Day\",\"countryCode\":\"DE\",\"fixed\":false,\"global\":false,\"counties\":[\"DE-BE\"],\"launchYear\":null,\"type\":\"Public\"},{\"date\":\"2020-05-21\",\"localName\":\"Christi Himmelfahrt\",\"name\":\"Ascension Day\",\"countryCode\":\"DE\",\"fixed\":false,\"global\":true,\"counties\":null,\"launchYear\":null,\"type\":\"Public\"},{\"date\":\"2020-05-31\",\"localName\":\"Pfingstsonntag\",\"name\":\"Pentecost\",\"countryCode\":\"DE\",\"fixed\":false,\"global\":false,\"counties\":[\"DE-BB\",\"DE-HE\"],\"launchYear\":null,\"type\":\"Public\"},{\"date\":\"2020-06-01\",\"localName\":\"Pfingstmontag\",\"name\":\"Whit Monday\",\"countryCode\":\"DE\",\"fixed\":false,\"global\":true,\"counties\":null,\"launchYear\":null,\"type\":\"Public\"},{\"date\":\"2020-06-11\",\"localName\":\"Fronleichnam\",\"name\":\"Corpus Christi\",\"countryCode\":\"DE\",\"fixed\":false,\"global\":false,\"counties\":[\"DE-BW\",\"DE-BY\",\"DE-HE\",\"DE-NW\",\"DE-RP\",\"DE-SL\"],\"launchYear\":null,\"type\":\"Public\"},{\"date\":\"2020-08-15\",\"localName\":\"Mari\u00e4 Himmelfahrt\",\"name\":\"Assumption Day\",\"countryCode\":\"DE\",\"fixed\":true,\"global\":false,\"counties\":[\"DE-SL\"],\"launchYear\":null,\"type\":\"Public\"},{\"date\":\"2020-09-20\",\"localName\":\"Weltkindertag\",\"name\":\"World Children's Day\",\"countryCode\":\"DE\",\"fixed\":true,\"global\":false,\"counties\":[\"DE-TH\"],\"launchYear\":2019,\"type\":\"Public\"},{\"date\":\"2020-10-03\",\"localName\":\"Tag der Deutschen Einheit\",\"name\":\"German Unity Day\",\"countryCode\":\"DE\",\"fixed\":true,\"global\":true,\"counties\":null,\"launchYear\":null,\"type\":\"Public\"},{\"date\":\"2020-10-31\",\"localName\":\"Reformationstag\",\"name\":\"Reformation Day\",\"countryCode\":\"DE\",\"fixed\":true,\"global\":false,\"counties\":[\"DE-BB\",\"DE-MV\",\"DE-SN\",\"DE-ST\",\"DE-TH\",\"DE-HB\",\"DE-HH\",\"DE-NI\",\"DE-SH\"],\"launchYear\":null,\"type\":\"Public\"},{\"date\":\"2020-11-01\",\"localName\":\"Allerheiligen\",\"name\":\"All Saints' Day\",\"countryCode\":\"DE\",\"fixed\":true,\"global\":false,\"counties\":[\"DE-BW\",\"DE-BY\",\"DE-NW\",\"DE-RP\",\"DE-SL\"],\"launchYear\":null,\"type\":\"Public\"},{\"date\":\"2020-11-18\",\"localName\":\"Bu\u00df- und Bettag\",\"name\":\"Repentance and Prayer Day\",\"countryCode\":\"DE\",\"fixed\":false,\"global\":false,\"counties\":[\"DE-SN\"],\"launchYear\":null,\"type\":\"Public\"},{\"date\":\"2020-12-25\",\"localName\":\"Erster Weihnachtstag\",\"name\":\"Christmas Day\",\"countryCode\":\"DE\",\"fixed\":true,\"global\":true,\"counties\":null,\"launchYear\":null,\"type\":\"Public\"},{\"date\":\"2020-12-26\",\"localName\":\"Zweiter Weihnachtstag\",\"name\":\"St. Stephen's Day\",\"countryCode\":\"DE\",\"fixed\":true,\"global\":true,\"counties\":null,\"launchYear\":null,\"type\":\"Public\"}]" So, when I run Database.objects.first().data I get exactly that and it's all good. I have the JSONField defined in the models.py of my Django application: from django.db import models class Database(models.Model): data = models.JSONField() However, when I run Database.objects.filter(data__countryCode = "DE") I get <QuerySet []>, and when I also put .data, it says that 'QuerySet' object has no module data. How can I get the filter to work for this database? -
How to fetch data from postgres existing tables to Django?
I have a Postgres Database and it has plenty of tables in it, using Django I need to query or get all the table rows into my views.py. After reading I understood that creating a model in models.py will create a new table into my DB which is not what I need. Is using django a good way to fetch data from postgres or should I use the python library to communicate with postgres directly (psycopg2)? If django has a way to fetch data from table then how do I do it? -
Installing gettext in virtual environment of shared hosting
I made a multilingual django website and I am deploying it to shared hosting. I should install gettext to virtual environment. I have read about gettext is not python package so I can't install it using pip. Is there any way to install gettext in virtual environment of shared hosting? I can't use sudo because I don't have root access. -
Heroku deploys succesfully then throws a Server Error (500)
I have been painstakingly trying to get my app deployed on Heroku. I have reached a point where the app appears to deploy successfully but when I follow the link I get a page that just says Server Error (500) Running heroku logs --tail I get this traceback: [...] 2022-01-19T11:33:08.121453+00:00 app[web.1]: [2022-01-19 11:33:08 +0000] [4] [INFO] Starting gunicorn 20.1.0 2022-01-19T11:33:08.121895+00:00 app[web.1]: [2022-01-19 11:33:08 +0000] [4] [DEBUG] Arbiter booted 2022-01-19T11:33:08.121927+00:00 app[web.1]: [2022-01-19 11:33:08 +0000] [4] [INFO] Listening at: http://0.0.0.0:13184 (4) 2022-01-19T11:33:08.121962+00:00 app[web.1]: [2022-01-19 11:33:08 +0000] [4] [INFO] Using worker: sync 2022-01-19T11:33:08.125067+00:00 app[web.1]: [2022-01-19 11:33:08 +0000] [9] [INFO] Booting worker with pid: 9 2022-01-19T11:33:08.140667+00:00 app[web.1]: [2022-01-19 11:33:08 +0000] [10] [INFO] Booting worker with pid: 10 2022-01-19T11:33:08.154835+00:00 app[web.1]: [2022-01-19 11:33:08 +0000] [4] [DEBUG] 2 workers 2022-01-19T11:33:08.414085+00:00 heroku[web.1]: State changed from starting to up 2022-01-19T11:33:09.177223+00:00 app[web.1]: [2022-01-19 11:33:09 +0000] [9] [DEBUG] Closing connection. 2022-01-19T11:33:09.178680+00:00 app[web.1]: [2022-01-19 11:33:09 +0000] [9] [DEBUG] Closing connection. 2022-01-19T11:33:09.737656+00:00 app[web.1]: [2022-01-19 11:33:09 +0000] [10] [DEBUG] GET / 2022-01-19T11:33:10.635903+00:00 app[web.1]: 10.1.82.87 - - [19/Jan/2022:11:33:10 +0000] "GET / HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36" 2022-01-19T11:33:10.636610+00:00 heroku[router]: at=info method=GET path="/" host=vygrapp.herokuapp.com request_id=752a8ffc-7f35-41b7-b052-dcc8a093364e fwd="175.45.149.67" dyno=web.1 connect=0ms service=899ms status=500 bytes=611 protocol=https [...] I have … -
reverting a RemoveField migration (django.db.utils.IntegrityError)
Im trying to revert a migration by migrating to previous migration but i got this error: django.db.utils.IntegrityError: column "field_name" contains null values this problem occurs when a migrations.RemoveField is in the migration which is reverted to. when the migration is reverting a field by null=False is created. How can i resolve the problem? -
Migrations doesn't starts for dockerized Django project
I've created e simple hello world project with Django and Docker. At the end of Dockerfile there is the command below: ENTRYPOINT ["/app/web/entrypoint.sh"] that activate this script: #!/bin/sh echo " ---> DB Connection Parameters: \ DB name: $DB_NAME \ DB host: $DB_HOST \ DB port: $DB_PORT" poetry run python3 website/manage.py migrate --noinput poetry run python3 website/manage.py collectstatic --noinput poetry run python3 website/manage.py createsuperuser --noinput echo " ---> Django Project Port: $PROJECT_PORT" poetry run python3 website/manage.py runserver 0.0.0.0:"$PROJECT_PORT" exec "$@" The project starts but the migration isn't run and I'm forced to log inside the container and use python3 manage.py migrate to start the migration. Why the migration command doesn't run and collectstatic runs automatically? Below the docker-compose: version: '3.7' services: db: container_name: dev_db image: postgis/postgis restart: always environment: POSTGRES_PASSWORD: ${DB_PASSWORD} POSTGRES_USER: ${DB_USER} POSTGRES_DB: ${DB_NAME} volumes: - db-data:/var/lib/postgresql/data website: image: maxdragonheart/${PROJECT_NAME} build: context: ./web dockerfile: Dockerfile environment: PROJECT_NAME: ${PROJECT_NAME} PROJECT_PORT: ${PROJECT_PORT} SECRET_KEY: ${SECRET_KEY} DB_ENGINE: ${DB_ENGINE} DB_NAME: ${DB_NAME} DB_USER: ${DB_USER} DB_PASSWORD: ${DB_PASSWORD} DB_PORT: ${DB_PORT} DB_HOST: ${DB_HOST} DEBUG: ${DEBUG} ALLOWED_HOSTS: ${ALLOWED_HOSTS} container_name: dev_website restart: always ports: - ${PROJECT_PORT}:${PROJECT_PORT} volumes: - website-static-folder:/app/web/static-folder - website-media-folder:/app/web/media-folder - logs:/app/logs depends_on: - db volumes: db-data: website-static-folder: website-media-folder: logs: -
how to write a signal to change a field in a model after another filed from another model is changed
I have a user model that has to go through several tasks such as completing their information, taking some tests, and interviews. So I added a progress level field that shows the user status at the moment. this is my model: class User(AbstractUser): id = models.AutoField(primary_key=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) isPreRegistered = models.BooleanField(default=False) role = models.CharField(max_length=25, null=True, choices=USER_ROLE_CHOICES, default=USER_ROLE_CHOICES[0][0]) role_id = models.CharField(max_length=10, default='applicant') username = models.CharField(unique=True, max_length=13) first_name = models.CharField(max_length=32, null=True, default=None) last_name = models.CharField(max_length=64, null=True, default=None) gender = models.CharField(max_length=10, null=True) personalInfo = models.OneToOneField(PersonalInfo, on_delete=models.CASCADE, null=True) contactInfo = models.OneToOneField(ContactInfo, on_delete=models.Case, null=True) eliteInfo = models.OneToOneField(EliteInfo, on_delete=models.CASCADE, null=True) progress_level = models.CharField(max_length=25, null=True, choices=USER_PROGRESS_LEVELS, default=USER_PROGRESS_LEVELS[0][0]) and there are multiple models which are connected to the user model using a foreign key relation. this is one of the models I added here for instance: class PsychologicInfo(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) final_assessment = models.TextField(null=True, blank=True) is_approved = models.CharField(max_length=64, blank=True) is_interviewed = models.BooleanField(default=False) I want to write a signal or a save method that does something like this: if the is_interviewed field was True, change that progress_level to USER_ROLE_CHOICES[1][0] I have no idea how to do this so thanks for the tips -
Whats the best way to structure my application and whats the best hosting service to use for this project
I'm looking to setup an application that scrapes information off the web and stores it in a database that i can build a api off using python and django then have a front end created in react that will display the data. the data am scraping is always be increasing and to keep the time down to scrape a specific set of data i wanted to split these out into individual jobs that run 24/7 to keep my database up to date. A lot of the data has the same structure to i thought creating a docker environment that spins up a new container every time a new data set it found would be efficient. 1- I'm wondering if this is the best approach ? 2- would you separate this into separate applications app1 that populated the data base app2 for the api app3 for the front end ? also where is the best place to host this sort of project i have worked alot locally and have little to no knowledge of deploying an application like this to the real world. any advice would be highly appreciated