Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - Nested Serializer Attribute error in response
wondering if someone could help me with the following problem. I have a serialises such as this: class LineupPlayerSerializer(serializers.ModelSerializer): id = serializers.UUIDField(write_only=True) name = serializers.CharField(read_only=True) positionType = serializers.CharField(read_only=True) alternativePositions = serializers.CharField(read_only=True, required=False, allow_blank=True) shirtNumber = serializers.IntegerField(read_only=True, required=False, allow_null=True) positionOnPitch = serializers.IntegerField(required=True) class Meta: model = LineupPlayer fields = ['id', 'positionType', 'alternativePositions', 'name', 'shirtNumber', 'positionOnPitch'] def create(self, validated_data): player_id = validated_data.pop('id') player = Player.objects.get(id=player_id) position_on_pitch = validated_data.pop('positionOnPitch') lineup = validated_data.pop('lineup') lineup_player = LineupPlayer.objects.create(lineup=lineup, player=player, positionOnPitch=position_on_pitch) return lineup_player class LineupSerializer(serializers.ModelSerializer): players = LineupPlayerSerializer(many=True) class Meta: model = Lineup fields = ['id', 'formation', 'players'] def create(self, validated_data): try: players_data = validated_data.pop('players') lineup = Lineup.objects.create(**validated_data) for player_data in players_data: player_data['lineup'] = lineup LineupPlayerSerializer().create(player_data) return lineup except Exception as e: print(f"Error: {e}") raise e However, when I send the request I get an Attribute error: Got AttributeError when attempting to get a value for field `positionOnPitch` on serializer `LineupPlayerReadSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Player` instance. Original exception text was: 'Player' object has no attribute 'positionOnPitch'. For some reason Django thinks that the positionOnPitch is in the Player model and I can't figure out how. When I use write_only=True for positionOnPitch it sends the … -
Efficient way to get relationship data
I have a Modal ABC and a field named GROUP which is a foreign key, and this model Abc is also used as a foreign key in another model XYZ. My requirement is that when I view the list of XYZ with filters such as (whse="01" and abc="02") I want to get the name of the group(from model abc) along with the list data of the XYZ model. class ABC(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) class XYZ(models.Model): abc = models.ForeignKey(ABC, on_delete=models.CASCADE) whse = models.ForeignKey(WHSE, on_delete=models.CASCADE) qty = models.CharField() What I do right now is - in serializer I define a SerializerMethodField() fields. here is the code - class XYZSerializer(serializers.ModelSerializer): groupName = serializers.SerializerMethodField() def get_groupName(self, instance): return instance.abc.group.name if instance.abc else '' class Meta: model = ZYX fields = '__all__' I get my desired result but you can see that my filter requirement is always (whse="01" and abc="02") on the XYZ model and so the value of get_groupName is always going to remain the same for each of my requests (my abc is always the same in the output list, so will be the group name). How can I format my data, serializer to reduce the database query, (to find groupName) for … -
Appending Wagtail StructBlock to Streamfield
is there a good way to append a StructBlock into an existing StreamField? I'm building a links page where non admin users can add their own links. I would like to be able to append a LinkBlock using form data. I'm attaching what I have right now and currently stepping through the Wagtail source code to better understand how blocks are created. class LinkBlock(blocks.StructBlock): title = blocks.CharBlock(required=True, help_text="Link title") url = blocks.URLBlock( required=True, help_text="Link URL", ) class LinksPage(Page): links = StreamField( [ ("link", LinkBlock()), ], blank=True, use_json_field=True, max_length=20 ) content_panels = Page.content_panels + [ FieldPanel("links"), ] # Adding dynamic links with form data links_page.links.append( ( "link", { "title": form.cleaned_data["title"], "url": form.cleaned_data["url"], "link_type": form.cleaned_data["link_type"], "color_scheme": form.cleaned_data["color_scheme"], }, ) ) try: # TODO: Investigate why this is necessary # links_page.links._raw_data = [lnk for lnk in links_page.links._raw_data if lnk is not None] # without the filter above, we get a TypeError when trying to save the page links_page.save() except TypeError as e: logger.error(f"Error saving link: {e}") raise e """ Example stack trace: File "../.venv/lib/python3.13/site-packages/wagtail/blocks/stream_block.py", line 680, in __getitem__ self._prefetch_blocks(raw_value["type"]) ~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^ File "../.venv/lib/python3.13/site-packages/wagtail/blocks/stream_block.py", line 710, in _prefetch_blocks raw_values = OrderedDict( File "../.venv/lib/python3.13/site-packages/wagtail/blocks/stream_block.py", line 713, in <genexpr> if raw_item["type"] == type_name and self._bound_blocks[i] is None … -
UnicodeDecodeError with socket.getfqdn in Django runserver on Windows
I’m building a Django API. After transferring my project to a new server and attempting to run it with: python manage.py runserver I encountered the following exception: File "", line 795, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) ^^^^^^^^^^^^^^^^^^^ UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 19: invalid start byte I verified my hostname using the hostname command in the terminal. It returned: DESKTOP-KTU1TC2 (consists of only ASCII characters). I have also run this code, but everything works just fine. >>>import socket >>>socket.gethostbyname('127.0.0.1') 127.0.0.1 >>>socket.gethostbyname('DESKTOP-KTU1TC2') (some ip address) I have also tried to explicitly start the server with: python manage.py runserver 127.0.0.1:8000 The error persists. Environment Details: Python: 3.12 Django: 5.1.4 What should i try to resolve this issue? Thank you in advance -
MAUI / Django Serializer - Trailing slash added
I have a MAUI app that connects to an API to collect some data. I am handling the API width django. Whatever I try, it seems a trailing slash is added automatically at the end of the path which creates an error. logs: method=GET path="/api/some-model/?userprofile_id=105/" Received userprofile_id: 105/ Error during processing: Field 'id' expected a number but got '105/'. On the API side the trailing slash does not appear, which makes me think its on the server side. int userId = int.Parse((Shell.Current as AppShell).userID); string url = $"api-path/?userprofile_id={userId}"; # url = api-path/?userprofile_id=105 API<List<Model>>.Get( url, OnModelSuccess, OnModelError); On Django side, I have set APPEND_SLASH = True and listed below the path of my api: router.register(r'api-path', APIPATHViewSet, basename='apipath') Any idea how I could remove the trailing slash from the request? -
Django with uwsgi not service static files
I am running a django app using uwsgi and docker. When i open the admin panel, it's all messed up. I figured it's because the static files are giving 404. How do i fix this? uwsgi.ini: static-map = /static=/app/static static-expires = /* 7776000 offload-threads = %k settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') I have run collectstatic and verified static dir exists in docker container Dockerfile FROM python:3.10-slim # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set working directory WORKDIR /app # Install system dependencies RUN apt-get update \ && apt-get install -y software-properties-common python3-launchpadlib \ && add-apt-repository ppa:savoury1/ffmpeg4 \ && apt-get update \ && apt-get install -y --no-install-recommends gcc libpq-dev ffmpeg libc-dev \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* # Install Python dependencies COPY Pipfile Pipfile.lock /app/ RUN pip install pipenv && pipenv install --system --deploy # Copy project files COPY . /app/ # Expose the port the app runs on EXPOSE 8000 # Run the Django app CMD ["uwsgi", "--http", "0.0.0.0:8000", "--module", "yt_automation.wsgi:application", "--ini", "uwsgi.ini"] -
why I get error when I use href="{{ panel.get_absolute.url }}" in my templates?
I wrote a simple page to show a list of goods that when you click on each of them it forwards you to the purpose page to show the good's details, but I think this method doesn't work right now or I have a mistake ... this is my model: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class PanelManager(models.Manager): def ye(self,year): return self.filter(publish__year=year) def pu(self,publish): return self.filter(status=publish) class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager,self).get_queryset().filter(status='published') class Panel(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') author = models.ForeignKey(User, on_delete=models.CASCADE) objects = PanelManager() published = PublishedManager() # objects = models.Manager() def get_absolute_url(self): return reverse('users:details',args=[self.slug, self.id]) class Meta: ordering = ('-publish',) def __str__(self): return self.title my views: from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse from .models import Panel def test1(request): return HttpResponse("Hello this is test1") def panellist(request): panels=Panel.objects.filter(publish__year=2024) return render(request, 'users/panel/panel list.html',{'panels':panels}) def p_details(request,panel, pk): panel=get_object_or_404(Panel,slug=panel,id=pk) return render(request, 'users/panel/details.html', {'panel':panel}) my urls: from django.urls import path from .import views urlpatterns = [ path('panellist/', views.panellist, name='panellist'), path('details/<slug:panel>/<int:pk>/', views.p_details, name='details'), ] my … -
Prevent Django DetailView from adding template context with name of object
I have a DetailView for users, and it seems to be adding a user context variable. This is problematic because I have an application-wide context variable, user that contains the current user that is being overridden. How can I prevent the DetailView from adding this context variable? -
Error related to connecting Django from Docker to Nginx
I am currently working on Docker and have done the following: The Django test page was working fine on localhost. I connected it to Docker. I also connected Docker to Gunicorn. However, when I try to connect it through Nginx, only the default Nginx page is displayed, and it is not connecting to the application I created. nginx/Dockerfile FROM nginx:latest RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d # nginx/nginx.conf upstream daniel_blog { server web:8000; } server { listen 80; server_name localhost; # Default location location / { proxy_pass http://daniel_blog; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } # Static files location /static/ { alias /usr/src/app/_static/; } # Media files location /media/ { alias /usr/src/app/_media/; } } --- # .env.dev DEBUG="1" SECRET_KEY="django-insecure-88ndzs0z0uzko4x5f=*ngu=#h+a(k=!#ooyvt*0h+78r1n=^oy" DJANGO_ALLOWED_HOSTS = localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=daniel_blog_dev SQL_USER=daniel_blog_user SQL_PASSWORD=daniel_blog_db_password SQL_HOST=db SQL_PORT=5432 --- # .env.prod DEBUG=0 SECRET_KEY=w4+=--yyyigm1-=na@9et*1ldt-q-x4x=57m2xkiru6!oxeh5b DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=daniel_blog_prod SQL_USER=daniel_blog_user SQL_PASSWORD=daniel_blog_db_password SQL_HOST=db SQL_PORT=5432 --- # .env.prod.db POSTGRES_USER=daniel_blog_user POSTGRES_PASSWORD=daniel_blog_db_password POSTGRES_DB=daniel_blog_prod --- # docker-compose.yml services: nginx: build: ./nginx volumes: - static_volumes:/usr/src/app/_static - media_volumes:/usr/src/app/_media ports: - 80:80 depends_on: - web web: build: . command: gunicorn daniel_blog.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volumes:/usr/src/app/_static - media_volumes:/usr/src/app/_media - ./:/usr/src/app/_media expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:17.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ … -
Sorting a string before a number with Postgres and Django
I want to use fuzzy dates for sorting a Django query, so you can use a full date if you have it, but maybe you only know year and month. For example, Jan XX 2024 would come before Jan 1 2024 and Jan 2 2024. I was originally planning to store as a string 202401XX, 20240101, etc, but Postgres naturally sorts characters after numbers so this would put the date with no day AFTER the date with day specified. I was thinking of converting the 20240101 to letters before saving to the database (X=A, 0=F, 1=G, etc) since this is a computationally cheap thing and I could control where everything sorted. Is this a terrible idea? Is there a better way? I don't want to do a custom Postgres query because that would be complicated with Django's built-in pagination -
Is there way to display historical records for all model instances using django-simple-history?
I am using django-simple-history for saving history of the objects. And it works fine. But I want to create a view in django admin that displays history records for all instances in model in one page. For example I have a model class TestModel(models.Model): title = models.CharField('title', max_length=100) history = HistoricalRecords() and admin class TestModelAdmin(SimpleHistoryAdmin): list_display = ['title'] admin.site.register(TestModel, TestModelAdmin) And now I can see the history of each instance. Not sure how I can solve this problem. May be there is a way to create custom views in admin site (without model), or maybe I should create another model? What's the best way to display all history records (for all instances) in admin panel? -
Redirecting from DELETE to GET in Django
I use Django django 4.0.8 and django-tastypie. Why is it that when I send a request (for example) http://127.0.0.1:8000/api/v1/courses/3 via Postman, I get a redirect to GET /api/v1/courses/3/? If I send http://127.0.0.1:8000/api/v1/courses/3/ it work correctly. Adding 'APPEND_SLASH = True' in settings.py does not resolve this problem. String "MIDDLEWARE = ['django.middleware.common.CommonMiddleware']" I have in settings.p -
How to handle user login through Spotify (what to do with tokens)
I'm trying to create a web app using a Django backend and React frontend. This is my first time using Django and dealing with accounts specifically. The app revolves around Spotify accounts so to login a user has to login through Spotify. I understand the authorization process and can get a user's access/refresh token, but I'm not sure what to do from here. I have found a lot of conflicting information online. Most people say not to use local storage which makes sense. Right now I am trying to implement it using Django sessions, but I've read online about that not scaling well/not being RESTful so I'm confused. I also looked at using django-allauth and it worked, but I'm confused with how it would work with my React frontend because as far as I understand it, it's just something I can do only in Django (localhost:8000). I want to be able to create a User in my database once a user logs in for the first time. From here, do I store the user's tokens inside the database too? Do I use Django's User model at all? I saw people mentioning Django's built-in authorization but confused how that ties in … -
Django flush raises "cannot truncate a table referenced in a foreign key constraint"
Consider the following models.py: from django.db import models class Foo(models.Model): bars = models.ManyToManyField( "Bar", blank=True ) class Bar(models.Model): foos = models.ManyToManyField( "Foo", blank=True, through="Foo_bars" ) and the associated migration: from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Bar", fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ], ), migrations.CreateModel( name="Foo", fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("bars", models.ManyToManyField(blank=True, to="demo.bar")), ], ), migrations.AddField( model_name="bar", name="foos", field=models.ManyToManyField(blank=True, to="demo.foo"), ), ] Running python manage.py migrate && python manage.py flush --no-input --traceback produces the following trace back File "/opt/venv/lib/python3.13/site-packages/psycopg/cursor.py", line 97, in execute raise ex.with_traceback(None) django.db.utils.NotSupportedError: cannot truncate a table referenced in a foreign key constraint DETAIL: Table "demo_bar_foos" references "demo_foo". HINT: Truncate table "demo_bar_foos" at the same time, or use TRUNCATE ... CASCADE. How can I fix this problem? How can I add cascade? A full reproducible example is available at https://github.com/rgaiacs/django-flush-problem. -
Django getting 404 error when trying to load files from MinIO on the same server
I have setup a Django web app (Django version 5.0.6) on an Ubuntu 22.04 LTS operating system with its default backend file system running MinIO 2024-08-03T04-33-23Z. The services are all running using HTTPS. My Django web app is configured to run with Gunicorn version 22.0.0 and Nginx version 1.26.2 My Django settings are provided below. ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', [subdomain_ip], 'subdomain.domain.org' ] CSRF_TRUSTED_ORIGINS = [f'https://{host}' for host in ALLOWED_HOSTS] CSRF_ALLOWED_ORIGINS = [f'https://{host}' for host in ALLOWED_HOSTS] CORS_ORIGINS_WHITELIST = [f'https://{host}' for host in ALLOWED_HOSTS] INTERNAL_IPS = ['127.0.0.1', 'localhost', [subdomain_ip], 'subdomain.domain.org'] # MINIO BACKEND SETTINGS MINIO_CONSISTENCY_CHECK_ON_START = True MINIO_ENDPOINT = 'subdomain.domain.org:9000' MINIO_REGION = 'eu-west-1' # Default is set to None, current is Ireland MINIO_ACCESS_KEY = '[REDACTED]' MINIO_SECRET_KEY = '[REDACTED]' MINIO_USE_HTTPS = True MINIO_EXTERNAL_ENDPOINT = 'subdomain.domain.org:9000' MINIO_EXTERNAL_ENDPOINT_USE_HTTPS = True MINIO_STORAGE_ENDPOINT = 'subdomain.domain.org:9000' MINIO_STORAGE_ACCESS_KEY = '[REDACTED]' MINIO_STORAGE_SECRET_KEY = '[REDACTED]' #MINIO_STATIC_FILES_BUCKET = 'bridge-static-files-bucket' MINIO_MEDIA_FILES_BUCKET = 'bridge-media-files-bucket' # Media files storage configuration #DEFAULT_FILE_STORAGE = 'minio_storage.storage.MinioMediaStorage' DEFAULT_FILE_STORAGE = 'django_minio_backend.models.MinioBackend' MINIO_STORAGE_MEDIA_BUCKET_NAME = MINIO_MEDIA_FILES_BUCKET MINIO_STORAGE_MEDIA_URL = f"{MINIO_EXTERNAL_ENDPOINT}/{MINIO_MEDIA_FILES_BUCKET}" MINIO_PRIVATE_BUCKETS = ['django-backend-dev-private', ] MINIO_PUBLIC_BUCKETS = ['django-backend-dev-public', ] #MINIO_PRIVATE_BUCKETS.append(MINIO_STATIC_FILES_BUCKET) MINIO_PRIVATE_BUCKETS.append(MINIO_MEDIA_FILES_BUCKET) # Default: True // Creates bucket if missing, then save MINIO_BUCKET_CHECK_ON_SAVE = True # SSL SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 31536000 # 1 year SECURE_HSTS_INCLUDE_SUBDOMAINS = True … -
why django makemigration command creates python based code instead of creating sql commands
why django makemigration command creates python based code instead of creating sql commands, Someone please explain from design decision point of view, and what benefits we get from it. -
Authentication with Django Ninja, allauth or other solid solution?
I'm creating an API with django ninja, and I wanted to implement user authentication and accounts. I like allauth for it's social account functionality built in, as I plan for users to be able to link steam/xbox accounts and I've seen you can use this with drf relatively easily? Can I implement it with django ninja, or is there any other good authentication for ninja specifically. Also, will I need token authentication for this if at some point in the future it may interface with a mobile application? Thanks for the support. -
How to alter data entered into django models to fit a criteria?
I have a django models.py file that I use to store information in my database. I store information on businesses and the countries that they operate in. I get the list of countries from their website. However they may call each country by a different name or use different formatting, for example 'The Gambia' vs 'Gambia', 'Eswatini' vs 'Swaziland', 'Trinidad and Tobago' vs 'Trinidad & Tobago'', 'The United States' vs 'United States of America'. I want that when I store the names of these countries in my database they automatically follow a set of rules to ensure consistent formatting of their names. Additionally, some websites state something like 'We operate in 150 countries'. I want to enter this information into the database but not have it come up when I request a list of countries from the frontend. Here is my models.py: class Company(models.Model): #the newly created database model and below are the fields name = models.CharField(max_length=250, blank=True, null=True) #textField used for larger strings, CharField, smaller slug = models.SlugField(max_length=250, blank=True, db_index=True, unique=True) available_merchant_countries = models.TextField(max_length=2500, blank=True, null=True) available_merchant_countries_source = models.URLField(max_length=250, blank=True, null=True) -
How to dynamically list fields for products
I have various products, and their fields need to change depending on the category. Is it possible to implement this in the most optimized way? Also, can the fields be managed from the admin panel? -
Datatables instance not synced with DOM (input checkbox status)
I have a table my_tbl initialized with datatables2.1.8.js jQuery library: /* using python django template because table template is not in the same html file */ {% include 'my_tbl_template.html' %} let my_tbl=$('#my_tbl').DataTable({...}), each cell containing <input type="checkbox" value="some_value"> whether initially checked or unchecked; The problem exactly is that my_tbl is not synced with the html dom after changing manually the checkboxes status! (check or uncheck); e.g. when I have two checkboxes (2 cells) initially both checked, when user unchecks one of them printCheckboxStatusDom() prints 1 //(expected number of checked checkboxes) but printCheckboxStatusTbl() prints 2 //the initial checked checkboxes $(document).ready(function(){ $('input[type=checkbox]').change(function() { printCheckboxStatusDom(); // prints correctly how many checkbox is checked at this time printCheckboxStatusTbl(); //always prints initialized values (no change) }); function printCheckboxStatusDom(){ let checkeds = $(document).find('input[type=checkbox]:checked'); console.log('DOM: checked boxes: ' + checkeds.length); } /* Function to print checkboxes status in the my_tbl instance */ function printCheckboxStatusTbl() { my_tbl.rows().every(function (rowIdx, tableLoop, rowLoop) { let rowNode = this.node(); let cellCheckboxes = $(rowNode).find('input[type=checkbox]:checked'); console.log('Tbl: checked boxes: ' + cellCheckboxes.length); } ); } -
Transferring a Django + React Project to a New PC in an Offline Environment Without Reinstalling Dependencies
I have a full-stack Django and React project that I need to transfer to a new computer in a completely offline environment. My current setup includes: Django backend with custom app React frontend Virtual environment Specific dependency requirements Project Structure: development/ ├── .git/ ├── .gitignore ├── backend/ │ ├── app/ │ ├── db/ │ ├── manage.py │ └── myproject/ ├── frontend/ │ ├── node_modules/ │ ├── package.json │ ├── package-lock.json │ ├── public/ │ └── src/ ├── initial_data.py ├── packages/ ├── README.md ├── requirements.txt └── venv/ Challenges Dependency Management No internet access for pip or npm install Potential system-specific binary incompatibilities Preserving exact package versions Environment Reproduction Virtual environment setup Python and Node.js version compatibility Native library dependencies Current Attempts I've tried: Directly copying the entire project directory Manually installing requirements from requirements.txt Using pip and npm to install packages Invariably, these methods fail due to: Missing system libraries Version conflicts Binary incompatibility Specific Questions How can I package all project dependencies for offline transfer? What's the most reliable method to reproduce the development environment? Are there tools that can create a complete, transferable project snapshot? Detailed Environment Details Backend: Django 5.0.6 Frontend: React (based on package.json) Python: 3.12.4 Operating … -
What could be the possible reasons for encountering the error?
What could be the possible reasons for encountering the error 'OperationalError: no such table: auth_user' when running a Django application, and how can it be resolved? I am try to solves that error but I cant find solution on Internet related to this error please if you optimized and best solution kindly give me proper answer? 'OperationalError: no such table: auth_user' when running a Django application, and how can it be resolved? -
How to solve 'django.db.migrations.exceptions.InconsistentMigrationHistory' error?? (using powershell/VSCode)
I am making a web app (I am a student and this is my first attempt of building a project) using stack: Django, Vue and MySQL. Attaching link to git repo here: https://github.com/yeshapan/LearningDashboard (please refer ReadME for details) I completed initial setup and then created an app called dashboard where I defined models for the features. Edit: Here's the error message as text: Traceback (most recent call last): File "C:\Users\DELL\Desktop\LearningDashboard\manage.py", line 22, in <module> main() File "C:\Users\DELL\Desktop\LearningDashboard\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\base.py", line 459, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\base.py", line 107, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\commands\migrate.py", line 121, in handle executor.loader.check_consistent_history(connection) File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\db\migrations\loader.py", line 327, in check_consistent_history raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency dashboard.0001_initial on database 'default'. However, it is raising error: Error message I tried asking ChatGPT for help. It said to delete everything in dashboard/migrations and delete db.sqlite3 file in root folder (Edit: I also deleted the table from MySQL and applied migrations again but it is still giving error) and apply … -
The dropdown menu is not expanding. CSS and JS are connected correctly
I am a beginner in web development. I need some help. The dropdown menu is not expanding. CSS and JS are connected correctly. What could be the reason? I checked the CSS/JS classes and connected files. Everything seems to be correct, I even used GPT, but no results. :( I can provide other project files if needed. Here is the code from the main file layout.html. {% load static %} <!DOCTYPE html> <html lang="uk"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}Головна{% endblock %}</title> <link href="https://stackpath.bootstrapcdn.com/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="{% static 'main/css/main.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/5.10.1/main.min.css"> </head> <body> <button class="btn btn-primary" id="sidebarToggle"> <i class="fas fa-bars"></i> </button> <div class="d-flex"> <aside class="flex-shrink-0 p-3 bg-dark text-white sidebar" id="sidebar"> <a href="/" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none"> <img src="{% static 'main/img/2.png' %}" alt="Logo" class="small-logo"> </a> <hr> <ul class="nav nav-pills flex-column mb-auto"> <li class="nav-item"> <a href="{% url 'layout' %}" class="nav-link text-white {% if request.resolver_match.url_name == 'layout' %}active{% endif %}" aria-current="page"> <i class="fas fa-heart"></i> Головна </a> </li> <li> <a href="{% url 'staff' %}" class="nav-link text-white {% if request.resolver_match.url_name == 'staff' %}active{% endif %}"> <i class="fas fa-users"></i> Особовий склад </a> </li> <li> <a href="{% url 'calendar' %}" … -
"C# PBKDF2 password hashing with Django-compatible format (pbkdf2_sha256), issues with password verification"
I am working on a C# application where I need to verify user passwords that were hashed using Django’s PBKDF2 algorithm (pbkdf2_sha256). The passwords are stored in the format: pbkdf2_sha256$iterations$salt$hash For example: pbkdf2_sha256$870000$wyEbTcPvbTOet9npIyftqZ$Xv274JNGq1ZMQQHzmZx8q5n+Nly/U5Wf1WYLRO4d8YY= I'm trying to replicate the same process in C# using Rfc2898DeriveBytes to verify the password. However, I am encountering an issue where the computed hash does not match the stored hash, even though the entered password is correct. Here's the C# code I’m using to verify the password: public static bool VerifyPassword(string enteredPassword, string storedPasswordHash) { var parts = storedPasswordHash.Split('$'); if (parts.Length != 4 || parts[0] != "pbkdf2_sha256") { Console.WriteLine("Invalid password format."); return false; } string iterationsStr = parts[1]; string salt = parts[2]; string storedHash = parts[3]; if (!int.TryParse(iterationsStr, out int iterations)) { Console.WriteLine("Invalid iterations count."); return false; } byte[] saltBytes = DecodeBase64Salt(salt); if (saltBytes == null) { return false; } byte[] passwordBytes = Encoding.UTF8.GetBytes(enteredPassword); byte[] computedHashBytes; using (var pbkdf2 = new Rfc2898DeriveBytes(passwordBytes, saltBytes, iterations, HashAlgorithmName.SHA256)) { computedHashBytes = pbkdf2.GetBytes(32); } string computedHash = Convert.ToBase64String(computedHashBytes); Console.WriteLine($"Computed Hash: {computedHash}"); return storedHash == computedHash; } private static byte[] DecodeBase64Salt(string salt) { switch (salt.Length % 4) { case 2: salt += "=="; break; case 3: salt += "="; break; } …