Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How should I test this Custom Permissions
I'm confused about the procedure to test this permissions. Should I run this tests testing the login inheriting just the permissions? Couldn't just test this permissions by itsef? How must be done a test like this? def has_permission(self, request, view): user = request.user if not user: user = get_user(request) # -- Default user from allowed hosts bypasses authentication. if API_DEFAULT_USER == user.username: return True # -- Admin users have permission. if user.is_staff or user.is_superuser: return True # -- suscribed users have permission. if not user.is_anonymous: return True return False class SuscribedUserApiPerm(BasePermission): def has_permission(self, request, view): user = request.user # -- suscribed users only have permission. if not user.is_anonymous and user.username is None: return True return False class SubscriptionApiPerm(SuscribedUserApiPerm): def has_permission(self, request, view): user = request.user if super().has_permission(request, view): # Checking current user's subscription return user.owns_api() return False class SubscriptionSimulatorPerm(SuscribedUserApiPerm): def has_permission(self, request, view): user = request.user if super().has_permission(request, view): # Checking current user's subscription return user.owns_simulator() return False -
FATAL: password authentication failed for user "postgres" while running makemigrations
getting the below error while running makemigrations Traceback (most recent call last): File "/home/siva/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/home/siva/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/home/siva/venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/home/siva/venv/lib/python3.8/site-packages/psycopg2/init.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "postgres" FATAL: password authentication failed for user "postgres" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/siva/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/siva/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/siva/venv/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/siva/venv/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/siva/venv/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/siva/venv/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "/home/siva/venv/lib/python3.8/site-packages/django/db/migrations/loader.py", line 283, in check_consistent_history applied = recorder.applied_migrations() File "/home/siva/venv/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/home/siva/venv/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/siva/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/home/siva/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/home/siva/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/home/siva/venv/lib/python3.8/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from … -
Deleting database objects in django - How do I correctly make a delete function?
I'm building my first solo django project and one of the stumbling blocks I've run into is creating a "delete function" so I can delete objects in the database. I've been looking at various tutorials for this but I'm getting slightly confused along the way. I'd really appreciate any advice on how to do this correctly in django. Here's what I've been working with so far. I have a model called "Myteam" which looks like this... class Myteam(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) QB = models.CharField(max_length=80, null=True) QBscore = models.IntegerField(null=True) RB1 = models.CharField(max_length=80, null=True) RB1score = models.IntegerField(null=True) RB2 = models.CharField(max_length=80, null=True) RB2score = models.IntegerField(null=True) WR = models.CharField(max_length=80, null=True) WR1score = models.IntegerField(null=True) WR2 = models.CharField(max_length=80, null=True) WR2score = models.IntegerField(null=True) TE = models.CharField(max_length=80, null=True) TEscore = models.IntegerField(null=True) D = models.CharField(max_length=80, null=True) Dscore = models.IntegerField(null=True) K = models.CharField(max_length=80, null=True) Kscore = models.IntegerField(null=True) In my views.py, yesterday, I tried this out... def delete_player(request, pk): player = Myteam.objects.get(pk=id) if request.method == 'POST': player.delete() return HttpResponseRedirect(reverse("index")) return render(request, 'game/index.html') Here's my urls.py path('delete_player/<str:pk>', views.delete_player, name="delete_player") For the html, I was initially trying to have a button link to the delete_player function, but so many of the tutorials I've been looking at use a form with a … -
Create one shared model entry for the whole scope or class in Pytest | Django
I have a simple and possible quite dumb question on Pytest. For example I have a following fixture: @pytest.fixture(scope='module') def my_fixture(db): data = dict( … some data here...) obj = Model.objects.create(**data) return obj Well, if I use it like that I would receive following error: ScopeMismatch: You tried to access the 'function' scoped fixture 'db' with a 'module' scoped request object, involved factories That’s clear So that in order to still use ‘module’ scope I did following: @pytest.fixture(scope='module') def my_fixture(django_db_setup, django_db_blocker): data = dict( … some data here…) with django_db_blocker.unblock(): obj = Model.objects.create(**data) yield obj with django_db_blocker.unblock(): Model.objects.all().delete() Question is: Is it looks like hack or it is just normal way to do it in Pytest? I asking this because in unitests it would be just simple one-liner: @classmethod def setUpTestData(cls): cls.obj = Model.objects.create(**data) Is it any native way how to create one test object in database and use(share) it for 20 tests in one module( or in one class, whatever) without recreating it for each and every test method? It makes no sense for me to do it because of overhead. Or should i come back to old kind setup/setuptestdata and teardown /teardownclass? If I have ‘module’ scoped fixture … -
Docker - served react app, asset-manifest.json with incorrect filenames
I'm new to web development, and I run into a strange error. I have a React/Django app which I'm trying to productionize with nginx and docker. Django runs on a postgres db, and nginx just reroutes port 80 to my react and django ports. When I locally deploy the application using npm run build serve -s build everything works as desired. However, doing the same through Docker doesn't. I have a Dockerfile building the react application: FROM node:12.18.3-alpine3.9 as builder WORKDIR /usr/src/app COPY ./react-app/package.json . RUN apk add --no-cache --virtual .gyp \ python \ make \ g++ \ && npm install \ && apk del .gyp COPY ./react-app . RUN npm run build FROM node:12.18.3-alpine3.9 WORKDIR /usr/src/app RUN npm install -g serve COPY --from=builder /usr/src/app/build ./build Now when I use docker-compose build docker-compose up I see that my Django, React, Postgres and nginx containers are all running, with nginx visible at port 80. When I open localhost in my browser, I see nginx is looking for some static react files in the right directory. However, the react files it is looking for have a different hash than the static files. The static files of both the nginx and react container … -
Using localStorage to force specific window tab or popup window to reload
I am working on a Django project where we protocol documents and the protocol number should appear in a modal message popup, after the form is submitted and closed. The requested function is that if a file is protocolled either from the main window or from a popup list of documents it should always present a modal window with the number of the protocol, the file has been assigned with. I have written a JQuery script that based on certain conditions (page URL contains-or-not specific strings), it sets the localStorage value of UPDATE to 1. When that happens, it forces the active window or popup window to reload in order to display a modal with the assigned protocol number. Unfortunately the reloading doesnt happen as I would like it to happen. It works most of the time but there are times where it either: forces a second reload of the page or doesnt force a reload at all and I have to do it manually or (when the script is activated in a popup) it reloads the main page instead of the popup or (when the script is activated in a popup) it reloads the popup but the modal message … -
which one is better use Django for full-stack? or Keep the front end separate and handle the ui with API calls
Based on performance and maintenance(includes library availability) which one is better. use Django as full-stack or keeping ui in separate (like using React or other library or framework) and handle with api calls?.Please kindly do needful. -
ValueError when trying to create a following relationship in Django
I have looked through the similar SOverflow questions and no answer helped. I am trying to create a follower/following relationship when a button is pressed, passing the info through Javascript... function follow(user) { fetch(`/profile/${user.id}`, { method: 'POST', body: JSON.stringify({ followed: user.id }) }) .then(response => response.json()) .then(() => load_profile(user.id)) } ...then I receive it and try to save it or update it... @csrf_exempt @login_required def view_profile(request, user_id): if request.method == "POST": data = json.loads(request.body) followed = data.get("followed", "") follower = request.user.id obj, created = UserFollowing.objects.get_or_create(user_id=followed, following_user_id=follower, following=True) if not created: obj(following=False) obj.save() return JsonResponse({"message": "(Un)Followed successfully."}, status=201) ... and this is the model: class User(AbstractUser): pass def serialize(self): return { "id": self.id, "user": self.username, "following": self.following.count(), "followers": self.followers.count(), } class UserFollowing(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="following") following_user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="followers") following = models.BooleanField(blank=False, default=True) ERROR: ValueError: Cannot assign "3": "UserFollowing.user_id" must be a "User" instance. I have tried to pass different values such as the username, the object itself, to no avail. -
How do I assign an ID to a div using Django?
I'm using mezzanine, based on the django framework of Python and I'm trying to add a method for my blog posts. In the models.py I have added an incremental counter to be used as an id reference. ` def get_new_id(): n = 100 i = 1 for i in range(n): if i ==100: break print (i) ##just checking if it actually did what I asked return i This way I want to be able to show the newest post on my homepage without having to change it manually. I'd probably still need to reverse the count so the last blogpost becomes number 1, but regardless, the issue is not that. I understand the code might already be too little for what I want it to do but even this simple loop does not print i in the console, let alone place itself into the meta tag. I have added the reference to the method in the correct html page (or so I believe) from blog_post_list.html {% for blog_post in blog_posts.object_list %} <div id="{{ blog_post.get_new_id }}" class="post-preview"> <a href="{{ blog_post.get_absolute_url }}"> <h2 class="post-title"> {{ blog_post.title }} </h2> </a> {% if settings.BLOG_USE_FEATURED_IMAGE and blog_post.featured_image %} {% block blog_post_list_post_featured_image %} <a href="{{ blog_post.get_absolute_url … -
How to make a browser send notification when you change the windows or tabs
So, I want to make a web app for tests. Usually students try to cheat so they change the tabs or open other apps and search for their info.So, I use fiverr, and you can take skill tests on fiverr and if you tried to change the browser, for example ALT + TAB the test would stop.How can I implement a function like that with django or js? -
I am getting a No such table error in Django
I have read lot's of questions/answers trying to solve this. I am currently working on a website. The problem I am getting is the following: All my website was working Then I added two new models and changed 2 models name's After that I did 'python manage.py makemigrations' And 'python manage.py migrate' Everything seemed okay, but when I went to admin page (after adding the models to admin) the two new models and the models that I have changed names are not working. When I click on them in the admin page I get 'No such table: <table_name>'. I am going to show you... models.py theme = models.CharField(max_length=100) def __str__(self): return f'{self.theme}' class Question(models.Model): title = models.CharField(max_length=30, default="Title") theme = models.ForeignKey(Theme, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) content = models.TextField() post_date = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.title}' class UpVote(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) post = models.ForeignKey(Question, on_delete=models.CASCADE) class Answer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) post = models.ForeignKey(Question, on_delete=models.CASCADE) comment = models.TextField() post_date = models.DateTimeField(default=timezone.now) # ARTICLES___________________________________________________________________________________________ class ArticleTheme(models.Model): theme = models.CharField(max_length=20) def __str__(self): return f'{self.theme}' class Article(models.Model): title = models.CharField(max_length=30) author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) theme = models.ForeignKey(ArticleTheme, on_delete=models.CASCADE) pdf = models.FileField(upload_to='pdf', null=True) date_posted = models.DateTimeField(default=timezone.now) date_altered = models.DateTimeField(default=None, … -
How to filter and displayed 'many to many' elements in Django
I'm learning django and in my project can't figure out how properly get and displayed elements from many to many relation on deck detail page. model.py class Card(models.Model): def upload_path(self, filename): return os.path.join('cards/', filename) image = models.ImageField(upload_to=upload_path) card_num = models.CharField(max_length=20, default='') name = models.CharField(max_length=500, default='') desc = models.TextField(max_length=500, default='') card_class = models.OneToOneField(CardClass, on_delete=models.DO_NOTHING, default='') cost = models.OneToOneField(Cost, on_delete=models.DO_NOTHING, default='') card_type = models.OneToOneField(CardType, on_delete=models.DO_NOTHING, default='') rarity = models.OneToOneField(Rarity, on_delete=models.DO_NOTHING, default='') resource = models.IntegerField(default=None) attack = models.IntegerField(default=None) defence = models.IntegerField(default=None) def __str__(self): return self.name def get_absolute_url(self): return reverse('card:cardPageDetail', args=[self.name]) class Deck(models.Model): def upload_path(self, filename): return os.path.join('decks/', filename) image = models.ImageField(upload_to=upload_path) user = models.ForeignKey(User, on_delete=models.CASCADE) cards_list = models.ManyToManyField(Card, related_name='cards_list') deck_id = models.CharField(max_length=10, default='') name = models.CharField(max_length=500, default='') desc = models.CharField(max_length=500, default='') price = models.CharField(max_length=500, default='') def __str__(self): return self.name def get_absolute_url(self): return reverse('card:deckPageDetail', args=[self.name]) views.py def deckPageDetail(request, name): deck=get_object_or_404(Deck, name=name) cards_all = Card.objects.all() queryset = cards_all.objects.filter(cards_list__in=deck.deck_id) print(queryset) context = { 'deck': deck, 'cards_in_deck': queryset, } return render(request, 'landing/deck_detail.html', context) I tried few solutions based on stackoverflow and uncle google, but without results.I will be grateful for help. -
NoReverseMatch at /add_post
I have been working on a blog site using django and I made a way to add post within the home page without going to the admin page but when I post using the new way I get this error NoReverseMatch at /add_post Reverse for 'article-view' with arguments '('3', '0')' not found. 1 pattern(s) tried: ['article/(?P<pk>[0-9]+)$'] This is my models.py file from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(max_length=3500) def __str__(self): return (self.title + " | " + str(self.author)) def get_absolute_url(self): return reverse("article-view", args=(str(self.id))) This is the views.py file from django.views.generic import ListView, DetailView, CreateView from .models import Post class HomeView(ListView): model = Post template_name = "home.html" class ArticleDetailView(DetailView): model = Post template_name = "detail_view.html" class AddPostView(CreateView): model = Post template_name = "add_post.html" fields = "__all__" This is the polls/urls.py from django.urls import path from .views import HomeView, ArticleDetailView, AddPostView urlpatterns = [ path('', HomeView.as_view(), name='home'), path('article/<int:pk>', ArticleDetailView.as_view(), name='article-view'), path('add_post', AddPostView.as_view(), name='add_post'), ] This is the add_post.html file {% extends 'base.html' %} {% block content %} <head> <title>Adding Post</title> </head> <h1>Add Blog Posts</h1> <form method="POST"> {% csrf_token %} {{ form.as_p }} … -
Django, ElasticBeanstalk, SES and Celery not working when I load to AWS
I have a django application with celery using AWS SES as a broker. When I run celery from my PC using the SES service it works fine. But when I try and load to AWS via ElasticBeanstalk I'm getting the following error in my eb-activity.log file [include] files: uwsgi.conf celery.conf celerybeat.conf [inet_http_server] port = 127.0.0.1:9001 celerybeat: available celeryd: available celeryd: added process group celerybeat: added process group celeryd: stopped celeryd: ERROR (abnormal termination) celerybeat: stopped celerybeat: ERROR (abnormal termination) I'm trying to set celery running using this config file (which I copied/modified from another stackoverflow answer I cannot now find) files: "/opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh": mode: "000755" owner: root group: root content: | #!/usr/bin/env bash # Create required directories sudo mkdir -p /var/log/celery/ sudo mkdir -p /var/run/celery/ # Create group called 'celery' sudo groupadd -f celery # add the user 'celery' if it doesn't exist and add it to the group with same name id -u celery &>/dev/null || sudo useradd -g celery celery # add permissions to the celery user for r+w to the folders just created sudo chown -R celery:celery /var/log/celery/ sudo chown -R celery:celery /var/run/celery/ # Get django environment variables celeryenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/%/%%/g' | … -
how can i get the uploaded file in Django template?
in this template: {% block content %} <form method="post" enctype="multipart/form-data"> <input type="file" id="files" name="files" multiple="multiple" /> <p class="container" style="margin-top: 10px"> <input type="submit" value="upload" class="btn btn-primary" /> </p> </form> {% endblock%} how can I get the uploaded file in the views.py I want to get the file, edited it, and render the edited file to another template. -
Why do I get this error in Admin Page Not Found [closed]
I finished my project and I am trying to upload in Production, my website works correctly but I am having an error PAGE NOT FOUND when I try to add/save a blog in Django Admin. It throws an error Page not found. What can I do? -
django static files error 400 - aws lightsail
I followed amazon docs on how to Deploy A Django Project My settings.py DEBUG = False ALLOWED_HOSTS = ['X.XXX.XXX.XXX'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'HOST': 'localhost', 'PORT': '5432', 'USER': 'postgres', 'PASSWORD': 'mypass' } } STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'cms/static') ] I used 'Host': 'localhost' because 'HOST': '/opt/bitnami/postgresql/', gives me this error which I have asked a question about here: django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/opt/bitnami/postgresql/.s.PGSQL.5432/.s.PGSQL.5432"? and python manage.py collectstatic --noinput works fine just like in my laptop. I added static root in urls.py: urlpatterns = [ path('', include('myapp.urls')), . . ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) under /opt/bitnami/apache2/conf/vhosts I created two files: cms-http-vhost.conf : <IfDefine !IS_CMS_LOADED> Define IS_CMS_LOADED WSGIDaemonProcess cms python-home=/home/bitnami/py37-venv/ python-path=/home/bitnami/project/cms </IfDefine> <VirtualHost 127.0.0.1:80 _default_:80> ServerAlias * WSGIProcessGroup cms Alias /robots.txt /home/bitnami/project/cms/static/robots.txt Alias /static/ /home/bitnami/project/cms/static/ <Directory /home/bitnami/project/cms/static> Require all granted </Directory> WSGIScriptAlias / /home/bitnami/project/cms/cms/wsgi.py <Directory /home/project/cms/cms> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> and cms-https-vhost.conf: <IfDefine !IS_CMS_LOADED> Define IS_CMS_LOADED WSGIDaemonProcess cms python-home=/home/bitnami/py37-venv/ python-path=/home/bitnami/project/cms </IfDefine> <VirtualHost 127.0.0.1:443 _default_:443> ServerAlias * SSLEngine on SSLCertificateFile "/opt/bitnami/apache2/conf/bitnami/certs/server.crt" SSLCertificateKeyFile "/opt/bitnami/apache2/conf/bitnami/certs/server.key" WSGIProcessGroup APPNAME Alias /robots.txt /home/bitnami/project/cms/static/robots.txt Alias … -
Mysql key specification on ALTER TABLE
I have this code that was handed down to me with engine.connect() as con: con.execute('ALTER TABLE `mystuff` ADD PRIMARY KEY (`index`);') But I get the following error '(1170, "BLOB/TEXT column 'index' used in key specification without a key length")' [SQL: CREATE INDEX ix_mystuff_index ON mystuff (index)] -
How do I add users to access to the postgres apart from the admin using django
How to add users to the postgres users in pgadmin4 on django server, beside the admin user? Example: A website is created where there is a login button to enter into the website. The admin has the access to it by creating a python manage.py createsuperuser but If I want to add another users to access to the site how should i add them ? -
How to limit Simultaneous logins in Django Rest auth
I have a project that has a custom user model extended by AbstractBaseUser and for login I'm using an endpoint provided by django rest auth (rest-auth/login). So my question is how can prevent same user is login with another device. I need to display somethin like "You have already logged in" when a user tries to login with another device while he logged into the system Thanks! -
How to get data dictionary based on Django models?
Just wonder how to get the whole data dictionary(markdown or html or text) based on the all Django models. Like this #### payinfo | field | type | default | comment | | --- | --- | --- | --- | | id | int(11) | None | id | | school | varchar(32) | None | school | | com_id | varchar(32) | None | com_id | | remark | varchar(50) | None | remark | | status | int(11) | None | status | | company_id | int(11) | None | company_id | | php_path | varchar(32) | None | php_path | -
getting error while postgres connecting to Django
madhu@DESKTOP-9CAUDPK:/mnt/f/backup/PycharmProjects/Ecommerce/ecommerce$ python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/home/madhu/.local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/home/madhu/.local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/madhu/.local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/home/madhu/.local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/madhu/.local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "/home/madhu/.local/lib/python3.8/site-packages/psycopg2/init.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "madhu" FATAL: password authentication failed for user "madhu" The above exception was the direct cause of the following exception: 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/madhu/.local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/madhu/.local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/home/madhu/.local/lib/python3.8/site-packages/django/core/management/base.py", line 458, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/madhu/.local/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "/home/madhu/.local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 49, in init self.build_graph() File "/home/madhu/.local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/madhu/.local/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 76, in applied_migrations if self.has_table(): File "/home/madhu/.local/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/madhu/.local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, … -
NoReverseMatch at / Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['posts/(?P<pk>[0-9]+)/$']
I'm building a django blog app. But, when I'm trying to build detail pages for blog posts, I'm getting this error: NoReverseMatch at / Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['posts/(?P<pk>[0-9]+)/$'] This is my post_detail view function: def post_detail(request,post_id): post = get_object_or_404(Post, id=post_id) return render(request, 'blog/detail.html',{'post':post}) My url route: path('posts/<int:post_id>/',views.post_detail,name='detail'), And the line that links to detail page: <p class="lead my-3"><a href="{% url 'blog:detail' post.id %}" class="text-white font-weight-bold">{{ latest_post.title }}</a></p> I don't think I should have any error in this. Where am I going wrong? -
how to use django-import-export in DRF?
The result of installing import-export and importing from the admin page I got the following error How can I fix it? error : Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\import_export\resources.py", line 639, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\ProgramData\Anaconda3\lib\site-packages\import_export\resources.py", line 334, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\ProgramData\Anaconda3\lib\site-packages\import_export\resources.py", line 322, in get_instance self.fields[f] for f in self.get_import_id_fields() File "C:\ProgramData\Anaconda3\lib\site-packages\import_export\resources.py", line 322, in self.fields[f] for f in self.get_import_id_fields() KeyError: 'id' enter code here admin.py from django.contrib import admin from .models import Country from import_export.admin import ExportActionModelAdmin, ImportExportMixin, ImportMixin @admin.register(Country) class CountryAdmin(ImportExportMixin, admin.ModelAdmin): list_display = [ "country_ID", "iso_code", "cname_en" ] -
How can I get the Django auth SetPasswordForm to display errors?
I am using Django's SetPasswordForm to allow the user to reset their own password.They will have been sent an email and clicked on a link which directs them to: /users/new-password/uid/token urls.py path('new-password/<uidb64>/<str:token>/', views.NewPassword.as_view(), name='new-password'), views.py class NewPassword(View): url = 'users/new_password.html' def get(self, request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is None or not account_activation_token.check_token(user, token): text = 'Your password cannot be reset. Please contact support.' messages.error(request, text) return HttpResponseRedirect(reverse('account')) password_form = SetPasswordForm(user=user) context = { 'password_form': password_form, 'uidb64': uidb64, 'token': token, } return render(request, 'users/new_password.html', context) def post(self, request, uidb64, token): uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) password_form = SetPasswordForm(user=user) if not password_form.is_valid(): context = { 'password_form': password_form, 'uidb64': uidb64, 'token': token, } return render(request, self.url, context) messages.success(request, 'Your password has been reset. You may now sign in.') return render(request, reverse('login'), context) new_password.html <form method="post" action="{% url 'new-password' {{ uidb64 }} {{ token }} %}"> {% csrf_token %} <h1>Set New Password</h1> <table> {% for field in password_form %} <tr> <td>{{ field.label_tag }}</td> <td>{{ field }}</td> {% if field.errors %} {% for error in field.errors %} <td style="color: red">{{ error }}</td> {% endfor %} {% endif %} </tr> …