Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Updating a group of Django objects in one click
I have a Message model with an 'unread' field set to default=True: class Message(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) sender = models.ForeignKey(Profile, on_delete=models.CASCADE) message = models.TextField(blank=True) unread = models.BooleanField(default=True) I want to be able to select a group of these objects at once and update their unread status to False on click. Each of them are currently being displayed with a checkbox alongside, and I have a form on top: <form action="{% url 'users:read_message' %}" method="post"> {% csrf_token %} <button type="submit">Mark as read</button> </form> {% for msg in messages %} <input type="checkbox" name="message" value="{{ msg.id }}"> <p>{{ msg.message }}</p> {% endfor %} And here is the view: def message_read(request): if request.method == 'POST': selected_messages = request.POST.getlist('message') for message in selected_messages: read = Message.objects.get(pk=message) read.update(unread=False) return redirect('users:messages') return redirect('users:messages') At the moment my request.method == 'POST' is always returning false. Is anyone able to explain what I've done wrong? -
Celery app didnt see settings specified in settings.py file
I am trying to extend my django app with celery functionality i created celery.py file in project/project directory where i put code as mentioned in [official documentation][1] Here is the code import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE','project.settings') app=Celery('project') app.config_from_object('django.conf::settings',namespace='CELERY') Than inside my project/settings.py file i specified related to celery configs as follow CELERY_TIMEZONE = "Europe/Moscow" CELERYBEAT_SHEDULE = { 'test_beat_tasks':{ 'task':'webhooks.tasks.adding', 'schedule':crontab(minute='*/1), }, } Than in command line **python manage.py shell #i imported app from project.celery.py module from project import celery #than examined app configs celery.app.conf And inside huge output of celery configs i see that timezone is None As i understand my problem is that initiated in project/celery.py app isn't accept my project/settings.py celery related config but why so? What i am doing wrong? Please guide me [1]: https://docs.celeryproject.org/en/stable/django/first-steps-with-django.html -
ML_Model deployment with Django (JOBLIB)
I am trying to deploy ML model with Django. I have done already three of them. At the beginning it worked. Because of some kind of reasons, it stopped working now. What exactly happens. When I enter the data, it should return the list of the entered parameters, and the result. Unfortunately, django model does not return either the entered data or the result. It is interesting that it worked on my first project (https://github.com/RG-911/Car-Price-Prediction.git). Now, it stopped partially (does not return list of entered parameters) working on this project, too. In the second project and third project it returns neither parameters and results. The second project: https://github.com/RG-911/Car-type-prediction.git The third project: https://github.com/RG-911/Mobile-OS-detection.git YOU MAY DOWNLOAD .RAR FILES OF THE DJANGO MODELS. Thanks in advance for the help. -
Sentry doesn't take into account level param for capture_message()
When I call in my code capture_message(level="INFO") sentry marks it as an error. I tried other logging levels, but result is the same. Here are my settings for django: sentry_sdk.init( ... integrations=[ ... LoggingIntegration( level=logging.INFO, event_level=logging.ERROR, ), ] ) Basically I need to mark my custom message as warning. How can I achieve it? -
Django graphene generate schema
Is there a way how to dynamically generate Django graphene schema from Django models? I am trying to reduce my code as I have a lot of models and each model has to have in my schema.py file a Query, Type Class, and a resolve function. This is becoming overwhelming to maintain as my amount of models and model fields grow. class blog_postType(DjangoObjectType): class Meta: model = models.blog_post filter_fields = get_all_model_fields(models.blog_post) class Query(ObjectType): post = graphene.List( blog_postType, id=graphene.Int(), title=graphene.String(), ) def resolve_blog_post(self, info, **kwargs): return model.blog_post.objects.all() schema = graphene.Schema(query=Query,mutation=Mutation) this is a small example, which grows by having a huge amount of models. -
Update custom UserAdmin's `change_password_form` to use PasswordChangeForm
Using django 2.2. I have a custom user inheriting from AbastractUser, and the default user password change form to include the user's old password. I've found that django includes PasswordChangeForm which includes old password entry along with new_password1, new_password2. I've tried to set change_password_form but when I click the related user "change password" link, the resulting password change view displays no fields. from myapp.models import MyCustomUser from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.admin.forms import PasswordChangeForm @admin.register(MyCustomUser) class MyCustomUserAdmin(UserAdmin): list_display = list(UserAdmin.list_display) list_display.remove("first_name") list_display.remove("last_name") ordering = ("-date_joined",) search_fields = ("username", "email") change_password_form = PasswordChangeForm fieldsets = ( (None, {"fields": ("username", "client", "password")}), (_("Personal info"), {"fields": ("email", "confirm_email")}), (_("Permissions"), {"fields": ("is_active", "is_superuser")}), ) How can I update the my CustomUserAdmin to use a form that forces the user to re-entry their original password? -
'PictureDetail' object has no attribute 'user'
When I am not logged in and click on the Download link, this error appears. AttributeError at /pictures/5/ 'PictureDetail' object has no attribute 'user' I want the picture to be downloaded only by the user who has at least one uploaded picture. I could put LoginRequiredMixin as an attribute of the PictureDetail class and that would solve the problem, but I only need to hide the Download link and not the whole picture. views.py class PictureDetail(DetailView): model = Picture @login_required def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if Picture.objects.filter(user=self.request.user).exists(): context["download"] = True return context models.py class Picture(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) picture_detail.html {% if download == True %} <p class="card-text"><a href="{{ picture.picture.url }}">Download</a></p> {% endif %} -
Django 3.1 deployment on Heroku - collectstatic fails
I have seen very similar posts on this issue on this and other websites. However, most of the answers I found were either outdated, sloppy, or just did not work. Heroku is not letting me push my Django app because of a failure due to collection of static files. Code settings.py: from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent STATIC_ROOT = BASE_DIR / "staticfiles" STATIC_URL = "/static/" STATICFILES_DIRS = [BASE_DIR / "static"] Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED=1 RUN mkdir /usr/src/app WORKDIR /usr/src/app COPY requirements.txt /usr/src/app RUN pip install -r requirements.txt COPY . /usr/src/app docker-compose.yml: version: "3.8" services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres migration: build: . command: python manage.py migrate volumes: - .:/usr/src/app depends_on: - db web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - db - migration Procfile: web: gunicorn my_app.wsgi requirements.txt: django psycopg2 gunicorn runtime.txt: python-3.9.0 Error When I run git push heroku master I get the following error... Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ … -
How can anormal user view Django admin logs?
I am makink a blog project with django. I want each user to see the logs (post aprroval time, comment approval time etc) of admin.How can i do? -
How to build dashboard in python? (Level : beginner) [closed]
I have a jupyter notebook with matplotlib graphs and I want to build a dashboard in python, but as a newbie, I'm confused about how should I do this? There are different things like plotly dash, Django, Tkinter, etc. What should I learn? and How this process of building a dashboard from code in 'jupyter notebook' works? what are the steps involved in it? The code I want to build a dashboard from is from this website -
DRF simple jwt getting auth token from a user instance OR change username and password combination
I have a chat app that uses the same authentication method as in WhatsApp. Normally I would get the jwt auth token with this: path('api/token/', ObtainPairViewToken.as_view(), name='token_obtain_pair'), However This asks for both username and password while my user model is using phone_number and a validation code instead. Is there any way to change this? username ======> phone_number password ======> phone_code (The validation code) The second way Is to pass the user instance and get the auth token from it somehow my Login view @api_view(['POST',]) def loginuser(request): if request.method == 'POST': phone_number = request.data.get('phone_number') try: user = User.objects.get(phone_number=phone_number) if int(request.data.get('phone_code')) == user.phone_code and user.phone_code: # user.phone_code = None # user.save() return Response({'phone_number': phone_number}, status.HTTP_200_OK) else: return Response({'error': "Invalid code"}, status.HTTP_400_BAD_REQUEST) except Exception as error: return Response({'error': error}, status.HTTP_500_INTERNAL_SERVER_ERROR) my user model: class User(AbstractUser): phone_number = PhoneNumberField(unique=True) username = models.CharField(max_length=30) password = models.CharField(null=True, blank=True, max_length=20) about = models.CharField( max_length=190, default="Hi, I use Orgachat!", blank=True, null=True) ... phone_code = models.IntegerField(blank=True, null=True) USERNAME_FIELD = 'phone_number' def __str__(self): return str(self.username) # Save auth token, I know this should be in signals.py but whatever @receiver(post_save, sender=User) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) -
Registration form in Django using [intl-tel-input] to take international phone number from user
everybody. I'm using [intl-tel-input] library to take international phone number from users during registration but i don't know how to store the phone number in database. But i'm using django model form to store the rest of the inputs. I need your help. -
Show customer orders in one model Django
I am creating an eCommerce website for my client. I am completely new to Django. I am following a tutorial: creating an eCommerce Django website. In tutorial instructor creates 3 models: Customer, Order, Order_Items. I did not like the model setup in that tutorial. When a customer places an order, in database order created and seperate order_items being created and they are being assigned to order. I want something different like in Wordpress Woocommerce, when a customer places an order, in the admin dashboard you can see Customer order, and when you view that order it shows products and their price, quantity, and total price in one place. I want to make an Order model that contains and shows: customer name, products, quantity, and total product price. As far as I know, Order and Order_item is a common solution for creating order but for the website admin(for my client), it would be very hard to understand and keep track of customer orders. I couldn't find any solution on the Internet. It would be great if you could give me an idea of how to solve this problem. Thanks in advance! -
Django share users in different databases causes 500 and 403 errors
The goal I want Doccano to use the users that are saved in my other app (app2) as its own users, instead of Doccano keeping its own users. These are both Django databases, so i assume these are not doccano specific issues The problem The connection between the users work, i can login in doccano with app2 users. when in the /projects page an 500 internal server error arises on the website and on the terminal app2 prints: "ERROR: relation "api_project" does not exist at character 363" When creating a new project a 403 Forbidden arises when doing a POST to /v1/projects What i did I am currently running the Doccano Backend, nginx and postgres in their containers and running app2 and the postgres_app2 in containers as well. Doccano backend shares a (docker-compose)network with Doccano postgres and another network with postgres_app2. doccano/app/app/settings.py has both databases and a link to the router: # settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': path.join(BASE_DIR, 'db.sqlite3'), }, "app2_db": { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": os.getenv("POSTGRES_USER", "user_app2"), "PASSWORD": os.getenv("POSTGRES_PASSWORD", "pass_app2"), "HOST": "postgres", "PORT": 5432, } } DATABASE_ROUTERS = ['app.authRouter.AuthRouter'] with the AuthRouter.py looking like this: # AuthRouter.py class AuthRouter(object): def db_for_read(self, model, **hints): if … -
Django with SQLite - Database is locked - does it throw error? When does it occur?
I'm using Django + sqlite for my hobbist project (Gallery script). The whole script isn't very write-heavy. The only writes to database is incrementing views for each browsed photo. Today I was browsing logs and noticed few "Database is locked" errors. I know this is sqlite's issue, but I'm not sure how Django handles it. I'm unable to reproduce the error on my own, therefore I have two questions. If the "Database is locked" error occurs during the user visit (number of views update is called from PhotoDetailView) does it end up in 500 error or the user stills sees the photo? Does it fail silently (counter not updated, print to logs)? How does the single no parallel writes rule work for SQLite? Is it single write at given time for whole database or table? Item? Any ideas how can I manually lock the database to reproduce the "database is locked" error? -
how can i export excel file to views.py django project
i am trying to export a column in excel file in my database to a list then render it to my template. m code is: def home(request): ch = chart.objects.get() a= ch.chart_file.path labels = a['x'].tolist() b = [float(n) for s in labels for n in s.strip().split(' ')] context = { 's': b } return render(request, 'home.html', context) and in template: {% block content%} {% for i in s %} <p>{{ i }}</p> {% endfor % {%endblock%} but it raise this error: string indices must be integers how can i fix it? -
Cannot solve Error while running '$ python manage.py collectstatic --noinput'
I dont know what is going wrong but i cannot deploy my app in heroku. Everytime its throwing me this error but my code seems fine. I have also created staticfiles folder in my root-directory with an empty css file. Please can anybody help. I dont know if this issue is caused by static files or not. My error during deployment: -----> Python app detected ! Python has released a security update! Please consider upgrading to python-3.8.6 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Installing python-3.8.5 -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 -----> Installing SQLite3 -----> Installing requirements with pip Collecting asgiref==3.2.10 Downloading asgiref-3.2.10-py3-none-any.whl (19 kB) Collecting certifi==2020.6.20 Downloading certifi-2020.6.20-py2.py3-none-any.whl (156 kB) Collecting chardet==3.0.4 Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB) Collecting Cython==0.29.21 Downloading Cython-0.29.21-cp38-cp38-manylinux1_x86_64.whl (1.9 MB) Collecting dj-database-url==0.5.0 Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) Collecting Django==3.1.1 Downloading Django-3.1.1-py3-none-any.whl (7.8 MB) Collecting django-crispy-forms==1.9.2 Downloading django_crispy_forms-1.9.2-py3-none-any.whl (108 kB) Collecting django-embed-video==1.3.3 Downloading django_embed_video-1.3.3-py3-none-any.whl (24 kB) Collecting django-js-asset==1.2.2 Downloading django_js_asset-1.2.2-py2.py3-none-any.whl (5.8 kB) Collecting django-mptt==0.11.0 Downloading django_mptt-0.11.0-py2.py3-none-any.whl (109 kB) Collecting gunicorn==20.0.4 Downloading gunicorn-20.0.4-py2.py3-none-any.whl (77 kB) Collecting idna==2.10 Downloading idna-2.10-py2.py3-none-any.whl (58 kB) Collecting numpy==1.19.4 Downloading numpy-1.19.4-cp38-cp38-manylinux2010_x86_64.whl (14.5 MB) Collecting Pillow==7.2.0 Downloading Pillow-7.2.0-cp38-cp38-manylinux1_x86_64.whl (2.2 MB) Collecting python-decouple==3.3 Downloading python-decouple-3.3.tar.gz (10 kB) Collecting pytz==2020.1 Downloading pytz-2020.1-py2.py3-none-any.whl (510 kB) Collecting requests==2.24.0 Downloading requests-2.24.0-py2.py3-none-any.whl … -
Django Admin Site -- view path "admin/" at "/"
I'm developing a Django (3.1) app that only uses the Admin Site. The default behavior is then to serve the Admin Site with the path: http://localhost:8080/admin/ Which assumes that you have other sites at http://localhost:8080/other_site Because my only site is the Admin Site, I'd like to serve the admin site at: http://localhost:8080/ without the admin/. Here is the file website/urls.py (website folder has all the settings/config) from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('management/', include('management.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And here is the file management/urls.py (management is the app with all the models) from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] How can I do this? -
Can I use single database for different Django website? [closed]
Q. Can I use single database for different Django website? . If the yes then how can I use data from the database in my views.py? . I was working on a website which will have different versions one for desktop users. Url will be like example.com and other for mobile user m.example.com. How can i use similar database for these two website. I am using Django=2.2 and sqlite -
Flask: get the context on the filter
I'm a beginner at the flask, I want to practice filter, I've read the official documentation, but it doesn't help. I want to create a firstof filter, i.e., Outputs the first argument variable that is not “false” .(same as Django's firstof). <h1>Hi, {{ "username, 'guest'"| firstof }} </h1> @app.route('/') def index(): return render_template('index.html') # expect output: Hi, guest # return render_template('index.html', username='Carson') # Hi, Carson I try, @app.template_filter('firstof') def firstof_filter(s: str): """ USAGE:: {{ "var1, var2, 'default_val'" | firstof }} """ for data in s.split(','): data = data.strip() if data[0] == data[-1] and data[0] in ("'", '"'): return data[1:-1] # a constant """ # does any similar grammar like below? if hasattr(app.current.context, data): return app.current.context[data] """ It would be nice if you could provide more links about flask-filter. thanks! -
Django form include Many2Many field from related_name
I have two models with two update forms. Now I want to achieve two things: be able to edit a certificate and set all the servers this certificate is used on be able to update a server and set all the certificates which are used on this server. class Certificate(models.Model): internal_name = models.CharField(max_length=1024) pem_representation = models.TextField(unique=True) servers = models.ManyToManyField( Server, related_name='certificates', blank=True) class Server(models.Model): name = models.CharField(max_length=1024, unique=True) class CertificateUpdateForm(forms.ModelForm): class Meta: model = models.Certificate fields = ['internal_name', 'pem_representation', 'servers'] class ServerUpdateForm(forms.ModelForm): class Meta: model = models.Server fields = ['name', 'certificates'] Without the field "certificates" in ServerUpdateForm I get no error but when updating via the form the changes for the certificates just aren't recognized. The error message I get with this code is: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib64/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib64/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File " venv/lib64/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File " venv/lib64/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File " venv/lib64/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File " venv/lib64/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File " venv/lib64/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File " venv/lib64/python3.8/site-packages/django/core/checks/urls.py", line 23, … -
pytest no django "lazy_django.py no Django settings"
my project list: main_project - projects/ - tests/ - project1/ - django_project/ - tests/ - django_app/ - django_project/ - manage.py now, when I on main_project path, run pytest ./projects/django_project, it can pass django_project pytest. But I want run one pytest to run wholl pytest including project1 & django_project on main_project path, it passed all project1 pytests, but auto skipped django_project's pytest, when I run with pytest -rsx it shows: SKIPPED [2] .../local/lib/python3.6/site-packages/pytest-django/lazy_django.py:14: no Django settings Any suggestion? thanks! -
Template inheritance with dynamic content
Is it possible to make one sub-template inherit a div with dynamic content from an upper level template? For eg., there are 3 templates as following: base.html <!DOCTYPE html> <html> <head> </head> <body> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> level_1_template.html {% extends "base.html" %} {% block content %} <div id="dynamic-level1"> ...some elements here that depend on variable {{ level_1_var }}} </div> {% block level2_content %} {% endblock %} {% endblock %} level_2_template.html {% extends "level_1_template.html" %} {% block level2_content %} ...doing level 2 stuff here ... {% endblock %} In this generic example, level_1_var variable is passed into the corresponding view for that template and not the view for level_2_template.html When rendering level_2_template.html, div dynamic-level1 is not rendered. Is there a way to make this inheritance possible? Of course, one way is to repeat the whole thing in level_2_template.html and to pass the variable level_1_var to the corresponding view. But this does not seem like a decent (or DRY) way to do. Thanks. -
Insert into many to many field Django
I'm trying to build Reddit in Django and for that, I am creating a board where users can discuss topics. But I am not able to map user and board. Model: class Board(models.Model): id = models.AutoField(primary_key=True) unique_id = models.CharField(max_length=100, null=False, unique=True) created_by = models.ForeignKey(User_Detail, on_delete=models.CASCADE, related_name="board_creator") name = models.CharField(max_length=100, null=False, unique= True) class UserBoardMapping(models.Model): user = models.ManyToManyField(User_Detail) board = models.ManyToManyField(Board) user_type = models.CharField(max_length=10, choices=USER_TYPE, default='moderator') My view: class CreateBoard(APIView): def post(self, request): data = JSONParser().parse(request) unique_id = data.get('board_id', None) created_by = data.get('created_by', None) name = data.get('name', None) if not created_by or not name: return Response({'ERROR': 'Please provide both username and password'}, status=status.HTTP_400_BAD_REQUEST) if Board.objects.filter(name=name).exists(): return JsonResponse({'ERROR': "Board Already registered! "}, status=status.HTTP_409_CONFLICT) if not User_Detail.objects.filter(username=created_by).exists(): return JsonResponse({'ERROR': "Username is not registered! "}, status=status.HTTP_404_NOT_FOUND) username = User_Detail.objects.get(username=created_by) board = Board(unique_id=unique_id, created_by=username, name=name) board.save() user_board_mapping = UserBoardMapping(user=username, board=board) user_board_mapping.save() UserBoardMapping is not working, how can I map user and board and Insert data in many to many field what am I doing wrong here in this code? -
Error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
I want to fetch some data from API, but I get the error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 I've checked the code a hundred times but obviously there is something I'm missing. Can anybody see what I'm missing? also if that can help too it returns me Promise {<pending>} with [[PromiseState]]: "rejected" My function for the api from django views: def fetchapi(request): url = 'https://prime.webflow.com:30190/data_link' params={"user":"test", "api_key":"notarealapikey", "act":"get_system_users", "user_id":"all"} response = requests.get(url, params) #Read the JSON users = response.json() #print(users) #Create a Django model object for each object in the JSON and store the data in django model (in database)""" for user in users: Employee.objects.create(status=user['status'], email=user['user_email'], name=user['user_name'], webflow_id=user['user_id'], user_type=user['user_type']) context = { "users": Employee.objects.all(), } return render(request, 'fetchapi.html', context) fetchapi.html {% extends 'main.html' %} {% block content %} <h1>FetchAPI</h1> <script> function fetchData(){ fetch("http://192.168.2.80:8000/fetchapi/").then(response => { const data = response.json(); console.log(data) }); } fetchData(); </script> {% endblock %} what my json looks like I tried to print it in the terminal from views: { 'status': 'active', 'user_email': '', 'user_id': 701, 'user_name': 'formapi', 'user_type': 'backoffice' },