Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django Email - Gmail Not Showing correct sender
When I send an email from a form on the contact template, which has 3 fields: 'email' 'subject' 'message' to my gmail account that I set up in settings.py, Gmail shows the email as sent from me to me , and not the original sender that I input in the form. this is my contact view: def contact_view(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin-email@gmail.com']) form.save() except BadHeaderError: return HttpResponse('Invalid header found.') return render(request, 'webapp/success.html') form = ContactForm() context = {'form': form} return render(request, 'webapp/contact.html', context) I added a form.save() so I could keep a record on the admin panel of the emails sent. Admin panel shows the correct sender, but Gmail does not. -
Using jQuery to Access Django Database
Okay, so I have been trying to figure this out for about a week and I can't find a straight answer on the internet: I am making Django website and I need to access my database (which is SQLite3) in jQuery to edit the contents of my site. Let's say I have a one-dimensional database like this: in my Django "Views.py" I have this: from exampleapp.models import database def page(request): data = database.objects.all() return(render(request, "homepage.html", {"data": data})) In my HTML file, I have this (which is an iteration of the database): {% for x in data %} <p id = {{x}} > {{x}} </p> {% endfor %} Which outputs this on the HTML Page: Anyways, the id of each DOM element is equal to it's content ("apple", "cheese", etc...). I would like to reference these id's in jQuery so I can edit them. For instance, if wanted to reference the element with the id = "cheese", how can I do that in jQuery? I understand that there is an Ajax function in jQuery which allows it to parse JSON. I can convert my database into JSON format with this in my "Views.py" file (but I still don't know how to … -
How to make dropdown currenycode-countryname in django model
I need to make dropdownlist like this, AED-UAE Dirham AFN-Afghani... For all countries. When I use CountryField() from django-countries I have got all country names only in the dropdown list. how can I get currencycode-country name as a dropdownlist in django model?? -
How to pass date and id through url in django
I am trying to pass date and id through url, but getting an error, I have passed just id before and I usually do it like this. path('user_payment_menu/<int:pk>/',user_payment_menu, name='user_payment_menu'), but now I want date to pass after int:pk/ but when I add date after a slash I am getting an error. -
Django Rest Auth using google authentication
url.py urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('rest_auth.urls')), path('', GoogleLogin.as_view()), path('auth/google/callback/', google_callback, name='google_callback'), path('auth/google/url/', google_views.oauth2_login) ] views.py import urllib.parse from allauth.socialaccount.providers.google import views as google_views from allauth.socialaccount.providers.oauth2.client import OAuth2Client from django.contrib import admin from django.shortcuts import redirect from django.urls import include, path, reverse from rest_auth.registration.views import SocialLoginView class GoogleLogin(SocialLoginView): adapter_class = google_views.GoogleOAuth2Adapter client_class = OAuth2Client @property def callback_url(self): # use the same callback url as defined in your GitHub app, this url must # be absolute: return self.request.build_absolute_uri(reverse('google_callback')) enter code here def google_callback(request): params = urllib.parse.urlencode(request.GET) return redirect(f'http://localhost:8000/accounts/google/login/callback/') Client ID for Web application URIs :http://127.0.0.1:8000 Authorised redirect URIs : http://127.0.0.1:8000/auth/google/callback/ error: Authorization Error Error 400: redirect_uri_mismatch You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy. If you're the app developer, register the redirect URI in the Google Cloud Console. Learn more The content in this section has been provided by the app developer. This content has not been reviewed or verified by Google. If you’re the app developer, make sure that these request details comply with Google policies. redirect_uri: http://localhost:8000/auth/google/callback/ Pl help me. Thank you in advance. django-rest-auth using google authentication any reference documentation pl share me. -
how to filter only the rows containing first occurrence of an item in Django query
I have below data from my Django model id Date value 0 1975 a 21 1975 b 1 1976 b 22 1976 c 3 1977 a 2 1977 b 4 1978 c 25 1978 d 5 1979 e 26 1979 f 6 1980 a 27 1980 f I have this: id Date value 0 1975 a 21 1975 b 1 1976 b 22 1976 c 3 1977 a 2 1977 b 4 1978 c 25 1978 d 5 1979 e 26 1979 f 6 1980 a 27 1980 f I am having trouble finding a way to keep only the lines containing the first occurrence of a'value'. I want to drop duplicate 'values', keeping the row with the lowest 'Date'.The end result should be: id Date value 0 1975 a 21 1975 b 22 1976 c 25 1978 d 5 1979 e 26 1979 f -
How to save multiple dynamically created forms in django
I am trying to create a page where various data corresponding to mutliple models can be input by the user, and to have an option to dynamically add additional forms. I have been attempting to use htmx for this and am able to dynamically add forms, however when I save it is only the last entered form that is saved. I haven't used formsets as this wont integrate well with htmx https://justdjango.com/blog/dynamic-forms-in-django-htmx#django-formsets-vs-htmx. Code below any suggestion as to how to get all the dynamically created forms to be save would be most appreciated! models.py from django.db import models class Author(models.Model): name = models.CharField(max_length=50) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=100) forms.py from django import forms from .models import Book, Author from crispy_forms.helper import FormHelper class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ['name'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-CaseForm' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_tag = False class BookForm(forms.ModelForm): class Meta: model = Book fields = ('title',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_tag = False self.helper.form_show_labels = False views.py class create_book(TemplateView): template_name = 'create_book.html' def get(self, *args, **kwargs): author_form = AuthorForm book_form = … -
How do I design my django app which fetches the data from a legacy database which has huge number of tables?
I am developing a Django app which fetches the data from a huge database and then perform some statistical operation and prints the result. There are different ways available but I want to know what is the best way of doing it? Dataset have a lot of tables, so is it advisable to create models for all those tables? and use Django ORM to replicate below query? OR else I should not use Models at all and use RAW SQL query to fetch the data from database and perform operation and then show the result. If yes then please suggest the best way of doing it. "USE r_d; SELECT nus.noyau_utilisateur_id as "candidate_id", pcon.id as "assessment_id", pcon.created_at as "assessment_creation_date", YEAR(pcon.created_at) as "assessment_year", tti.libelle as "test_name", tfi.libelle as "factor_name", pcal.score_reel as "real_score", pcal.score_brut as "raw_score", pcal.score_calcule as "calculated_score" FROM `passation_calcul` pcal JOIN `passation_contrat` pcon ON pcon.id = pcal.passation_contrat_id JOIN `noyau_utilisateur_societe` nus ON nus.id = pcon.noyau_utilisateur_societe_id JOIN `test_test` tt ON tt.id = pcon.test_test_id JOIN `test_test_i18n` tti ON tt.id = tti.test_test_id JOIN `test_facteur` tf ON tf.id = pcal.id_ref JOIN `test_facteur_i18n` tfi ON tf.id = tfi.test_facteur_id WHERE pcon.test_test_id = 144 AND pcon.etat = "COMPLETED" AND tti.noyau_ref_langue_produit_id = 1 AND pcal.table_ref = 'test_facteur' AND tfi.noyau_ref_langue_produit_id = … -
Does Django's collectstatic command double the space used in production?
I understand that collectstatic command copies static-files found in different Django apps of the Django project to a defined single path so that webserver can easly serve files. Here is what question me: For example, I have many big static-files in several apps and I push my Django project to production. I run collectstatic. The static-files will be copied to project static folder. It means that the static-files are now in two different locations so use twice the storage isn't it? I probably miss a point somewhere in the production deployment process because it doesn't feel right to me in term of storage space.