Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have completed the registration process in Django user login, but I want the login process to check and match the tokens. How can I do this
I created a user login with Django. I used tokens during the registration process, and I want the user to be redirected to the homepage if the tokens match when they enter their password during login. I want to implement user login with tokens in my Django project -
How to edit field how an embedded model in django
I have following models : ModelA --> with fields flda1, flda2, fld3 and id ModelB --> with fields fldb1, fldb2, id and a_obj = foreign-key-to-ModelA Now I have to write view to update flda1 and flda2 of ModelA and fldb1 of ModelB resources having foreign-key-to-same(ModelA) [some (not all) -- i.e., not all b_objs need to be modified ] The update data must be sent as follows : data = { 'flda1' : 'PRADEEP 2 title CHANGED', 'flda2' : 'medium CHANGED again...', "b_objs" : [ {'fldb1':'TB', 'modela':99, 'id':184}, {'fldb1':'STF', 'modela':99, 'id':185} ] } And the query parameter contains id for ModelA The problem is that the view and the serializer are working properly for flda1 and flda2. But when I add b_objs, I get errors. Here is my view : class ViewA(RetrieveUpdateDestroyAPIView): queryset = ModelA.objects.all().prefetch_related('b_objs') serializer_class = ModelASerializer def update(self, request, *args, **kwargs): modela_id = = request.query_params['id'] modela_ins = queryset.filter(pk=modela_id).first() serializer = self.get_serializer(project, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() And serializers are : class ModelBSerializer(serializers.ModelSerializer): class Meta : model = ModelB fields = '__all__' class ModelASerializer(serializers.ModelSerializer): obj_bs = ModelBSerializer(many=True) def validate(self, data) : # validation code return data def update(self, instance, validated_data): print(validated_data) for field, value in validated_data.items(): setattr(instance, field, value) instance.save() # … -
AWS Beanstalk - FileNotFoundError: [Errno 2] No such file or directory: '/var/app/staging/'
I am using Elastic Beanstalk without container, just the EC2 instance. Sometimes it fails without any reason when it create a new instance. I found some weird logs May 20 20:32:48 ip-172-31-14-242 audit[10978]: AVC avc: denied { open } for pid=10978 comm="nginx" path="/var/log/nginx/error.log" dev="nvme0n1p1" ino=3682049 scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:cloud_log_t:s0 tclass=file permissive=1 [2024-05-20T20:21:47.035Z] Sending signal 0 to CFN wait condition https://cloudformation-waitcondition-us-east-1.s3.amazonaws.com/arn%3Aaws%3Acloudformation%3Aus-east-1%3A576017513047%3Astack/awseb-e-xcvkczyzt5-stack/3804c910-892f-11ee-abd9-0a6f02a2186d/AWSEBInstanceLaunchWaitHandle?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20231122T120405Z&X-Amz-SignedHeaders=host&X-Amz-Expires=86399&X-Amz-Credential=AKIA6L7Q4OWT3JRXU3BZ%2F20231122%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=abf31ed864bec2be68aa61889b6b2a836c610de7ba3bed93dce80c1ee7589faa Error signaling CloudFormation: [Errno 403] HTTP Error 403 : <?xml version="1.0" encoding="UTF-8"?> <Error><Code>AccessDenied</Code><Message>Request has expired</Message><X-Amz-Expires>86399</X-Amz-Expires><Expires>2023-11-23T12:04:04Z</Expires><ServerTime>2024-05-20T20:21:47Z</ServerTime><RequestId>9SRZ3MVWKVAR7FJ2</RequestId><HostId>B16Ow5bF0aibCFU52u+lnnMOBI6Rijz9KV/Y+UGKWkgHz4E+QtXAbYDp48ZnLK5wAsOHgblLZOk=</HostId></Error> 2024-05-20 19:44:47,211 [ERROR] -----------------------BUILD FAILED!------------------------ 2024-05-20 19:44:47,212 [ERROR] Unhandled exception during build: [Errno 2] No such file or directory: '/var/app/staging/' Traceback (most recent call last): File "/opt/aws/bin/cfn-init", line 181, in <module> worklog.build(metadata, configSets, strict_mode) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 137, in build Contractor(metadata, strict_mode).build(configSets, self) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 567, in build self.run_config(config, worklog) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 579, in run_config CloudFormationCarpenter(config, self._auth_config, self.strict_mode).build(worklog) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 277, in build changes['commands'] = CommandTool().apply( File "/usr/lib/python3.9/site-packages/cfnbootstrap/command_tool.py", line 116, in apply commandResult = LoggingProcessHelper( File "/usr/lib/python3.9/site-packages/cfnbootstrap/util.py", line 619, in call results = self.process_helper.call() File "/usr/lib/python3.9/site-packages/cfnbootstrap/util.py", line 591, in call process = subprocess.Popen( File "/usr/lib64/python3.9/subprocess.py", line 951, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/usr/lib64/python3.9/subprocess.py", line 1821, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: '/var/app/staging/' I know … -
Use a DB backend function on the result of an aggreate in Django
Is it possible to have a DB function executed on the result of an aggregate? In my case, I have this aggregate: geom = SomeModel.objects.filter(otherModel=xxx).aggregate(geom=Union("geom")) Let's say I would like to run another DB function on the output of the aggregate (like Reverse for instance. How can I achieve this? -
Cookie does not get set
I have a Django REST API that sends with session authentication. And the problem is the csrftoken cookie that I get in request does not get set. Here's a part of my SETTINGS.py file # CORS and CSRF CORS_ALLOWED_ORIGINS = [ 'https://123.client' ] CORS_ALLOW_CREDENTIALS = True CORS_EXPOSE_HEADERS = [ 'Set-Cookie' ] CSRF_TRUSTED_ORIGINS = [ 'https://123.client' ] CSRF_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = False SESSION_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SECURE = True Here are the response headers: HTTP/1.1 202 Accepted Date: Tue, 21 May 2024 12:31:31 GMT Content-Length: 0 Connection: keep-alive Vary: Accept, Cookie, origin Allow: POST, OPTIONS X-Frame-Options: DENY X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin access-control-allow-origin: https://123.client access-control-allow-credentials: true access-control-expose-headers: Set-Cookie Set-Cookie: csrftoken=...; expires=Tue, 20 May 2025 12:31:31 GMT; Max-Age=31449600; Path=/; SameSite=None; Secure sessionid=...; expires=Tue, 04 Jun 2024 12:31:31 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=None; Secure Server: ... And when I try to read the csrftoken cookie to set the X-CSRFToken header, I can't get it and it's not showing neither in browser nor when I try to access it in https://123.client through document.cookie. On what side is the problem here? Am I just not reading the cookie correctly or is there something needs to be done server-side? -
Can't get two elements to update while using Django and HTMX
I'm trying to create a car pool where I use HTMX in my Django project to make it work. The CarPool model consist of two FK. One FK is "City", and the other is "Car". I have it somewhat working. So within my two tables (one table with all the cars that have no city attached, and the other table displaying all the cars attached to the city that has been clicked), I'm able to use hx-post to add the car, and same to remove the car with the clicked city. But I don't get the lists to update after they are clicked. I have tried different ways of using hx-oob-swap but since I'm fairly new with both Django and HTMX I'm not sure where to exactly use it. See attached pictures. So picture "notclicked", the left table shows all cars with no city, and the right table displays cars with "Chicago" as a FK. notclicked Picture "clicked" I have now clicked on the car MMW 331 from the left table, and it adds it to the right table which is good, but then when I click on it, I want it also to be removed from the left table … -
Stripe promocode: how to verify that user have redeemed the promocode before or not
I have a Django project configured with Stripe for payments. I have created promocodes for discounts, which can only be redeemed once per customer. The problem is that I want to validate whether a given customer has already redeemed a specific promocode. If they haven't redeemed it, I want to proceed to the next step; otherwise, I want to stop the customer at that point. I have retrieve the promocode but it returns the following values: { "active": true, "code": "test10", "coupon": { "amount_off": null, "created": 1716289929, "currency": "usd", "duration": "once", "duration_in_months": null, "id": "test10", "livemode": false, "max_redemptions": null, "metadata": {}, "name": null, "object": "coupon", "percent_off": 10.0, "redeem_by": null, "times_redeemed": 1, "valid": true }, "created": 1716289930, "customer": null, "expires_at": 1716595200, "id": "promo_1PIqc2B67hjAZnF4umv6pZCP", "livemode": false, "max_redemptions": null, "metadata": {}, "object": "promotion_code", "restrictions": { "first_time_transaction": true, "minimum_amount": null, "minimum_amount_currency": null }, "times_redeemed": 1 } I am not able to find an API that validates whether a customer has already redeemed a given promocode. I'm expecting a method or API endpoint in Stripe that allows me to check if a specific customer (customer ID) has redeemed a specific promocode. I have created The promocode which is only be redeemed once per customer. -
"This field may not be blank." Django DRF
I am new to DRF, I am working on the the registraion API My MOdel from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self, email, user_type, password=None, **extra_fields): email = self.normalize_email(email) user = self.model(email=email, user_type=user_type, **extra_fields) user.set_password(password) user.save(using=self._db) return user class CustomUser(AbstractBaseUser): USER_TYPE_CHOICES = ( ('seller', 'Seller'), ('user', 'User'), ) username = models.CharField(unique=True, max_length=20, null=True, blank=True,) email = models.EmailField(unique=True, blank=True,) first_name = models.CharField(max_length=256 , blank=True,) last_name = models.CharField(max_length=256, blank=True,) user_type = models.CharField(max_length=10, choices=USER_TYPE_CHOICES , blank=True,) email_otp = models.CharField(max_length=10, blank=True,) phone_otp = models.CharField(max_length=10, blank=True,) email_verified = models.BooleanField(default=False, blank=True,) create_at = models.DateTimeField(auto_now_add=True, blank=True,) update_at = models.DateTimeField(auto_now=True, blank=True,) is_active = models.BooleanField(default=True, blank=True,) is_staff = models.BooleanField(default=False, blank=True,) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_type'] class SellerProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) address_1 = models.CharField(max_length=255, blank=True,) address_2 = models.CharField(max_length=255, default="Null", blank=True,) address_3 = models.CharField(max_length=255, default="Null", blank=True,) state = models.CharField(max_length=100, blank=True,) phone_number = models.CharField(max_length=15, blank=True,) zip_code = models.CharField(max_length=10, blank=True,) class UserProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE , blank=True,) profile_pic = models.ImageField(upload_to='profile_pics', blank=True, null=True) bio = models.TextField(blank=True,) dob = models.DateField(blank=True,) phone_number = models.CharField(max_length=15, blank=True,) My serializer class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('profile_pic', 'bio', 'dob', 'phone_number') class SellerProfileSerializer(serializers.ModelSerializer): class Meta: model = SellerProfile fields = ('address_1', 'address_2', 'address_3', 'state', 'phone_number', … -
upgrade from 4.2.6 to 5.0.6 destroyed my forms
I am using an ImageForm to upload images to my database and I store them in base64 (user's icons, only some pixels). But the update destroyed the functionality: class CustomImageFile(AdminFileWidget): def render(self, name, value, attrs=None, renderer=None): output = [super().render(name, value)] try: output.append(self.form_instance.instance.show_picture()) except: pass return "".join([x for x in output]) class PersonAdminForm(forms.ModelForm): image_file = forms.ImageField(widget=CustomImageFile, required=False, label="picture") def __init__(self, *args, **kwargs): """ to add self.form_instance to widget """ super().__init__(*args, **kwargs) self.fields["image_file"].widget.form_instance = self class Meta: model = Person fields = ["name", ..., "image_file"] @admin.register(Person) class PersonAdmin(admin.ModelAdmin): list_display = ["get_name", "get_picture"] @admin.display(description="...") def get_picture(self, obj): try: return obj.show_picture except: return "... " class Person(models.Model): name = models.CharField("name", max_length=128, blank=True, null=True) picture = models.TextField("asb64", blank=True) @property def show_picture(self): try: return format_html(f"""<img src="{self.picture}">""") except: return "" I tested this with Django 4.2.6 & 4.2.13 which yields: After an upgrade to 5.0.6: Where there changes to ImageField? I have not yet found something in the patchnotes I could use, but would be glad for a solution. -
how to get distinct record based on specific fields in django orm?
def get_queryset(self): # current_date = datetime(2024, 9, 2, 12, 56, 54, 324893).today() current_date = datetime.today() # get the booking data from the current date --------- requested_datetime is when the patient has scheduled the booking for booking_data = PatientBooking.objects.annotate( admission_datetime=F('requested_admission_datetime'), delivery_datetime=F('estimated_due_date'), fully_dilation_datetime=ExpressionWrapper( F('estimated_due_date') - timedelta(days=(1)), output_field=DateTimeField() ), source=Value('booking', output_field=CharField()) ).filter(status="ACCEPTED", admission_datetime__date=current_date ) # get the patient data from the current date ---- based on when the patient record is created_at patient_data = PatientDetails.objects.annotate( admission_datetime=F('created_at'), delivery_datetime=F('estimated_due_date'), fully_dilation_datetime=F('patient_fully_dilated'), source=Value('patient', output_field=CharField()) ).filter(status="ACTIVE", admission_datetime__date=current_date ) # combine the record in one queryset using union on the required fields only combined_queryset = booking_data.values('first_name', 'last_name', 'delivery_type', 'date_of_birth', 'admission_datetime', 'delivery_datetime', 'fully_dilation_datetime', 'source' ).union( patient_data.values('first_name', 'last_name', 'delivery_type', 'date_of_birth', 'admission_datetime', 'delivery_datetime', 'fully_dilation_datetime', 'source' ) ).order_by('first_name', 'last_name', 'date_of_birth') # if records in both the model matches---- then consider it as same patient and consider the record where the source=patient combined_queryset = combined_queryset.distinct( 'first_name', 'last_name', 'date_of_birth' ) return combined_queryset This is my queryset. I have two models PatientDetails and PatientBooking both models have different numbers of fields and names I want to get a single queryset with specific fields from both tables. So I first annotate the field name and then perform union to it. To get a single queryset with field … -
How to start Celery Beat and Worker in production environment(cpanel)
please I developed a django app that automatically generates invoice and sends an email to client at certain hours. This app works perfectly in the development environment but not in production. I need help on how to work with redis and celery beat in production(cpanel) When I tried starting celery beat on cpanel, i was getting an error regarding Redis -
retrieve query params in django
I created a redirect endpoint on my django app. I normally am able to get query params from the url path but when this redirect happens, it appends the value # to the url. this stops me from being able to get the query params. how do i retrieve access_token as a query params from this url? /redirect/#access_token=ya29.a0AXooCgvXSv2-9x-4i6V I tried using request.GET.get('access_token') but it did not work. I also printed request.META but access_token is not in it -
Use IntegerChoices instead of Model for rest framework
I have field like this, models.py from django.db import models as m class Faculty(m.IntegerChoices): Arts = 1, 'Arts', Scienece = 2, 'Sceience' Other = 3 ,'Other' and it is used as reference in other models. Howeber, now I want to get the list by API rest framework. For example if it is not IntegerChoices but Model I can use the rest framework with view and serializer class MyModelViewSet(viewsets.ModelViewSet): queryset = sm.Faculty.objects.all() serializer_class = s.FormSelectorSerializer class MyModleSerializer(ModelSerializer): detail = serializers.JSONField() class Meta: model = sm.MyModel fields = ('id') I can use the rest framework like this , However for IntegerChoices, How can I do the equivalent to this thing? Or is it possible? -
Django extra actions need to add additional parameter but not working
I have a extra action in Django. I need to provide additional query param to it, shown below: class MyViewSet: .... ... @action(detail=True, method=["get"], url_path=r"abc/(?P<name>[A-Za-z\.]+)") def abc_op(self, request, pk, name): .... The above is not working when I call the API like: http://localhost:8000/employee/1/abc/xy.z, but if I append / at the end I get the result: http://localhost:8000/employee/1/abc/xy.z/ with request http://localhost:8000/employee/1/abc/xy.z I get: { "detail": "Not found." } But when I make request http://localhost:8000/employee/1/abc/xy.z/ (appending / at the end) I get: { "result": True, "data": [] } Please let me help understand what is wrong here. This should work without appending any / at the end. -
DatabaseError at /admin/shop/item/add/
here pic of error another pic debug log DatabaseError at /admin/shop/item/add/ No exception message supplied Request Method:POSTRequest URL:http://127.0.0.1:8000/admin/shop/item/add/Django Version:4.1.13Exception Type:DatabaseErrorException Location:C:\Users\MSI\Desktop\A Project_Django_thanhduc\my_venv\Lib\site-packages\djongo\cursor.py, line 81, in fetchoneRaised during:django.contrib.admin.options.add_viewPython Executable:C:\Users\MSI\Desktop\A Project_Django_thanhduc\my_venv\Scripts\python.exePython Version:3.11.9Python Path:['C:\\Users\\MSI\\Desktop\\A Project_Django_thanhduc\\my_app', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\\python311.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\\Lib', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0', 'C:\\Users\\MSI\\Desktop\\A Project_Django_thanhduc\\my_venv', 'C:\\Users\\MSI\\Desktop\\A ' 'Project_Django_thanhduc\\my_venv\\Lib\\site-packages']Server time:Tue, 21 May 2024 08:33:44 +0000 This is my setting.py database DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'onlineshop', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'localhost', 'port': 27017, 'authSource': 'admin', # Đảm bảo rằng authSource là đúng }, 'LOGGING': { 'version': 1, 'loggers': { 'djongo': { 'level': 'DEBUG', 'propagate': False, } }, }, } } Model.py : from django.db import models from django.contrib.auth.models import User class Topic(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Item(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=100) price = models.DecimalField(max_digits=20, decimal_places=2) image = models.ImageField(upload_to='items/', null=True, blank=True) description = models.TextField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return f"{self.name} - {self.host.username if self.host else 'No Host'}" I'm start a project with django and mongodb(with djongo eninge). When I create user in my template(html) i can create item, update, delete, even with superuser. But when I go to adminstrations(with … -
Reverse for 'listing_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['listings/listings/(?P<pk>[0-9]+)/\\Z']
I'm new to django and I'm creating a listing site, similar to Gumtree. When I try to retrieve the logged-in user's listings from the database and display on their MyListings page, I get the above error. My code is below. Any help would be appreciated! Also, I have checked, each listing has a pk value. urls.py from django.urls import path from listings import views urlpatterns = [ path('my_listings/', views.my_listings, name='my_listings'), path('create/', views.create_listing, name='create_listing'), path('listings/<int:pk>/', views.listing_detail, name='listing_detail'), path('listings/<int:pk>/update/', views.update_listing, name='update_listing'), path('listings/<int:pk>/delete/', views.delete_listing, name='delete_listing'), ] views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .models import Listing from users.models import Profile from .forms import ListingForm from django.contrib import messages from django.contrib.auth import get_user_model from django.db import IntegrityError from django.core.exceptions import ObjectDoesNotExist User = get_user_model() @login_required def my_listings(request): print("my_listings view called") context = {} #initialise the context dictionary if request.user.is_authenticated: try: # Get logged-in user logged_in_user=request.user # Get user profile profile=get_object_or_404(Profile, email=logged_in_user.email) print(f"Profile for user {request.user}: {profile}") listings = Listing.objects.filter(profile=profile) print(f"Listings for profile {profile}: {listings}") for listing in listings: print(f"Listing PK: {listing.pk}") except ObjectDoesNotExist: print(f"Profile does not exist for user {request.user}") # If the profile doesn't exist, handle the error profile = None listings = Listing.objects.none() context['listings'] = listings print("Context … -
How can I prevent the user to add a public holiday who has the same date with other public holiday in django?
I am new to django. My model is this: class PublicHoliday(models.Model): name = models.CharField(_('Holiday Name'), max_length=100, unique=True) date_time = models.DateField(_('Holiday Date')) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.name @receiver(pre_save, sender=PublicHoliday) def save_current_year(sender, instance, **kwargs): new_intance_date_time = instance.date_time.replace(year=timezone.now( ).year, month=instance.date_time.month, day=instance.date_time.day) instance.date_time = new_intance_date_time And the serializer is this: class PublicHolidayCreateSerializer(serializers.ModelSerializer): class Meta: model = PublicHoliday fields = '__all__' def create(self, validated_data): if PublicHoliday.objects.filter(date_time=validated_data['date_time']).exists(): raise serializers.ValidationError("This public day already exists") return super().create(validated_data) def update(self, instance, validated_data): if 'date_time' in validated_data and PublicHoliday.objects.filter(date_time=validated_data['date_time']).exclude(pk=instance.pk).exists(): raise serializers.ValidationError("This public day already exists") return super().update(instance, validated_data) But when I create or update a public holiday who has the same dates as other public holidays doesn't work. How can I solve this -
Django Links & Buttons Click Issue: All clicks open in a new window
Since a number of commits, All clicks on buttons, links, submit buttons... open in a new window. Submitting forms does not work anymore, which means I can't test the last changes I've made, and the navigation is obviously broken. What's happening: Clicking on any button or link opens a new window/tab, as the target="_blank" attribute would have the links behave What's expected: Action after clicking on any button or link should instead stay on the same page, as the default target="self" link behavior... I have no real clue of where the issue might be coming from...: An incorect or closure? I've checked, rechecking... One of the libraries that remained after I uninstalled tailwind A fault in the django_browser_reload extension Something linked with django-unicorn ? Thank you for helping me fix this blocking issue... -
Django Model OneToOneField migrations cannot encounter column
Hello im learning Django and trying to add a new table where I save my isbn numbers and I wanted to make onetoone relation book with isbn number. Django creates the tables of isbn and books aswell. the problem when I do the onetoonefield. models.py from django.db import models class BookNumber(models.Model): isbn_10 = models.CharField(max_length=10, blank=True) isbn_13 = models.CharField(max_length=13, blank=True) class Book(models.Model): title = models.CharField(max_length=36, blank=False, unique=True) description = models.TextField(max_length=266, blank=True, unique=False) price = models.DecimalField(default=0, max_digits=6, decimal_places=2) published = models.DateField(blank=True, null=True) is_published = models.BooleanField(default=False) file = models.FileField(upload_to='covers/', blank=True) cover = models.ImageField(upload_to='covers/', blank=True) #numbers = models.OneToOneField(BookNumber, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.title when I uncomment the numbers it throws the next error: virtenv/lib/python3.12/site-packages/django/db/backends/sqlite3/base.py", line 329, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.OperationalError: **no such column: demo_book.number_id** from the SQLLite: sqlite> .tables auth_group demo_book auth_group_permissions demo_booknumber auth_permission django_admin_log auth_user django_content_type auth_user_groups django_migrations auth_user_user_permissions django_session authtoken_token sqlite> .schema demo_book CREATE TABLE IF NOT EXISTS "demo_book" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(36) NOT NULL UNIQUE, "cover" varchar(100) NOT NULL, "description" text NOT NULL, "file" varchar(100) NOT NULL, "is_published" bool NOT NULL, "price" decimal NOT NULL, "published" date NULL); sqlite> .schema demo_booknumber CREATE TABLE IF NOT EXISTS "demo_booknumber" ("isbn_10" varchar(10) NOT NULL, … -
Simplest way to get Django errors emailed to
I have a Django Application hosted on Python Anywhere with a PostGre back end. Is there anyway I can get the errors that are normally added to the error log to sent to my email, so I can be quickly notified of error. I am familiar with writing simple middleware, but i don't understand Django well enough to know how to capture the errors that go to error-log file. -
How to serialize subprocess.popen()
This is follow-on to Return output of subprocess.popen() in webserver. I have a long running process that is kicked off by a Webserver call (running Django). I'm using subprocess.popen() to spawn the process. I figured out how I can save the stdout and retrieve it later. But since this is a long-running process, I want the client to be able to cancel it. But in order to do that, I need an instance of the popen() object. But it is not serialiable, so I can't store it in a database or anywhere else? Is there any other solution other that just storing it locally in a map in views.py? -
Cannot view Django application installed with helm on Minikube
I have packaged a custom helm chart and did helm install announcements /helm When I go to kubectl get pods and kubectl get deploy it shows the pods and deployments are up. However, when I try to go to the Service IP to see the application, it hangs. I then try to do the command given by the helm install: export SERVICE_IP=$(kubectl get svc --namespace default announcements-helm --template "{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}") And then I get the error: error: error executing template "{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}": template: output:1:10: executing "output" at <index .status.loadBalancer.ingress 0>: error calling index: index of untyped nil I'm very new to Helm and Kubernetes, so I'm not sure what to try to fix this. Any advice? -
Embed HTML file inside another HTML file
I have an HTML file which contains Django Template Language loops and variables. I want to add this file to another HTML file for readability mainly. I tried to use but I am getting a 404 error (file is located inside a folder which I already tried to add to src="folder/file.html"). Thank you in advance. -
django multiple database settingup for multiple region
In a Django project with multiple regional databases, fetching an employee object with a related model from a different database results in the related model being retrieved from the default database instead of the intended regional database. Two regional databases (us and potentially others) DatabaseRouter to route models to their respective databases Issue occurs when trying to prefetch or access related models using foreign key relationships i have share the djangoshellplus and the dbrouter code for reference -
django TemplateSyntaxError at /display/displaymyoperations/ Could not parse the remainder: '(url)' from 'unquote(url)'
hi every one i received the message above when i want to show the oprations that user make i have a project to evluate youtube vidios and web shows in frame in my project this is views.py for myoprations `def displaymyoperations(request): # استرداد بيانات المستخدم الحالي current_user = request.user userprofile=UserProfile.objects.get(user=current_user) # استعلام بيانات العروض التي قام المستخدم بتقييمها display_data = Display_Data.objects.filter(users=userprofile).order_by('-puplish_date') #display_data = Display_Data.objects.filter(users=userprofile) # تحويل قيمة التقييم إلى نص وصفي for display_datum in display_data: if display_datum.choosenum == 1: display_datum.choosenum_text = "نجاح" elif display_datum.choosenum == 2: display_datum.choosenum_text = "فشل" elif display_datum.choosenum == 3: display_datum.choosenum_text = "بحاجة إلى مال" elif display_datum.choosenum == 4: display_datum.choosenum_text = "بحاجة إلى أدوات" else: display_datum.choosenum_text = "مؤجل" # تحضير سياق العرض (context) context = { 'display_data': display_data, } # عرض القالب (template) مع البيانات return render(request, 'display/displaymyoperations.html', context) and this is templete ` {% for display_datum in display_data %} {% if display_datum.displays.isyoutube %} {% with video_id=display_datum.displays.url|slice:"30:" %} {{ display_datum.displays.text }} {% endwith %} {% else %} {% with url=display_datum.displays.url|stringformat:"s" %} {{ display_datum.displays.text }} {% endwith %} {% endif %} <strong>{{ display_datum.choosenum_text }}</strong> {{ display_datum.puplish_date }}<br> {% endfor %}`` the probelm is raise on display_web although display_video is the same i dont know why this error rise …