Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to give data to ManyToManyField from view in django
Hello i am new to django and i am trying to create a page where we can add and participate in various events. This is the model i created for my database model.py class Venue(models.Model): name = models.CharField('Venue Name', max_length=120) address = models.CharField(max_length=300) zip_code = models.CharField('Zip Code', max_length=6) phone = models.CharField('Contact Number', max_length=25, blank=True) web = models.URLField('Website Address', blank=True) email = models.EmailField('Email', blank=True) owner = models.IntegerField('Venue Owner', blank=False, default=1) venue_image = models.ImageField(null=True, blank=True, upload_to="images/") class Event(models.Model): name = models.CharField('Event Name', max_length=120) event_date = models.DateTimeField('Event Date') venue = models.ForeignKey(Venue, blank=True,null=True, on_delete=models.CASCADE) manager = models.ForeignKey(User,blank=True,null=True,on_delete=models.SET_NULL) description = models.TextField(blank=True, ) attendees = models.ManyToManyField(User,blank=True, related_name='attendees') here i am trying to make a link by clicking that link user participate to that Event but i am not getting how to put the user data in the above attendees field view function def attendees(request): Event.attendees.add(request.user) return redirect('list-events') error : AttributeError at /participate/ 'ManyToManyDescriptor' object has no attribute 'add' link <a href="{% url 'participate' %}">Participate</a> url.py path('participate/', attendees, name='participate') -
Django Parler throwing 404 error when switching language
I created a website that will be translated into different languages using the Django Parler package, my default language is English, but I was told by my client to make the website load French by default and then a user can switch to English if he or she wants. I was able to make the site load French by default by creating a middleware and adding it to settings, but my challenge is this, I can't switch the site to English, If I do it gives me a 404 error here is the link to the site site https://ambassadedusaintesprit.com Here is my middleware from django.conf import settings from django.utils import translation class ForceLangMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): language_code = 'fr' translation.activate(language_code) response = self.get_response(request) translation.deactivate() return response **My Settings** MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'ambassade_app.middleware.ForceLangMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LANGUAGE_CODE = 'en' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = ( ('fr', _('French')), ('en', _('English')), ) PARLER_LANGUAGES = { None: ( {'code': 'fr',}, {'code': 'en',}, ), 'default': { 'fallback': ['fr',], 'hide_untranslated': False, } } PARLER_DEFAULT_LANGUAGE_CODE = 'fr' language switcher in base.html <form id="formLang" action="{% url 'set_language' … -
Django limit acces to data for owner
i'm trying to make query for user in Django, but still every user can see all data from data base. I've tried with filters, q objects, but none of these helped me. Here is my model: class Book(models.Model): def __str__(self): return f'{self.bookIdent} - belonging to: {self.user}' user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bookIdent = models.CharField(max_length=255) bookshelf = models.ForeignKey(BookShelf, default='', on_delete=models.CASCADE) @classmethod def total_info(cls): return cls.objects.aggregate(book_counter=Count('id')) class Meta: verbose_name_plural = "Books" And my views: @login_required(login_url="/login/") def index(request): context = {'segment': 'index'} html_template = loader.get_template('dashboard.html') context.update(dict(Book.total_info())) context['Book'] = set_pagination(request,Book.objects.all(). filter(user=request.user), item_numer=10) return HttpResponse(html_template.render(context, request)) I would like to make query that only user from book class could see his books. -
Django REST framework: Join tables
I am trying to make an API view where the user inputs the name of a controller and receives the measurements it can return as a JSON. models.py class Microcontrollers(models.Model): name = models.CharField(max_length=25) serial_number = models.CharField(max_length=20, blank=True, null=True) type = models.CharField(max_length=15, blank=True, null=True) software = models.CharField(max_length=20, blank=True, null=True) version = models.CharField(max_length=5, blank=True, null=True) date_installed = models.DateField(blank=True, null=True) date_battery_last_replaced = models.DateField(blank=True, null=True) source = models.CharField(max_length=10, blank=True, null=True) friendly_name = models.CharField(max_length=45, blank=True, null=True) class MicrocontrollersMeasurements(models.Model): microcontroller = models.ForeignKey(Microcontrollers, models.DO_NOTHING, blank=True, null=True) measurement = models.ForeignKey(Measurements, models.DO_NOTHING, blank=True, null=True) class Measurements(models.Model): code = models.CharField(max_length=25) measurement = models.CharField(max_length=25) unit = models.CharField(max_length=25) type = models.CharField(max_length=25) serializers.py class SourceStationsSerializer(serializers.ModelSerializer): def create(self, validated_data): pass def update(self, instance, validated_data): pass class Meta: model = Microcontrollers fields = ['id', 'name'] class StationMeasurementsSerializer(serializers.ModelSerializer): def create(self, validated_data): pass def update(self, instance, validated_data): pass class Meta: model = MicrocontrollersMeasurements fields = '__all__' class MeasurementsSerializer(serializers.ModelSerializer): station = SourceStationsSerializer() stationMeasurements = StationMeasurementsSerializer() def create(self, validated_data): pass def update(self, instance, validated_data): pass class Meta: model = Measurements fields = '__all__' The database creates IDs for each controller and measurement. My question is how can i join the 3 tables so i can find the measurements that belong to each controller. -
Remove QuerySet format from Output
How do I remove queryset from the output? MY Query format Xname= final.objects.filter(fshape=shapeofpill).values('fnmae') XDescr= final.objects.filter(fshape=shapeofpill).values("fdescr") Output: <QuerySet [{'fnmae': 'Dexmethylphenidate'}]> <QuerySet [{'fdescr': 'Dexmethylphenidate is used in the treatment of adh'}]> I want only values eg. In first query I want only Dexmethylphenidate as a Output