Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding the django-parler to django admin pages?
I'm workin on my django project and I added django-parler to my django project. I have added parler in my models.py and that looks like this: class Category(TranslatableModel): translations = TranslatedFields( category_name=models.CharField(max_length=255, verbose_name="Category name"), ) parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) slug = models.SlugField(max_length=200, unique=True, editable=False, default='') def clean(self): if self.parent: if self.parent.parent: raise ValidationError("A category that already has a parent cannot be set as the parent of another category.") def save(self, *args, **kwargs): if not self.slug: base_slug = slugify(self.safe_translation_getter('category_name', self.category_name)) # Ensure uniqueness of the slug slug = base_slug counter = 1 while Category.objects.filter(slug=slug).exists(): slug = f"{base_slug}-{counter}" counter += 1 self.slug = slug super(Category, self).save(*args, **kwargs) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['category_name'] def __str__(self): return self.safe_translation_getter('category_name', self.category_name) Tricky part is that I want slug to be translated not just category name. Also, in admin.py I did it like this: admin.site.register(Category, TranslatableAdmin) And I got it like on images below. I'm happy with the result. What you see on first image, is when you click on categories on admin side, and if I have multiple translations it makes entry for every language. On second image you see how it looks like when you are adding … -
Django 404 when connecting to websocket router wh
I'm trying to write my first Django project using websockets. I use django channels. And everything worked fine until the time to integrate react, nginx and django came. Now i get: Could not connect to wss://our.web.site/ws/notifications/id/?token={my_token} Request URL: https://our.web.site/ws/notifications/id/?token={my_token} Request Method: GET Status Code: 404 Not Found my asgi.py: import os from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application from apps.notifications.middlewares import JwtAuthMiddlewareStack from apps.notifications.routing import websocket_urlpatterns os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") # application = get_asgi_application() application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( JwtAuthMiddlewareStack(URLRouter(websocket_urlpatterns)) ), } ) my routing.py: from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r"ws/notifications/(?P<user_id>\w+)/$", consumers.NotificationConsumer.as_asgi()), ] my consumers.py: import json from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer from apps.notifications.models import Notification, OnlineUser class NotificationConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.user = None self.pool_name = None async def connect(self): self.user = self.scope["user"] self.pool_name = f"user_id_{self.user.id}" await self.accept() await self.channel_layer.group_add( self.pool_name, self.channel_name, ) await self.add_online_user() async def disconnect(self, close_code): await self.remove_online_user() await self.channel_layer.group_discard(self.pool_name, self.channel_name) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] await self.channel_layer.group_send(self.pool_name, {"type": "read_message", "message": message}) async def read_message(self, event): message = event["message"] await self.mark_notifications_as_read(message) await self.send(text_data=json.dumps({"message": message, "message_type": "read_message"}, ensure_ascii=False)) async def notification_message(self, event): message … -
How to change model field names among themselves in Django?
I have created a model in my Django project. By mistake, I set the date_created and date_updated fields wrong as follows: class Article(models.Model): date_created = models.DateTimeField(auto_now=True) date_updated = models.DateTimeField(auto_now_add=True) I should have set date_created as auto_now_add=True, and date_updated as auto_now=True. Now, when I want to change the model names by each other as class Article(models.Model): date_updated = models.DateTimeField(auto_now=True) date_created = models.DateTimeField(auto_now_add=True) Django detects that I just changed the definition of the fields and creates a migration as operations = [ migrations.AlterField( model_name='article', name='date_created', field=models.DateTimeField(auto_now_add=True), ), migrations.AlterField( model_name='article', name='date_updated', field=models.DateTimeField(auto_now=True), ), ] But I actually renamed them. When I manually set the migrations as RenameField, it simply does not work because Django detects that I have not created a migration for the changes that I made. Renaming with a different name could be solution, but I need to keep the field names. What can I do in this situation? -
In Django I have been getting this error can anyone help me to solve this
while learning Django created static folder and templates folder and imported code from bootstrap and while running the server I have been getting this errorThis image with Debug = True in settings.py fileAnd this image with Debug = False in settings.py file I need this to solve my error -
Russian set default language when user opened website in Chrome browser
In base.html there is a dropdown to change the language. I think get_current_language comes in Russian Even if en is the default language, when entering kedi.uz, the default language is Russian. How can I set the default language for the user when he first logs in? repo link: https://github.com/bahrom04/ekologiya/blob/master/templates/base.html#L56 # base.py LANGUAGE_CODE = "en-us" this is the dropdown to change language and it stores django_language into session. <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go"> </form> For new users the session will be empty but language of website is on russian language in Chrome browser but if i open it on FireFox, default language of website will be english. My both Chrome and Firefox on english -
execution error in javascript post event $.post when in dev everything is ok
My javascript code raise an error in my production server (nginx+gunicorn) when all is ok in dev. here is my js many thanks for your help <script> const findLoc = () => { const success = (position) => { const latitude = position.coords.latitude; const longitude = position.coords.longitude; var data = {'latitude': latitude, 'longitude': longitude }; data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val(); console.log('Location is on'); console.log(data); document.getElementById("LocationLat").innerHTML = latitude; document.getElementById("LocationLon").innerHTML = longitude; ----->$.post("gps/", data,function(response) { // La réponse est maintenant disponible dans la variable 'response' console.log('Réponse reçue:', response); document.getElementById("postdata").innerHTML = response; $('.spinner-border').hide(); // Faites quelque chose avec les données, par exemple mettre à jour le contenu de la page }).fail(function(xhr, status, error) { // En cas d'échec de la requête, affichez l'erreur console.log('Erreur lors de la requête:', status, error); }); } const error = () => { console.log('Location gathering Not allowed') $('.spinner-border').hide(); document.getElementById("postdata").innerHTML ="Activate position in your browser !" } navigator.geolocation.getCurrentPosition(success,error); } </script> the error is raised by this instruction ---->$.post here the console in the browser : enter image description here urls.py urlpatterns = [ path('admin/', admin.site.urls), path('gps/',views.home_view), views.py def home_view(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') if request.method == 'POST': Latitude = float(request.POST.get('latitude')) Longitude = float(request.POST.get('longitude')) … -
WSL(Ubuntu 22.04 LTS) djnago project unable to connect to Mysql Workbench, but mysql -u root -p working
I'm running my django project in WSL(ubuntu 22.04 LTS), recently moved from windows, when i create a db in windows and migrate the db tables are created but in linux the db itself when created in mysql terminal, not shown in mysql workbench? The problem is that the project in windows was running fine with mysql but since i shifted to linux and using mysql workbench, the database isnt created in mysql wrorkbench from mysql terminal, seems like my project and mysql isnt connected. can anyone help? When i create a database in mysql terminal in my vscode with mysql -u root -p create database "xyz"; the database is created and i migrate the tables in db but this database is just not visible in mysql workbench I tried creating a db in mysql workbench and then adding that db name to settings.py but the db that is created in workbench isnt connected to django project -
Can someone explain to me what "data = validated_data.copy()" means?
I wonder why the create method does not process the data directly but has to copy it into data and then process it indirectly, while the returned result is also the processed user. class UserSerializer(serializers.ModelSerializer): alumni = AlumniSerializer() def to_representation(self, instance): req = super().to_representation(instance) if instance.avatar: req['avatar'] = instance.avatar.url if instance.cover: req['cover'] = instance.cover.url return req def create(self, validated_data): data = validated_data.copy() user = User(**data) user.set_password(user.password) user.save() return user class Meta: model = User fields = ['id', 'first_name', 'last_name', 'username', 'password', 'email', 'avatar', 'cover', 'alumni'] extra_kwargs = { 'password': { 'write_only': True } } -
Profile Picture Not Showing
I am able to upload a profile picture and it goes to the database. I have a "print(profile.profile_picture)" in my views.py that will correctly print the current profile picture in the console when I save. For some reason the profile picture will not show though, my "{% if profile.profile_picture %}" in my profile.html isn't even picking anything up. [] VIEWS.PY= @login_required def profile(request): profile, created = Profile.objects.get_or_create(user=request.user) print(profile.profile_picture) if request.method == 'POST': form = ProfileForm(request.POST, request.FILES, instance=profile) if form.is_valid(): form.instance.user = request.user form.save() return redirect('base:profile') # Redirect to the home page after form submission else: form = ProfileForm(instance=profile) return render(request, 'profile.html', {'form': form}) PROFILE.HTML= <div class="ProfilePage"> <form method="POST" enctype="multipart/form-data" class="profile-form"> {% csrf_token %} <div class="form-group"> <label for="id_username">Username:</label> <input type="text" id="id_username" value="{{ request.user.username }}" readonly> </div> <div class="form-group"> <label for="id_bio">Bio:</label> <textarea id="id_bio" name="bio" rows="4" cols="50" required>{{ form.bio.value }} </textarea> </div> <div class="form-group"> <label for="id_profile_picture">Profile Picture:</label> <input type="file" id="id_profile_picture" name="profile_picture" accept="image/*"> </div> {% if profile.profile_picture %} <div class="form-group"> <label>Profile Picture Preview:</label><br> <img src="{{ profile.profile_picture.url }}" alt="Profile Picture" style="max-width: 500px;"> </div> {% endif %} <button type="submit" class="btn-submit">Save</button> </form> </div> FORMS.PY= from django import forms from .models import Profile class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['bio', 'profile_picture'] I can give more … -
Adding the django-parler to admin pages?
I added django-parler to my django project. I have added parler in my models.py and that looks like this: class Category(TranslatableModel): translations = TranslatedFields( category_name=models.CharField(max_length=255, verbose_name="Category name"), ) parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) slug = models.SlugField(max_length=200, unique=True, editable=False, default='') def clean(self): if self.parent: if self.parent.parent: raise ValidationError("A category that already has a parent cannot be set as the parent of another category.") def save(self, *args, **kwargs): if not self.slug: base_slug = slugify(self.safe_translation_getter('category_name', self.category_name)) # Ensure uniqueness of the slug slug = base_slug counter = 1 while Category.objects.filter(slug=slug).exists(): slug = f"{base_slug}-{counter}" counter += 1 self.slug = slug super(Category, self).save(*args, **kwargs) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['category_name'] def __str__(self): return self.safe_translation_getter('category_name', self.category_name) Tricky part is that I want slug to be translated not just category name. Also, in admin.py I did it like this: admin.site.register(Category, TranslatableAdmin) And I got it like on images below. I'm happy with the result. What you see on first image, is when you click on categories on admin side, and if I have multiple translations it makes entry for every language. On second image you see how it looks like when you are adding categry. Now the question, is it possible … -
ModuleNotFoundError: No module named 'django.db.backends.postgresql' on Ubuntu 24.04
Yesterday I switched to Ubuntu 24.04 LTS from windows and having an issue with my django project and tried every suggestion on the web but no luck. I'm getting below issue: django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgresql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'sqlite3' Most of the suggesion on the web telling update django but I'm already using the latest version 5.0.4 Also postgresql is working fine. I'm able to connect it. -
Django/Heroku - Handling ObjectDoesNotExist Exception When Pushing Data from API to Django Database
My django application receives data from an API. It's very unlikely the API will send incorrect information, but I am trying to cover the possibility the API may send data that would return ObjectDoesNotExist from malicious attempts. Below is my try at how I could handle the exception, by leaving the data 2 tries. After that, I want it to stop pushing the data. I left a few print statement to track the tries are being executed. But none of them are getting printed. This makes me think that the data received from the API is considered as valid (because it exists) and its only when the data is pushed to the database that the application realises it does not exist. Any suggestion on how I could handle this? (I am hoping I am clear) the function: def API_data(request): userprofile_id = request.GET.get('userprofile_id', '') venue_id = request.GET.get('venue_id', '') user = UserProfile.objects.get(id=userprofile_id) venue = Venue.objects.get(id=venue_id) venue_loyalty_point_rule = VenueLoyaltyPointRule.objects.get(venue=venue) scans = ItemisedLoyaltyCard.objects.filter( user_id=user.id, venue=venue) is_point_valid = loyalty_card_validation_rule( scans, user, venue, venue_loyalty_point_rule) if is_point_valid: try_count = 0 max_retries = 2 # Define the maximum number of retries while try_count < max_retries: try: ItemisedLoyaltyCard.objects.create( user_id=user.id, venue=venue, add_points=venue_loyalty_point_rule.points) # If creation succeeds, set data and break … -
Cannot get response for more than first or several first requests with Django and Apache?
I have started to learn Python, then Django in practice by way of executing tutorial codes in Python IDLE. Indeed as maybe the code is of old versions the code running not always works well. Especially I am stacked upon running Django with Apache 2.4 through mod_wsgi. I have done it at first two-three weeks ago, and then main issue was that Django requests on apache (on localhost, not on built-in localhost:8000) completed normally just the two-three times, then I should wait almost indefinitely to see the response from request, or without it. This week I returned to this example Django plus Apache, but it detiorated to the level that just first request is done, the second one almost not executed in a moment as it should be, or even not at all, the next ones - not at all untill Apache server restart in Apache24\bin httpd command. I have extracted Apache lounge (on Windows 10) in C:\Apache24 folder as it should be. Indeed when extracting I deleted two files (readme.txt..)as evidently not neccesarily files over nested Apache24 folder, so maybe I should extract to C:\Apache24\Apache24. When I extracted to the nested folder --- and run from C:\Apache24\Apache24\bin -- the … -
Django celery media folder backup issue
I create a library to get backup to Google Drive using with Google Drive api in python. Actually its work well but when I use with celery my library, celery do not wait for compress my media folder(I guess). Its every time get backup zipped and encrypted backup to Google Drive but its empty. If I go to my django app container and I write my custom command to get media backup, its work well. I have been dealing with 2 week. Is someone can help me about celery or my library. Tried: asycn compress process. my library -> https://github.com/ylrmali/py-googledrive (README.md is not updated) # gcapi/dbhandler/management/commands/pymedia_backup.py import asyncio from django.core.management.base import BaseCommand, CommandParser from django.conf import settings from gcapi.cryption import Cryption from gcapi.drive import GCDrive from gcapi.compress import compress_folder import os import tarfile import datetime class Command(BaseCommand): help = "Restore database" def add_arguments(self, parser: CommandParser): parser.add_argument( '--encrypt', action='store_true', help='Encrypt media folder' ) parser.add_argument( '--compress', action='store_true', help="Compress media folder" ) def __success_output(self, text): """ Success output """ return self.stdout.write(self.style.SUCCESS(str(text))) def __error_output(self, text): """ Success output """ return self.stdout.write(self.style.ERROR(str(text))) def __remove_temp(self, temp_list: list): """ Remove temprary used files """ for file in temp_list: os.remove(file) async def _create_media_tar_async(self, media_folder: str): """ Asynchronously create … -
Django update m2m objects on save
I have a m-2-m rel and i want to update the rel B after any rel A is added via the admin page. Here the details: I have 2 models, Match (rel A) and Player (rel B). I want to update Player.matches_played eveytime a new Match with that player in Match.team1 or Match.team2 is added. How can i achieve this??? the models class Match(models.Model): data=models.DateField(auto_now_add=False,auto_now=False) team1=models.ManyToManyField('players.Player',related_name='team_1') team2=models.ManyToManyField('players.Player',related_name='team_2') score_team1=models.IntegerField(validators=[MinValueValidator(0)]) score_team2=models.IntegerField(validators=[MinValueValidator(0)]) class Player(models.Model): matches_played= models.IntegerField(validators=[MinValueValidator(0)], default=0) I tried signals but in post_save signal {instance.team1} or instance.team1.all() return an empty QuerySet which i believe is correct as the M2M rel is saved later. Then i tried m2m_changed but that signal is not fired with a save via the admin page. What am i missing? @receiver(post_save, sender=Match, dispatch_uid="update_player_game_count") def update_player_games(sender, instance, created, **kwargs): print(f'created {instance.pk}') print(f'created {instance.team1}') print(f'created {instance.team2}') print(f'created {instance.score_team1}') print(instance.team1.all()) @receiver(m2m_changed, sender=Match, dispatch_uid="update_player_game_count") def update_player_game(sender, instance, created, action, **kwargs): print(action) if action == 'post_add': print(action) Thank you very much for you help an alternative which i thought about is to retrieve the data via a property in Player for instance like this, but i think, from a performance point of view, is better to update rows every time a match is added … -
Media not shown on django nginx host
I am currently working on a django project which I deployed to a digitalocean droplet with nginx. The website works, including the staticfiles. After looking at my error.log i saw that it was a permission problem: 2024/04/27 18:58:19 [error] 130139#130139: *194 open() "/home/project/project/media/gallery/IMG_9510.jpeg" failed (13: Permission denied) And when excecuting the namei command, this is the response: root@host:~# namei -l /home/project/project/media/gallery/IMG_9510.jpeg f: /home/refugium/refugium/media/gallery/IMG_9510.jpeg drwxr-xr-x root root / drwxr-xr-x root root home drwxr-x--- project_user project_user project drwxrwxr-x project_user project_user project drwxr-xr-x www-data www-data media drwxr-xr-x www-data www-data gallery -rwxr-xr-x www-data www-data IMG_9510.jpeg So the permissions seem to be fine. For the last check I shortly changed the user in my nginx.conf to root. After that it worked. Did I miss anything? This is my file in sites-available: server { listen 80; server_name refugium-romontberg.ch; location = /favicon.ico { access_log off; log_not_found off; } location /media/ { alias /home/refugium/refugium/media/; } location /static/ { alias /home/refugium/refugium/staticfiles/; } location / { client_max_body_size 200M; include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Thanks -
Django unit test fixing database row id
from django.test import TestCase class DefTests(TestCase): def setUp(self): # first made the label UserType(label="mylabel").save() ## UserType is model object, and I made the first row , the id is supposed to be 1 def test_my(self): u = UserType.objects.get(id=1) # UserType.DoesNotExis error I guess in test mode real insert is not executed, so id is not fixed. Am I correct? Then, Is there any way to fix the id in advance before doing test_****? -
Django Rest Framework serializer simultaneously request bug
i have one view with my basics config class base_view(LoginRequiredMixin, PermissionRequiredMixin): filter_backends = [SearchFilter] pagination_class = generic_pagination permission_required = '' # assigned at each final view (children) raise_exception = True # avoid redirecting to backend login fields = '__all__'# by default brings all fields aliases = [] # placeholder to avoid error as some views will not need aliases def handle_no_permission(self): if self.request.user.is_authenticated: # If the user is authenticated, but still lacks permission, return a JSON response indicating access denied. return JsonResponse({'detail': 'Permission Required'}, status=403) else: # If the user is not authenticated, return a JSON response indicating login required. return JsonResponse({'detail': 'Login Required'}, status=401) def get_serializer_class(self): self.serializer_class = generic_serializer self.serializer_class.Meta.model = self.model self.serializer_class.Meta.fields = self.fields self.serializer_class.Meta.aliases = self.aliases return self.serializer_class ### filter all querysets by company and organization + ordering def get_queryset(self): if self.fields == '__all__': queryset = self.model.objects.all() else: queryset = self.model.objects.only(*self.fields) ### gets user company/organization or FORCES specific company/organization (ADMIN ONLY!) if (self.request.query_params.get('id_com') is not None) and (self.request.user.id==id_admin): queryset = queryset.filter(id_company_fk=self.request.query_params.get('id_com')) if self.request.query_params.get('id_org') is not None: queryset = queryset.filter(id_organization_fk__in = self.request.query_params.get('id_org').split(',')) else: queryset = queryset.filter(id_company_fk=self.request.user.profile.id_company_fk) ### below: filters by organization(s) IF one is specified in user's profile AND if field exists on model if (self.request.user.profile.id_organization_fk is not … -
django - how to distinguish code is run by manage.py or but http server
I customized AppConfig in django to start some processes needed for the main application as described in the django documentation. In the usual initialization process, the ready method is only called once by Django. But in some corner cases, particularly in tests which are fiddling with installed applications, ready might be called more than once. In that case, either write idempotent methods, or put a flag on your AppConfig classes to prevent rerunning code which should be executed exactly one time. Two questions: in my experience the ready() method is alwasys called at least twice even if it just print an hello message. How can I add the flag pointed out in the documentation? I don't want the processes start when I run manage.py commands (ex. to migrate). How can I manage this in the code? -
using my trained model in the views, don't allow me to render the new return valus
it takes a while to load all the data into the new df_with_ṕredictions, my problem is how can I render the new table with those predictions in a template : def home(request): df = None df_with_predictions = None error_message = None api_key = None column_name = None predictions_html = "" # Initialize an empty string for the DataFrame HTML if request.method == 'POST': api_key = request.POST.get('api_key_input', '') column_name = request.POST.get('column_name', '') file = request.FILES.get('file') if file: try: file_ext = file.name.split(".")[-1] if file_ext == "csv": df = pd.read_csv(file) elif file_ext == "xlsx": df = pd.read_excel(file) if df is not None: x_new = get_embeddings(df, column_name, api_key) if x_new is not None: new_predictions = classify_comments(x_new) df_with_predictions = df.copy() df_with_predictions['Clasificación_gpt_'] = new_predictions print("File has been processed and predictions are added. in home") print(df_with_predictions) # Convert DataFrame to HTML predictions_html = df_with_predictions.to_html(classes="table table-striped", index=False) except Exception as e: error_message = str(e) context = { 'api_key': api_key, 'column_name': column_name, 'predictions_html': predictions_html, # Pass the HTML to the template 'error_message': error_message } return render(request, "home.html", context) I tried having al the variables in one post for manipulated in the home views, but I am still having troubles -
Enabling cache and images not loading in django?
If you enable the cache: @cache_page(20, key_prefix='index_page') def index(request): post_list = Post.objects.order_by('-pub_date').all() paginator = Paginator(post_list, 10) page_number = request.GET.get('page') page = paginator.get_page(page_number) return render(request, "index.html", {'page': page, 'paginator': paginator}) When I create a new post, I can no longer upload an image. @login_required def post_edit(request, username, post_id): profile = get_object_or_404(User, username=username) post = get_object_or_404(Post, pk=post_id, author__username=username) if request.user != post.author: return redirect('post', username=username, post_id=post_id) form = PostForm(request.POST or None, files=request.FILES or None, instance=post) if form.is_valid(): form.save() return redirect('post', username=username, post_id=post_id) return render(request, 'post_new.html', {'form': form, 'post': post}) How can I fix this so that it was possible to download pictures and use the cache? -
ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value cant migrate python file
I am not able to migrate my changes. when i run python manage.py runserver - Full Traceback Traceback (most recent call last): File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\manage.py", line 22, in main() File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\core\management_init_.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\core\management_init_.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\core\management\base.py", line 459, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\core\management\base.py", line 107, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\core\management\commands\migrate.py", line 117, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\db\migrations\loader.py", line 58, in init self.build_graph() File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\db\migrations\recorder.py", line 89, in applied_migrations if self.has_table(): ^^^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\db\migrations\recorder.py", line 63, in has_table with self.connection.cursor() as cursor: ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\db\backends\base\base.py", line 316, in cursor return self._cursor() ^^^^^^^^^^^^^^ File "C:\Users\kshitijb\Desktop\Income-Expense-Tracker\env\Lib\site-packages\django\db\backends\dummy\base.py", line 20, in complain raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. seetings.py DB_NAME = os.environ.get("POSTGRES_DB") #database name DB_USER_PASSWORD = os.environ.get("POSTGRES_PASSWORD") # database user password DB_USER = os.environ.get("POSTGRES_USER") # database username DB_HOST … -
CSS is not visible
I'm working on a project using Django. I imported HTML files and created a Base HTML. I placed CSS and images in a folder named 'static' and imported them, but the CSS is not appearing on the site, only the HTML. Would you like me to share the code? I try to change something on setting.py Nothing yet. I didn't want to change it without help from someone. -
Django Form's HiddenInput does not save initial value
I have a simple form with two HiddenInputs. Submitted form does not save initial values for hidden fields. What am I missing? forms.py class TestForm(forms.Form): foo = forms.CharField(required=False, initial="Foo") bar = forms.CharField(required=False, initial="Bar", widget=forms.HiddenInput()) is_true = forms.BooleanField(required=False, initial=True, widget=forms.HiddenInput()) views.py def test_view(request): test_form = TestForm() if request.method == "POST": test_form = TestForm(request.POST) if test_form.is_valid(): print(test_form.cleaned_data) return render(request, "test.html", {"test_form": test_form}) output {'foo': 'Foo', 'bar': '', 'is_true': False} How can i get presettled values for hidden fields after form submit? {'foo': 'Foo', 'bar': 'bar', 'is_true': True} -
Getting error while running Django app on apache2 server about GOOGLE_CLOUD_PROJECT
I am facing an issue while deploying my Django app on apache2 sever. Project ID is required to access Cloud Messaging service. Either set the projectId option, or use service account credentials. Alternatively, set the GOOGLE_CLOUD_PROJECT environment variable. I have declared these in my setting.py GOOGLE_APPLICATION_CREDENTIALS = '<path to json>' GOOGLE_CLOUD_PROJECT = '<project id>' FIREBASE_APP = initialize_app() I tried setting environment variable export GOOGLE_CLOUD_PROJECT= When I run my project ./manage.py runserver then it is working fine.