Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
plz help mw sir I am getting error when i run migrate commad
mayur@mayur-Latitude-E5440:~/Desktop/practice/myproject$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/lib/python3/dist-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/usr/lib/python3/dist-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python3/dist-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python3/dist-packages/django/core/management/base.py", line 361, in execute self.check() File "/usr/lib/python3/dist-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/usr/lib/python3/dist-packages/django/core/management/commands/migrate.py", line 64, in _run_checks issues = run_checks(tags=[Tags.database]) File "/usr/lib/python3/dist-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/usr/lib/python3/dist-packages/django/core/checks/database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "/usr/lib/python3/dist-packages/django/db/backends/mysql/validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "/usr/lib/python3/dist-packages/django/db/backends/mysql/validation.py", line 13, in _check_sql_mode with self.connection.cursor() as cursor: File "/usr/lib/python3/dist-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/usr/lib/python3/dist-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/usr/lib/python3/dist-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/usr/lib/python3/dist-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/usr/lib/python3/dist-packages/django/db/backends/mysql/base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "/usr/lib/python3/dist-packages/pymysql/init.py", line 94, in Connect return Connection(*args, **kwargs) File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 325, in init self.connect() File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 599, in connect self._request_authentication() File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 871, in _request_authentication auth_packet = self._process_auth(plugin_name, auth_packet) File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 902, in _process_auth return _auth.sha256_password_auth(self, auth_packet) File "/usr/lib/python3/dist-packages/pymysql/_auth.py", line 179, in sha256_password_auth data = sha2_rsa_encrypt(conn.password, conn.salt, conn.server_public_key) File "/usr/lib/python3/dist-packages/pymysql/_auth.py", line 144, in sha2_rsa_encrypt rsa_key = … -
Primary key with multiple fields in MYSQL DB wrongly recognized by Django, when connecting MYSQL table to Django
Below is the MYSQL table of Votes_list. As you can see here the primary key is {g_aadhaar_number, a_grievance_id} fields. Now while importing this table into Django as Model, below is the autogenrated code. g_aadhaar_number = models.ForeignKey(People, models.DO_NOTHING, db_column='G_Aadhaar_number') # Field name made lowercase. a_grievance = models.OneToOneField(Grievance, models.DO_NOTHING, db_column='A_Grievance_ID', primary_key=True) # Field name made lowercase. type = models.CharField(db_column='Type', max_length=10) # Field name made lowercase. class Meta: managed = False db_table = 'votes_list' unique_together = (('a_grievance', 'g_aadhaar_number'),) My doubt is even after Django correctly recoginising that the two fields together act as primary key in the line unique_together = (('a_grievance', 'g_aadhaar_number'),) , why is a_grievance expicitly mentioned as a primary key. This is causing a lot of errors. Can I know a solution? Thank you in advance :) -
set default view for date/time input field, overriding user locale?
I am rendering a datepicker within a Django Form. The answer may apply more to JS and HTML, but I'm being specific. date_field= forms.DateField( input_formats=['%Y-%m-%d'], widget=forms.DateInput( format='%Y-%m-%d', attrs={'type': 'date'} ) ) This renders my form and all, but unfortunately, the datepicker display field itself conforms to my US locale: Is it possible to preset the default display to something like 2020-11-13? -
how to override settings per test file in django?
I have two tests that when run at the same time fails: pytest -s -v blog/tests/ but when run individually it passes: pytest -s -v blog/tests/test_A.py pytest -s -v blog/tests/test_B.py I think the cause of this is both uses this pytest.fixture to override the settings: test_A.py: @pytest.fixture(autouse=True) def override_url(settings): settings.A_URL = f'https://{ip_host}:{port}' test_B.py @pytest.fixture(autouse=True) def override_url(settings): settings.B_URL = f'https://{ip_host}:{port}' Is there a way to fix this fixture to avoid the tests failing when ran at the same time? -
how can I get and edit image in Django views.py
I have a model of image with them name in Django. my model: class images(models.Model): name = models.CharField(max_length=150) image = models.ImageField() in my template I show the users a list of image name. I want when user click on the name of image, in the image detail template show hem the edited image. my model manager is: def get_by_id(self, product_id): qs = self.get_queryset().filter(id=product_id) if qs.count() == 1: return qs.first() else: return None and my views is: def image_detail(request, *args, **kwargs): img_id= kwargs['image_id'] im = images.objects.get_chart(ch_id) if MineralSpectrum is None: raise Http404 reach_image = im.image.path 'my code for edit image' context = {} return render(request, 'image_detail.html', context) but line 6 is wrong. how can I access the image to edit then render it to image_detail template? -
How to create a view for nested comments?
I want to have a nested comment system for my project. I have product model so I want to clients can comment on my products. I have my product and comment models and serializers and I related comments to products in product serializer so I can show product comments. what should i do to clients can write their comment for products??? the comments must be nested. this is my code: #models class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='comments') parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True,blank=True, related_name='replys') body = models.TextField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user} - {self.body[:30]}' class Meta: ordering = ('-created',) #serializers: class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ['id', 'user', 'product', 'parent', 'body', 'created'] class ProductSerializer(serializers.ModelSerializer): comments = CommentSerializer(many=True, read_only=True) class Meta: model = Product fields = ['id', 'category', 'name', 'slug', 'image_1', 'image_2', 'image_3', 'image_4', 'image_5', 'description', 'price', 'available', 'created', 'updated', 'comments'] lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } how should be my view?? #views: class Home(generics.ListAPIView): queryset = Product.objects.filter(available=True) serializer_class = ProductSerializer permission_classes = (permissions.AllowAny,) filter_backends = [filters.SearchFilter] search_fields = ['name', 'category__name', 'description'] class RetrieveProductView(generics.RetrieveAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = (permissions.AllowAny,) lookup_field = 'slug' -
Django help : AttributeError: module 'django.db.models' has no attribute 'DateTimeFireld'
I have no idea why I am getting the error. from django.db import models from django.utils import timezone from django.urls import reverse class Post(models.Model): title = models.CharField(verbose_name = 'TITLE', max_length = 100) content = models.TextField('CONTENT', default = "") pub_date = models.DateTimeFireld("PUBLISH DATE", default = timezone.now) mod_date = models.DateTimeField('MODIFY DATE', auto_now = True) class Meta: verbose_name = 'post' verbose_name_plural = 'posts' db_table = 'blog_posts' ordering = ('-mod_date',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args = (self.id,)) def get_pervious(self): return self.get_next_by_mod_date() def get_next(self): return self.get_next_by_mod_date() -
How to annotate a value from a related model in Django
I have a Post model: class Post(models.Model, NiceTextPrintMixin): text = models.TextField() pub_date = models.DateTimeField("date published", auto_now_add=True, db_index=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") group = models.ForeignKey(Group, on_delete=models.SET_NULL, blank=True, null=True, related_name="posts", ) image = models.ImageField(upload_to='posts/', blank=True, null=True) and a Like model: class Like(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, blank=False, null=False, related_name="likes") user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, null=False, related_name="likes") value = models.IntegerField() What i need is to annotate a field to a Post queryset that would contain a 'value' value from a Like model where the post_id=corresponding post_id and user=request.user if such a record exists is there a way to get that done in a simple annotate way ? -
how to clone a token from the Platform account to a Connect account. when using stripe prebuilt checkout page?
I am working on stripe payments, where i require having a shared customer across different connected accounts, that are connected with the platform I am using "Express Accounts" in stripe connect for connecting the connected accounts, that are linked with the platform account. On the frontend (client-side) (Angular), using the "Stripe Prebuilt checkout page", for accepting payment and I am verifying the payment in webhooks(checkout.session.completed) at backend using Django Rest Framework. I am using Destination Charges, for handling the payments and separate charges and transfers. (That i am able to achieve using stripe prebuilt checkout page by specifying payment_intent_data.application_fee_amount and payment_intent_data.transfer_data.destination) Now I have a requirement where I need to have shared customers and share customers across the connected accounts, i need to create token on connected account level and represent the customer there, a way to link the platform-level customer with the connected account without having to create it again. I tried to follow this article Clone customers across accounts but I have not had any luck, unfortunately. With Connect, you can accomplish this by following three steps: Storing customers, with a payment method, on the platform account Making tokens to clone the payment method when it’s time to … -
Multiple checkbox with same id in row and one needs to be selected
I'm trying to add a popup block which will work differently for each row. I used same checkbox id to work with CSS. But it always checks the first option. As a result, the first option in the list get deleted (as I'm working with delete button) instead of the selected one This is my HTML part : {% for item in items %} <input type="checkbox" id="popup"> <label for="popup" class="del_btn">Delete</label> <div class="popup-content"> <div class="pop-header"> <h2>Confirm deletion?</h2> <label for="popup" class="fa fa-times"></label> </div> <label for="popup" class="fa fa-exclamation"></label> <p>Once deleted, all data related to it can't be restored again.<br>Proceed to delete?</p> <div class="line"></div> <a href="{% url 'delete_item' item.id %}" class="btn btn-danger btn-sm" role="button"> <i class="fa fa-trash"></i> <span>Delete</span> </a> <label for="popup" class="close-btn">Cancel</label> </div> And my CSS part : .popup-content { top: 50%; left: 50%; opacity: 0; visibility: hidden; transform: translate(-50%, -50%); position: fixed; width: 450px; height: 350px; transition: 0.3s ease-in; background-color: khaki; border-radius: 3px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.4); } /* #popup { display: none; } */ #popup:checked ~ .popup-content { opacity: 1; visibility: visible; } .pop-header { height: 90px; background-color: #27AE60; overflow: hidden; border-radius: 3px 3px 0 0; box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2); } .pop-header … -
django-Did you forget to register or load this tag?
I am trying to create a static file to show my image in Django 3.8.3 I am using this code <!DOCTYPE html> {% load static %} <html> <head> <title>empty page</title> </head> <body> <h1>welcome to empty zone</h1> <h1> my name is {{name}} </h1> <img src="{% 'images/Django_Unchained_logo.jpg' %}" alt="no image found"> </body> </html> I already registered static in settings.py BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR=os.path.join(BASE_DIR,'templates') STATIC_DIR=os.path.join(BASE_DIR,'static') #staticfiles STATIC_URL = '/static/' STATICFILES_DIR=[ STATIC_DIR, ] -
Django Apache not loading static files
I am working on AWS LightSail, and I followed AWS's tutorial on how to deploy Django. Everything went smoothly until the end, when the static files didn't load. Here's my code: settings.py: STATIC_URL = '/static/' STATIC_ROOT = '/opt/bitnami/apps/django/django_projects/mysite/static' [project_root]/conf/httpd-app.conf: <IfDefine !IS_DJANGOSTACK_LOADED> Define IS_DJANGOSTACK_LOADED WSGIDaemonProcess wsgi-djangostack processes=2 threads=15 display-name=%{GROUP} </IfDefine> <Directory "/opt/bitnami/apps/django/django_projects/mysite/mysite"> Options +MultiViews AllowOverride All <IfVersion >= 2.3> Require all granted </IfVersion> WSGIProcessGroup wsgi-djangostack WSGIApplicationGroup %{GLOBAL} </Directory> Alias /mysite/static "/opt/bitnami/apps/django/lib/python3.7/site-packages/Django-2.2.9-py3.7.egg/django/contrib/admin/static" WSGIScriptAlias /mysite '/opt/bitnami/apps/django/django_projects/mysite/mysite/wsgi.py' The latter code is copied from AWS's tutorial, with obv the folder names adapted, so I really don't know what's going on. An I've of course ran python3 manage.py collectstatic. Any help is appreciated, thanks! -
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!