Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
nothing happens after running python manage.py shell < script.py
This is my first time trying to run a script. I'm trying to hash previously stored plain text in my db. Anyway I created script.py file in my project folder it doesn't seem to do anything what am I missing? The command I'm running in my virtual env: python manage.py shell < script.py My script.py file: from django.contrib.auth.hashers import make_password from myapp.models import User def hash_existing_passwords(): for user in User.objects.all(): user.user_password = make_password(user.user_password) user.save() -
DJANGO i want but deafult image but i cant always error [closed]
DJANGO i want but deafult image but i cant always error i but in the top {% load static %} <div class="download-img"> <div> <h3>{{books.username}}</h3> <small>{{books.created|timesince}}</small><br><br> {% if books.image.url %} <img src="{{books.image.url}}"> {% else %} <img src="{% static 'images/genericBookCover.jpg %}"> {% endif %} </div> </div> enter image description here -
Kept getting redirected to login page after keying login details correctly
can someone help me? Even though I have keyed in the correct credentials, I kept getting redirected back to the login page instead of the index page. Everything appears to be working fine, am unable to find the root cause of the problem. Help is deeply appreciated. My view code def login_view(request): if request.method == 'POST': form = LoginForm(request.POST or None) if form.is_valid(): email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(request, username=email, password=password) print('user:', user) print(password) if user is not None: login(request, user) print('1') return redirect('app:index') else: print('2') return JsonResponse({'success': False, 'message': 'Invalid email or password.'}) else: form = LoginForm() print('3') return render(request, 'login.html', {'form': form}) Terminal Output 3 1 3 -
Stripe configuration for saas application
I am creating a saas application using Django and handling payments using stripe. Here I have three types of pricing models. An admin could register any of the three plans. The admin could add multiple users to his team. Start-up: Free of cost supports up to 5 users. Have no time limit. Scale-up: supports up to 10 users. have monthly or yearly subscriptions. $1 per user per month. When the user number is 6 after the monthly period the charge will be 6*1 = $6 per month Premium: supports unlimited users. have monthly or yearly subscriptions. $2 per user per month. When the user number is 11 after the monthly period the charge will be 11*2 = $22 per month How can I configure these requirements into Stripe? I have created 3 products and created pricing for all of them, but I have no idea how can I handle the limit of the user. How can I charge the customer by the number of users in a team? -
how to link ipaddress to a name to allow connections when on the same router
So I making a small website with django, and I want my colleagues to be able to connect. We all will be using the same router, and although I can ask them to connect via the address I provide http://192.168.100.xxx on port 8000. I decided to make it easier by mapping the address to a name, so they can connect via http://my_server:8000. Although I am unsure on how to come about this. Whether to do it from the router settings, or my system settings. I've tried searching online on on how to do such, and most articles are come accross are very confusing. I would like someone to give a straightforwards approach to this. -
Can't send html template in google API
I am trying to send html template in google mail through python. I can send mail successfully but it is just text. For example when I send Hello world it will go as it is. I want to make the text bold. Here is my function for sending mail. `def send_email(subject: str, message: str, recipient: RecipientType): email = EmailMessage( subject=subject, body=message, from_email=FROM_EMAIL, to=[recipient.email], ) message = email.message() raw = base64.urlsafe_b64encode(message.as_bytes()).decode() binary_content = {'raw': raw, 'payload': {'mimeType': 'multipart/alternative'}} connection.users().messages().send(userId='me', body=binary_content).execute() ` I am using python and Google API. Thank you in advance. I tried different Mimetype but I am not so good with these things. -
AWX django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known
I have an AWX deployment using docker compose. The postgres database is having issues with dns name resolution. The issue started after I updated the docker-compose.yml to force the awx_web container to write some DNS IPs in /etc/resolv.conf. After that I ran: docker pull; docker compose up -d The containers were recreated, and I could no longer connect to the AWX web interface. I have tried stopping the containers, restarting them, reloading nginx and confirm it's running, recreating the containers with tweaked docker-compose.yml's, and I keep running into the server error issue. $ awx logs awx_web self.connect() File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known RESULT 2 OKREADY 2023-03-15 02:16:01,844 INFO exited: wsbroadcast (exit status 1; not expected) 2023-03-15 02:16:01,844 INFO exited: wsbroadcast (exit status 1; not expected) 2023-03-15 02:16:02,848 INFO spawned: 'wsbroadcast' with pid 7561 2023-03-15 02:16:02,848 INFO spawned: 'wsbroadcast' with pid 7561 2023-03-15 02:16:03,850 INFO success: wsbroadcast entered RUNNING state, process has stayed up for > than 1 seconds (startsecs) 2023-03-15 02:16:03,850 INFO … -
Django not working correctly with unit tests
Python 3.10 Django 4.0 MySQL backend in practice, but I guess during unit tests its using in memory SQLLite ModelA - primary model ModelB - ModelA contains a list of ModelB's The sequence of events happens like this: User posts to /endpoint ModelA gets inserted into DB with ModelB1, ModelB2, ModelB3 as child rows in my_method(): model_bs = list(model_a.model_bs.all()) model_bs contains b1, b2, b3 as expected. User posts to /endpoint again ModelA gets 3 new ModelB's inserted, ModelB4 - ModelB6 This is where things go haywire, but ONLY during the unit test. In my_method(), model_bs = list(model_a.model_bs.all()) model_bs STILL only contains b1, b2, b3 when it should have b1 - b6. If I look at ModelB.objects.all(), the in-memory DB has all 6 rows. Anybody seen this before? All 6 steps are happening within the context of a single unit test. If I try to do this against a real instance of MySQL, the second post does in fact get b1 - b6 as expected since it's a new actual instance of model_a (but representing the same database row). I don't really want to clear the cache or anything like that since the idea is that the parent model has already … -
Issue while trying to submit ajax form in django
Server Side Code @csrf_protect def Authenticate(request): if request.method == "POST": return JsonResponse({"success": False}) Form <form class="row" id="frmLogin"> {% csrf_token %} <input type="text" name="username" /> <input type="password" name="password" /> <button class="btn btn-primary">Submit</button> </form> JQuery $(document).ready(function() { $("form#frmLogin").validate({ rules: { "username": { "required": true }, "password": { "required": true } }, submitHandler: function(form) { $.post({ url: "/authenticate/", contentType: "application/json;charset=utf-8;", dataType: "json", data: JSON.stringify({ "username": $(form).find("[name='username']").val(), "password": $(form).find("[name='password']").val(), "csrfmiddlewaretoken": $(form).find("[name='csrfmiddlewaretoken']").val() }), async: true, success: function(response) { } }); } }); }); Error Message -
for DJANGO how can make only owner the post edit and delete
sorry for bad english im arabic and first im new here i wnat know how "DJANGO" how can make only owner the post edit and delete and THANK YOU `class Book(models.Model): username = models.ForeignKey(User , on_delete=models.CASCADE) title = models.CharField(max_length=40) descriptions = models.TextField(blank=True , null=True) image = models.ImageField(upload_to='books_pic' , blank=True , null=True , default='images/genericBookCover.jpg') bookauthor = models.CharField(max_length=18 , null=True , blank=True) downloadlink = models.URLField() created = models.DateTimeField(auto_now_add=timezone.now) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) slug = models.SlugField(null=True , blank=True)` `def book_edit(request , id): update = Book.objects.get(id=id) form = AddBookForm(instance=update) if request.method == 'POST': form = AddBookForm(request.POST or None , request.FILES or None , instance=update) if form.is_valid(): form.save() #return redirect('') context = {'form':form} return render(request , 'pages/edit_book.html' , context)` `def book_delete(request , id): delete = Book.objects.get(id=id) if request.method == 'POST': delete.delete() return redirect('/') context = {'delete':delete} return render(request , 'pages/delete_book.html' , context)` -
CSRF token seems to be getting in the way
CSRF token seems to be getting in the way I am writing django tests for my application, one of my views allows users to "like" other users posts. But the tests are failing, the issue seems to be that there is no CSRF token but I'm not sure if that's really it. POST data is not used by the view, it only uses the url data the only reason I'm saying this is because some other tests I wrote has similar problems and that solved it. But nothing I try is working here is my test: from django.test import TestCase, Client from django.utils import timezone from django.contrib.auth import get_user_model from django.contrib.auth.models import User from django.middleware.csrf import get_token from .views import update from .models import Post, Like --- some code ommited --- def test_like_view(self): # make a post p1 = Post.objects.create(title='title', body='body', published_date=timezone.now(), created_by=self.user) # get CSRF token response = self.client.get(f'/{p1.id}/update/') csrf_token = response.cookies['csrftoken'].value # send POST request with CSRF token response = self.client.post(f'/{p1.id}/like/', {'csrfmiddlewaretoken': csrf_token}) # check that the response status code is 302, indicating a redirect self.assertEqual(response.status_code, 302) # check that a Like object was created self.assertTrue(Like.objects.filter(post=p1).exists()) and here is the view: from django.shortcuts import render from django.http import … -
Issue: FOREIGN KEY constraint failed
so I'm currently writing a function to let the user write a review. Tho I'm having issues when the user goes to submit the review. It tells me that FOREIGN KEY constraint failed I know that it is a very simple issue, but I cant really see the solution The TracBack is: Traceback (most recent call last): File "/workspace/webster00/products/views.py", line 84, in submit_review review = ReviewRating.objects.get(user=request.user.userprofile, product_id=product_id) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/query.py", line 435, in get raise self.model.DoesNotExist( During handling of the above exception (ReviewRating matching query does not exist.), another exception occurred: File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception: File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/workspace/webster00/products/views.py", line 99, in submit_review data.save() File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py", line 763, in save_base updated = self._save_table( File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py", line 906, in _do_insert return manager._insert( File … -
DJANGO how can make only owner the post edit and delete
sorry for bad english im arabic and first im new here i wnat know how "DJANGO" how can make only owner the post edit and delete and THANK YOU I Try this in the tmplates for only how owner the post can he edit and delete {% if user.id == books.username.id %} <h1><a href="{% url 'books:book_delete' books.id %}">delete</a></h1> <h1><a href="{% url 'books:user_edit_book' books.id %}">update</a></h1> {% endif %} -
Sharing models between Django apps yields: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I have a Django project with multiple apps set up like: myproject/ - apps/ - app1/ - app2/ Everything works when running python manage.py runserver until I need to share models in app1 with app2. It seems this should be as simple as adding a standard import statement in the appropriate file in app2, e.g: # myproject/apps/app2/callback_funcs/sub_functions.py from apps.app1.models import SharedDataModel Unfortunately, as soon as I add the import statement, I get the error django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I tried solutions given here, here, and here, yet the problem persists. All apps are in my INSTALLED_APPS list and being read correctly (again, as long as I exclude the problematic import statement above). I thought the order of the apps in the INSTALLED_APPS list might be an issue (I've seen instructions elsewhere that state certain apps need to be first) but this doesn't seem to affect the results. I have: INSTALLED_APPS = [ ... 'apps.app1', 'apps.app2.app', ... ] app1 is a standard Django app, app2 is a Django Plotly Dash app and has an app file which contains: # myproject/apps/app2/app.py from django_plotly_dash import DjangoDash from .layout import layout from .callbacks import register_callbacks app = DjangoDash("app2") app.layout = layout register_callbacks(app) Interestingly, … -
How to set encoding on a postgres connection using a dj-database URL?
dj-database-url allows setting a postgres URL on a connection. For example: # python DATABASES = { 'default': dj_database_url.config() } # environment variable export DATABASE_URL=postgres://user:pw@localhost:port/dbname However, I inexplicably find that the DB connection has a SQL_ASCII encoding instead of UTF8 like I want. Here is one workaround for psycopg2, explicitly setting the client encoding on the connection. How do I do that with an implicit connection defined by DATABASE_URL? -
I want to implement calculation
Models: class TrainingProgram(TimeStampModel): name = models.CharField(max_length=100, verbose_name="Name", unique=True) slug = AutoSlugField(populate_from="name", unique=True, verbose_name="Slug") class Meta: verbose_name = "Training Program" verbose_name_plural = "Training Programs" db_table = "training_programs" class Course(TimeStampModel): name = models.CharField(max_length=100, verbose_name="Name", unique=True) slug = AutoSlugField(populate_from="name", unique=True, verbose_name="Slug") training_program = models.ForeignKey("training.TrainingProgram", on_delete=models.CASCADE, related_name='courses') class Meta: verbose_name = "Course" verbose_name_plural = "Courses" db_table = "courses" class CourseOutline(TimeStampModel): course = models.ForeignKey("training.Course", on_delete=models.CASCADE, related_name='outlines') name = models.CharField(max_length=100, verbose_name="Name", unique=True) is_active = models.BooleanField(default=True, verbose_name="Active") class Meta: verbose_name = "Course Outline" verbose_name_plural = "Course Outlines" db_table = "course_outlines" class EmployeeTrainingProgram(TimeStampModel): user_profile = models.ForeignKey("users.UserProfile", on_delete=models.CASCADE) training_program = models.ForeignKey("training.TrainingProgram", on_delete=models.CASCADE) is_completed = models.BooleanField(default=False, verbose_name="Completed") start_date = models.DateField(verbose_name="Start Date", ) completion = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="Completion", default=Decimal(0.00)) class Meta: verbose_name = "Employee Training Program" verbose_name_plural = "Employee Training Programs" db_table = "employee_training_programs" class EmployeeCourse(TimeStampModel): user_profile = models.ForeignKey("users.UserProfile", on_delete=models.CASCADE) course = models.ForeignKey("training.Course", on_delete=models.CASCADE) is_completed = models.BooleanField(default=False, verbose_name="Completed") completion = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="Completion", default=Decimal(0.00)) class Meta: verbose_name = "Employee Course" verbose_name_plural = "Employee Courses" db_table = "employee_courses" class EmployeeCourseOutline(TimeStampModel): user_profile = models.ForeignKey("users.UserProfile", on_delete=models.CASCADE) course_outline = models.ForeignKey("training.CourseOutline", on_delete=models.CASCADE) is_completed = models.BooleanField(default=False, verbose_name="Completed") class Meta: verbose_name = "Employee Course Outline" verbose_name_plural = "Employee Course Outlines" db_table = "employee_course_outlines" Serializer: class OutLineSerializer(serializers.ModelSerializer): course_display = serializers.CharField(source="course.name", read_only=True) class Meta: model = CourseOutline fields = '__all__' … -
Wait before fetching django objects if database transaction is ongoing
I have a python script which uses pandas to read an SQL Server table and then transfer it to a PostgreSQL database as it is. This happens every 10 minutes with a linux cron job. Whenever pd.to_sql is called it takes 1 minute for the table to be written to postgres. In Django i have an unmanaged model for this table and my problem is that if i use MyModel.objects.all() during the 1 minute that the pd.to_sql takes to run, I get no objects back. That's because in pd.to_sql I'm using if_exists='replace'. Although this is expected behavior, is there any way to "wait" somehow while executing MyModel.objects.all() while there's an insert going on in the database ? How should i approach this problem ? I have read about isolation level but I dont know if i should mess with that and if it will fix my problem. I also read about django's transaction.on_commit() but it's not for my case -
user with this email address already exists in postman but admin panel creates it
I have a custom user and profile model correlated. When I want to create new profile via Postman for this user I get user with this email address already exists //im using this json on Postman { "user":{ "email": "admin@gmail.com" }, "gender": "1", "bio": "test", "playlist": "qwerts", "gym": { "id": "74038574-51fa-4945-89b2-666c2888ebbb", "name": "testname", "date": "2023-03-12T14:21:54.835946Z", "place": "a897f045-da6d-4d7c-a706-9878b77128de" } } But when I'm in the admin panel I can easily create one I wanted to check what will happen when I pass an email that does not exist as a user The `.create()` method does not support writable nested fields by default. Write an explicit `.create()` method for serializer `user_mgmt.serializers.ProfileSerializer`, or set `read_only=True` on nested serializer fields. I suppose that those errors are not correlated but im posting it anyways just for diligence and probably i have errors in the same functions views.py class ProfileViewSet(viewsets.ModelViewSet): serializer_class = ProfileSerializer def get_queryset(self): return Event.objects.all() def create(self, request): serializer = ProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() data = serializer.data return Response(data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User exclude = ('password', 'is_superuser', 'is_staff', 'groups', 'user_permissions') class ProfileSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Profile fields = '__all__' depth = … -
Accessing POST data in a django CreateView
I am trying to use PurchaseCreateView to create a Purchase instance and then go on to update the Ingredients model The following code is throwing a MultiValueDictKey error. I CANNOT work out how to fix this. Can anyone help? Here are my Models: class Ingredient(models.Model): name = models.CharField(max_length=30) quantity = models.FloatField() price = models.FloatField() def __str__(self): return self.name def get_absolute_url(self): return "inventory" class MenuItem(models.Model): name = models.CharField(max_length=50) price = models.FloatField() def available(self): return all(x.enough() for x in self.reciperequirements_set.all()) def __str__(self): return self.name class RecipeRequirements(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) quantity = models.FloatField(default=0) def enough(self): return self.quantity <= self.ingredient.quantity def __str__(self): return f"{self.menu_item} requires {self.ingredient}" class Purchase(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.menu_item} purchased at {self.timestamp}"` My Views: ''' class PurchaseCreateView(CreateView): template_name = "inventory/purchase_form.html" model = Purchase fields = "all" success_url = reverse_lazy("home") def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["menu_items"] = [x for x in MenuItem.objects.all() if x.available()] return context def post(self, request): menu_item_id = request.POST["menuitem"] menu_item = MenuItem.objects.get(pk=menu_item_id) purchase = Purchase(menu_item=menu_item) purchase.save() ''' and the template: ''' {% extends 'base.html' %} {% block head %} <title>New purchase</title> {% endblock %} {% block content %} <h2>Add a new purchase</h2> <form method="POST"> {% csrf_token … -
django-simple-history doesn't create any historical data
In my application, I have a model DataSeriesModel and my migration file for this model looks like this: migrations.CreateModel( name='DataSeriesModel', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('id', model_utils.fields.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('name', models.CharField(max_length=255)), ... After adding history = HistoricalRecords() field to the model and running makemigrations I'm getting another migrations file with the content as follows: operations = [ migrations.CreateModel( name='HistoricalDataSeriesModel', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('id', model_utils.fields.UUIDField(db_index=True, default=uuid.uuid4, editable=False, primary_key=True)), ('name', models.CharField(max_length=255)), ... ('history_id', models.AutoField(primary_key=True, serialize=False)), ('history_date', models.DateTimeField(db_index=True)), ('history_change_reason', models.CharField(max_length=100, null=True)), ('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)), ('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)), ], Thera are two primary keys in this migration file and of course after migrate command we're getting: django.db.utils.ProgrammingError: multiple primary keys for table "data_series_models_historicaldataseriesmodel" are not allowed LINE 1: ...cription" text NULL, "history_id" serial NOT NULL PRIMARY KE... When I tried to manually set history_id to for example models.IntegerField() the migrate command worked without errors, but I didn't get any historical records in the database. What could be wrong? What can I try/change to get any historical records? -
Object of type '__proxy__' is not JSON serializable
When I want to import variants in a CSV file format then this error occurred. Here is the code: @api_view(["POST"]) @permission_classes((permissions.IsAuthenticated,)) def CSVBulkUpdate(request, model, pk=None): user = User.objects.get(id=request.user.id) mapped_obj_to_import = [] data = request.data["data"] mapped_obj = request.data["mapped_obj"] print(data) for row in data: row_obj = {} if row.get("id") or row.get("name"): for key, item in mapped_obj.items(): if item and row.get(key) != "": row_obj[item] = covertObjects(item, row.get(key)) mapped_obj_to_import.append(row_obj) try: if model == "product": csvBulkUpdate(user.id, mapped_obj_to_import) else: csvVariantBulkUpdate(user.id, mapped_obj_to_import) except Exception as e: print("Error: ", str(e)) return Response({"data": str(e)}, status=400) return Response({"data": "success"}, status=200) The csvVariantBulkUpdatefunction code: def csvVariantBulkUpdate(user, dataToUpdate): serializer_class = serializers.VariantImportUpdateSerializer model = models.Variant serializer_unapproved_class = serializers.UnapprovedVariantImportSerializer module = "variant" view = "Variant" list_data = dataToUpdate user = User.objects.get(id=user) print(user) variants = [] relational_fields = ["size", "color"] results = {"success": {}, "failure": {}} for i, item in enumerate(list_data): results["failure"][item["id"]] = {} try: record = model.objects.get(id=item["id"]) item["product"] = record.product.id if user.is_admin: print("variant update admin view triggered") update_size_in_approved = False update_color_in_approved = False if "size" in item: error, data = sizesValidate(item["size"]) if error: results["failure"][item["id"]]["size"] = data item["size"] = data update_size_in_approved = True if "color" in item: error, data = colorValidate(item["color"]) if error: results["failure"][item["id"]]["color"] = data item["color"] = data update_color_in_approved = True if len(results["failure"][item["id"]]) == … -
How to inherit from a model to use its fields but be an independant table in Django?
I have a CompanyRanking model: class CompanyRanking(): """Company ranking model. Rankin hold a top based on minutes usage for user. """ company = models.ForeignKey( 'companies.company', on_delete=models.CASCADE, null=True, related_name='ranking' ) user = models.ForeignKey( 'users.user', on_delete=models.CASCADE, null=True, related_name='ranking_position' ) extra_data = models.JSONField( null=True, blank=True ) I need to create another model with the same information as CompanyRanking but with an extra relation to another table (CompanyBatchByDate) in which I get the dates to filter the users's points and show other ranking. I am trying to inherit from CompanyRanking as shown: class CompanyRankingByBatch(CompanyRanking): """ Company ranking model based on batch. """ batch = models.ForeignKey( 'companies.CompanyBatchByDate', on_delete=models.SET_NULL, null=True, related_name='ranking_by_batch', ) class CompanyBatchByDate(): """ Company ranking model based on batch. """ company = models.ForeignKey( 'companies.company', on_delete=models.CASCADE, null=True, related_name='batch_by_date' ) initial_date = models.DateField( null=True, blank=True, help_text='Date when the batch start' ) finish_date = models.DateField( null=True, blank=True, help_text='Date when the batch finish' ) is_active = models.BooleanField( default=True, help_text='Batch that will be used to calculate the ranking' ) name = models.CharField( max_length=255, null=True, blank=True, help_text='Name of the batch' ) Problem is, I want to be able to have a differente related_name of the relationship of user - companyrankingbybatch and want to update this model fields independently from CompanyRanking. … -
Django List Admin Is Very Slow When Setting is_editable to use a Django Money Field
I'm utilizing the django-money package in my model like so. class MyModel(models.Model): price_low = MoneyField( max_digits=10, default=0, decimal_places=2, null=True, blank=True, default_currency="USD", ) price_medium = MoneyField( max_digits=10, default=0, decimal_places=2, null=True, blank=True, default_currency="USD", ) price_high = MoneyField( max_digits=10, default=0, decimal_places=2, null=True, blank=True, default_currency="USD", ) And then loading the models in an Admin List with these fields set as editable like so. class IssueAdmin(admin.ModelAdmin): list_editable = ( "price_low", "price_medium", "price_high" ) list_per_page = 20 With this setup and 400k records in the database it takes approx. 6 seconds to load the page. I'm limiting the results returned to 20 just to get this page to return in somewhat of a respectable time frame. If I remove the money fields from list_editable and put different fields that are basic inputs or even autocompletes the page loads in approx 1.5 seconds. How can I improve the performance of this? -
update_or_create with django JSONField
I use Django JSONField to save custom objects (that are callable) and i am confused by update_or_create. My custom objects could be realized by nesting enough dictionarys but that is a pain to work with. Thats why i want to use custom objects. I didn't want to use a Django Model for that object, as i worry about the amount of database requests. My Minimum example:models.py from django.db import models import json # Create your models here. class F: def __init__(self, val) -> None: self.val = val def __call__(self): return "call_return_string" def to_serializable(self) -> dict: return {"class": "F", "val": self.val} @classmethod def from_serialized(classtype, dic): assert "class" in dic.keys() assert dic["class"] == "F" return F(dic["val"]) class FEncoder(json.JSONEncoder): def default(self, f: F) -> dict: return f.to_serializable() class FDecoder(json.JSONDecoder): def F_obj_hook(self,dic:dict): if "class" in dic.keys(): if dic["class"] == "F": return F.from_serialized(dic) return dic def __init__(self,*args,**kwargs): super().__init__(object_hook=self.F_obj_hook,*args,**kwargs) class Tester(models.Model): id = models.BigAutoField(primary_key=True) data= models.JSONField(default=dict,encoder=FEncoder,decoder=FDecoder) Let f = F("1"). Now when i run any of these: #Tester.objects.create(data=f) #works as expected #Tester.objects.filter(id=1).update(data=f)#works as expected #Tester.objects.get(data=f)#works as expected #Tester.objects.update_or_create(data=f,defaults={"data":f}) #not as expected The first will create a database entry where the data column is filled with {"class": "F", "val": "1"}. The second would update an existing entry, … -
why Django form show UnicodeEncodeError in Persian language?
I have simple form as below: forms.py: from django import forms class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) views.py: from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import NameForm def get_name(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): print(form.cleaned_data) return HttpResponseRedirect('/') else: form = NameForm() return render(request, 'form.html', {'form': form}) form.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> </body> </html> If I write English character and submit form, it works ok and execute print statement but if I write Persian character like'متن تست' it shows this error: UnicodeEncodeError at / 'charmap' codec can't encode characters in position 132-136: character maps to <undefined> Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 4.1.7 Exception Type: UnicodeEncodeError Exception Value: 'charmap' codec can't encode characters in position 132-136: character maps to <undefined> Exception Location: C:\Program Files\Python311\Lib\encodings\cp1252.py, line 19, in encode Raised during: myapp.views.get_name Python Executable: C:\python\test1\venv\Scripts\python.exe Python Version: 3.11.2 Python Path: ['C:\\python\\test1', 'C:\\python\\test1', 'C:\\Program Files\\JetBrains\\PyCharm ' '2022.3.2\\plugins\\python\\helpers\\pycharm_display', 'C:\\Program Files\\Python311\\python311.zip', 'C:\\Program Files\\Python311\\DLLs', 'C:\\Program Files\\Python311\\Lib', 'C:\\Program Files\\Python311', 'C:\\python\\test1\\venv', 'C:\\python\\test1\\venv\\Lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2022.3.2\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] Server time: Tue, 14 Mar 2023 19:06:06 +0000 The string that could not …