Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integrity Error raised because of constraint cannot override In Django Admin Panel
I have 4 classes like below: from django.db import models class A(models.Model): title = models.CharField(max_length=100) class B(models.Model): title_b = models.CharField(max_length=100) a = models.ForeignKey(A, on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint(fields=['title_b'], name='unique_title_b') ] class C(models.Model): title_c = models.CharField(max_length=100) a = models.ForeignKey(A, on_delete=models.CASCADE) class D(models.Model): title_d = models.CharField(max_length=100) a = models.ForeignKey(A, on_delete=models.CASCADE) All related classes are used as Inline model which described below: from django.contrib import admin class BInline(admin.TabularInline): model = B class CInline(admin.TabularInline): model = C class DInline(admin.TabularInline): model = D And Model Admin of class A is defined as class AAdmin(admin.ModelAdmin): inlines = [BInline, CInline, DInline] As you can see class B has a constraint on title uniqueness. If I enter duplicate data for class B in admin panel, an Integrity Error is raised and error page with title IntegrityError at /app/A/81ac3366-4cdb-4cbb-a861-340ff188c760/change/ duplicate key value violates unique constraint "unique_title_b" DETAIL: Key (title)=(TestDuplicate) already exists. is shown. In order to show user a friendly message rather than this error page, I override save_related method in class AAdmin like below: def save_related(self, request, form, formsets, change): try: with transaction.atomic(): super().save_related(request, form, formsets, change) except IntegrityError as e: self.message_user(request, 'A related model constraint was violated: {}'.format(e), level=messages.ERROR) I expect that after overriding save_related … -
'EnrollHash' object is not subscriptable : Query on AWS Django
This is my part of the code: @require_http_methods(["POST"]) @csrf_exempt @validate_api_request def processCommand(request): jsonResponse = dict() jsonResponse["status_code"] = 200 jsonResponse["message"] = "Command Sent Successfully" jsonResponse["data"] = dict() if 'childhash' in request.POST and request.POST['childhash'] \ and 'command' in request.POST and request.POST['command']: usrcommand = request.POST['command'].lower() childhash = request.POST['childhash'] enrollhash = EnrollHash.objects.filter(hash=childhash).filter( status='enrolled').first() # apply simple and condition if not enrollhash: jsonResponse["status_code"] = 404 jsonResponse["message"] = "Invalid Child Hash" try: failedCommand = FailedCommand(childHash=childhash, status_code=404, commandData=jsonResponse) failedCommand.save() except IntegrityError: pass requests.post("http://mesh.stg.familytime.io//mdm/checkout", data={"child_mdm_hash": childhash}) return JResponse(jsonResponse) try: child = Child.objects.get(enrollHashId=enrollhash.id) except Child.DoesNotExist: child = None except Child.MultipleObjectsReturned: child = Child.objects.filter(enrollHashId=enrollhash.id).first() if usrcommand.lower() == 'applyrestrictions': if 'data' not in request.POST or not request.POST['data']: jsonResponse["status_code"] = 400 jsonResponse["message"] = "This command requires 'data' variable with json object" try: failedCommand = FailedCommand(childHash=childhash, status_code=400, commandData=jsonResponse) failedCommand.save() except IntegrityError: pass return JResponse(jsonResponse) try: resdict = json.loads(request.POST['data']) except Exception: jsonResponse["status_code"] = 400 jsonResponse["message"] = "Invalid json object for current command" try: failedCommand = FailedCommand(childHash=childhash, status_code=400, commandData=jsonResponse) failedCommand.save() except IntegrityError: pass return JResponse(jsonResponse) allowedRestrictions = Restrictions.restrictionsMapping() if not all(item in allowedRestrictions.keys() for item in resdict.keys()): jsonResponse["status_code"] = 400 jsonResponse["message"] = "Invalid keys in json object" try: failedCommand = FailedCommand(childHash=childhash, status_code=400, commandData=jsonResponse) failedCommand.save() except IntegrityError: pass return JResponse(jsonResponse) try: currentRestrictionsObj = Restrictions.objects.get(childId=child) except Restrictions.DoesNotExist: … -
How to prevent Gmail from altering image URLs in email HTML?
I'm working on an event management portal using Django, and I send a confirmation email upon user registration. The email includes a masthead image. However, when the email is received in Gmail, the URL for the image is being altered, causing rendering issues. Here's the relevant part of my code: def view_registration_form(request, event_id, event_name): event = get_object_or_404(Event, id=event_id, name=event_name) form_template = get_object_or_404(FormTemplate, event=event) view_only = 'view' in request.path if request.method == 'POST' and not view_only: response_data = {field.label: request.POST.get(f'field-{field.id}', '') for field in form_template.fields.all()} email = next((value for key, value in response_data.items() if '@' in value), None) # Save the form response print(email) FormResponse.objects.create(form=form_template, email=email, response_data=response_data) # Send confirmation email using the event's email configuration email_config = EmailNotification.objects.filter(event=event, email_type='confirmation').first() if email_config and email: ngrok_url = 'https://######.ngrok-free.app' # Replace with your ngrok URL masthead_url = f"{ngrok_url}{email_config.masthead.url}" html_message = f""" <html> <head> <style> .email-masthead img {{ width: 100%; height: auto; }} .email-footer {{ margin-top: 20px; font-size: 0.9em; color: #555; }} </style> </head> <body> <div class="email-masthead"> <img src="{masthead_url}" alt="Email Masthead"> </div> <div class="email-body"> {email_config.message} </div> <div class="email-footer"> {email_config.footer} </div> </body> </html> """ print(html_message) send_mail( email_config.subject, email_config.message, 'from@example.com', [email], fail_silently=False, html_message=html_message ) return JsonResponse({'status': 'success', 'message': 'Thank you for registering!'}) fields = [{ 'id': … -
Choosing the Right Architecture for Django Application: Monolith vs. Microservices [closed]
Project Idea: All-in-One School Portal Hi there! I need to build project for a school system which idea is collecting different existing sites (different sizes and technologies). Here's what it will offer: Student Dashboard: Students can log in to view their personal information, subject details, exam scores, and class schedules (including location, teacher, and room). Assignments: Both teachers and students can access the assignment section. Teachers can upload assignments, while students can submit their answers. Teachers can also grade submissions and leave comments. Additional Features: The portal will include other functionalities like teacher ratings and exam applications. Choosing the Right Architecture (Microservice vs Monolith) 1. Microservice vs Monolith I'm deciding between two architecture options: Microservices and Monolith. I've never used microservices before, but I have some ideas on how to implement it. Can you help me choose the best approach? 2. Deep Dive into Microservices If microservices are the better choice, can you explain how it would work for user information? If the first one (Microservice), could you elaborate on that in detail? For instance, should the user information be stored solely in the user table in the database, and if so, how do other services need to access it … -
Django caching causing blank screen on Brave browser
I have a new Django website and have just implemented the filesystem cache (django.core.cache.backends.filebased.FileBasedCache). This seems to work fine when I use a chrome browser to view the site, but when I use the Brave browser, it initially shows the site on the first GET of a url, but upon subsequent refreshes it draws a blank (white) screen. I am new to Django and, after reading the docs I think the following setting are all I need to implement it. And I can see the cache files being created on the server. So I assume I don't need to add the various decorators in the views (just want it to cache all pages). What is also interesting, is that the response time isn't that much quicker (from 550ms > 450ms).. maybe because its a filesystem cache?? Here are my settings CACHES = { "default": { "BACKEND": "django.core.cache.backends.filebased.FileBasedCache", "LOCATION": "/var/tmp/django_cache", "TIMEOUT": 600, } } MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'strip_whitespace.middlewares.HtmlStripWhiteSpaceMiddleware.html_strip_whitespace', 'django.middleware.cache.FetchFromCacheMiddleware', ] -
Django django.contrib.messages add new constant messages.NOTICE
How can I add new constant to Django messages? I want to add a new constant messages.NOTICE in addition to the existing six constants. That I can use to display notices using Bootstrap CSS. # settings.py from django.contrib.messages import constants as messages MESSAGE_TAGS = { messages.DEBUG: 'alert-secondary', messages.INFO: 'alert-info', messages.SUCCESS: 'alert-success', messages.WARNING: 'alert-warning', messages.ERROR: 'alert-danger', messages.NOTICE: 'alert-primary', } -
How to run an exe file of a server through your website and get its Window on browser?
Is it possible to run an exe file on your server through your website to start to use it through your browser? If so, how? I saw some people run pc games in browsers. So I want to do something similar. For back end I use Django, but I can consider any other frameworks. The main question is what technology should I search for? -
Microservice vs Monolith architecture in Django
Project Idea: All-in-One School Portal Hi there! I need to build project for a school system which idea is collecting different existing sites (different sizes and technologies). Here's what it will offer: Student Dashboard: Students can log in to view their personal information, subject details, exam scores, and class schedules (including location, teacher, and room). Assignments: Both teachers and students can access the assignment section. Teachers can upload assignments, while students can submit their answers. Teachers can also grade submissions and leave comments. Additional Features: The portal will include other functionalities like teacher ratings and exam applications. Choosing the Right Architecture (Microservice vs Monolith) 1. Microservice vs Monolith I'm deciding between two architecture options: Microservices and Monolith. I've never used microservices before, but I have some ideas on how to implement it. Can you help me choose the best approach? Microservices: This breaks down the application into smaller, independent services (e.g., User Service, Schedule Service, Assignment Service). Each service has its own database and can be developed, deployed, and scaled independently. Monolith: This is a single, unified application where everything is bundled together. It's simpler to set up initially but can become cumbersome and slow as the application grows. 2. … -
Apps without migrations must not have relations to apps with migrations. Why?
There is a vague paragraph in django docs: Apps without migrations must not have relations (ForeignKey, ManyToManyField, etc.) to apps with migrations. Sometimes it may work, but it’s not supported. I have 5 years of experience and never encountered problems in these cases. In what case it's dangerous to have relation to "apps with migrations" ? -
How make a StringRelatedField that is readonly and declared as ForeignKey available for post requests?
I have the following two model classes in django rest framework class Customer(models.Model): GENDER_CHOICES = [ ('Male', 'Male'), ('Female', 'Female'), ] customer_id = models.AutoField(primary_key=True) firstname = models.CharField(max_length=20) lastname = models.CharField(max_length=30) gender = models.CharField(max_length=6, choices=GENDER_CHOICES) date_of_birth = models.DateField() nationality = models.CharField(max_length=50, null=False) id_card_number = models.CharField(max_length=20, unique=True) passport_number = models.CharField(max_length=20, unique=True) address = models.CharField(max_length=100) phone_number = models.CharField(max_length=20) email = models.EmailField(max_length=254,null=True, blank=True, unique=True) def __str__(self): return f"{self.firstname} {self.lastname}" class Contract(models.Model): INSURANCE_TYPE_CHOICES = [ ('Health', 'Health Insurance'), ('Life', 'Life Insurance'), ('Auto', 'Auto Insurance'), ('Home', 'Home Insurance'), ] contract_number = models.AutoField(primary_key=True) start_date = models.DateField() end_date = models.DateField() insurance_type = models.CharField(max_length=15, choices=INSURANCE_TYPE_CHOICES) insurance_holder = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="contracts") active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.contract_number} {self.insurance_type}" and the following two serializers class ContractSerializer(serializers.ModelSerializer): insurance_holder = serializers.StringRelatedField(read_only=True) class Meta: model = Contract exclude = ("updated_at",) class CustomerSerializer(serializers.ModelSerializer): contracts = ContractSerializer(many=True, read_only=True) class Meta: model = Customer fields = "__all__" I have also created my url endpoints and my views, i have tested my api through Postman and the django-rest built in browasable API and everything is fine but the problem i have is the following. The insurance holder is a foreign key of my customers model so when i do get requests … -
I got Column error each time i change model.py
When i want to change or add one more model in Models.py , i got this error : OperationalError at /admin/groups/group/ no such column: groups_group.کد it only happens when it is the second time that im going to change the model. for the first time it doesnt have any special error. i run this commands but it doesnt help me : python manage.py makemigrations python manage.py migrate and also : python manage.py makemigrations appname python manage.py migrate appname here is my code : Models.py: from django.db import models class Group(models.Model): کد = models.IntegerField(max_length = 5, default = 00000) عنوان = models.CharField(max_length = 30) توضیحات_شماره_یک = models.CharField(max_length = 100) توضیحات_شماره_دو = models.CharField(max_length = 100) توضیحات_شماره_سه = models.CharField(max_length = 100) Views.py: from django.shortcuts import render def groups(request): return render(request, "groups/groups.html") def group(request): return render(request, "groups/group.html") Urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.groups, name = "groups"), path('group/', views.group, name = "group") ] Admin.py: from django.contrib import admin from .models import Group admin.site.register(Group) -
How can both ECS services, using the same Docker image but running in different containers, share the same Docker volume?
I'm working on a Django application where I need to upload a file received from a Django admin form to an S3 bucket asynchronously using a Celery shared task. Here is the relevant code: Django Model: import os import uuid from django.db import models def generate_file_upload_path(instance: "MyModel", filename: str): _, ext = os.path.splitext(filename) randomised_hex = uuid.uuid4().hex # name format: meta_uuid-randomised_hex.mp4 return f"{instance.id}-{randomised_hex}{ext}" class MyModel(models.Model): media_file = models.FileField(upload_to=generate_file_upload_path, blank=True, null=True) thumbnail_file = models.FileField(upload_to=generate_file_upload_path, blank=True, null=True) Model Admin: from django.contrib import admin from .models import MyModel from .tasks import process_media_file class MyModelAdmin(admin.ModelAdmin): list_display = ["release_year", "created_by"] def save_model(self, request, obj, form, change): super(MyModelAdmin, self).save_model(request, obj, form, change) if obj.media_file and obj.thumbnail_file: process_media_file.delay( { "media_meta_id": str(obj.id), "operation": "upload", } ) admin.site.register(MyModel, MyModelAdmin) I tried several solutions to make this work: 1. Base64 Encoding: I saved the base64 encoded string of the media and thumbnail files in the media_url and thumbnail_url fields respectively. In the Celery task, I decoded these strings, created files, and then uploaded them to S3. This approach was slow for larger files. 2. Direct S3 Upload: I saved the file received from the form directly to the S3 bucket using models.FileField(upload_to="path-to-bucket-dir"). This improved the speed but was not an asynchronous … -
Failed to execute postMessage on DOMWindow: http://x.localhost:8000 does not match the recipient window's origin http://localhost:8000
I've looked at a bunch of similar posts here and couldn't find a solution that has helped with this issue. I have an iframe embedded in a domain I don't control. That iframe opens a popup window and I'm trying to communicate between them. Things like window.opener don't work because the browser clears window.opener in this scenario. I've been reading that postMessage is a good way to get this to work but I keep getting this error whenever I try. Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://x.localhost:8000') does not match the recipient window's origin ('http://localhost:8000'). (I am using a Django app w/ JS frontend) I've tried setting window.document.domain='localhost but I get the error: Uncaught DOMException: Failed to set the 'domain' property on 'Document': 'localhost' is a top-level domain. Is there some way for me to do this? TIA! -
Send variable from HTML to python Django 5
Hi Im trying to build a html with python in backen (Django 5) and I trying to take a variable from HTML to python I found this old question and try to use that Django - pass value from html template to python function But I stuck in views.py I dont know how set path in url patters and I follow the answear, please can some help to figure out this my view.py file: urlpatterns = [ path('form_page/',views.form_name_view,name='form_page'), path('register/',views.register,name='register'), path('project_info/',views.project_info,name='project_info'), path('user_login/',views.user_login,name='user_login'), from old question Django - pass value from html template to python function <input type="text" name="name_id" placeholder="placeholder value"/> <input type="submit" name="value1"/> <input type="submit" name="value2"/> <input type="submit" name="value3"/> In the view you can then check with: def some_view(request): if request.method == 'POST': if 'value1' in request.POST: # … pass elif 'value2' in request.POST: # … pass elif 'value3' in request.POST: # … pass You can work with a name="…" attribute on the submit <button>s: <form method="POST" action=""> {% csrf_token %} <input type="text" name="name_id" placeholder="placeholder value"/> <input type="submit" name="value1"/> <input type="submit" name="value2"/> <input type="submit" name="value3"/> </form> In the view you can then check with: def some_view(request): if request.method == 'POST': if 'value1' in request.POST: # … pass elif 'value2' in request.POST: … -
Has anyone created a YouTube video to MP3 converter project in Python using Django?
I would like to create a project to convert YouTube videos to MP3 format and download them. If anyone has already done this, could you please share the GitHub repository link so that I can refer to it? I am looking for a YouTube video to MP3 conversion project in Python using Django. I have confusion on handling large size videos. -
Logging inside function called by django-apscheduler
I have running django-specific scheduler: django-apscheduler and it works fine as scheduler, it starts needed job as required, but i have problem with logging inside called function by scheduler. Logger created with no errors reported, with name as defined in settings.py, but looks strange, has some few atributes, has level = 0, and do nothing with logging commands. Part of settings.py LOGGING = { "version": 1, # the dictConfig format version "disable_existing_loggers": False, # retain the default loggers "handlers": { "debug_file": { "class": "logging.FileHandler", "filename": BASE_DIR / "main/logs/debug.log", "level": "DEBUG", "formatter": "verbose", }, "error_file": { "class": "logging.FileHandler", "filename": BASE_DIR / "main/logs/errors.log", "level": "ERROR", "formatter": "verbose", }, "cron_file": { "class": "logging.FileHandler", "filename": BASE_DIR / "main/logs/cron.log", "level": "DEBUG", "formatter": "verbose", }, }, "loggers": { "main.payment_callback": { "level": "DEBUG", "handlers": ["debug_file", "error_file"], "propagate": True, "cron": { "level": "DEBUG", "handlers": ["cron_file"], "propagate": True, }, }, }, "formatters": { "verbose": { "format": "{name} {levelname} {asctime} {module} {message}", "style": "{", }, "simple": { "format": "{levelname} {message}", "style": "{", }, }, } Part of scheduler.py using to add a job: import logging from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.executors.pool import ProcessPoolExecutor, ThreadPoolExecutor from django_apscheduler.jobstores import register_events, register_job from django.conf import settings from .cron import manager_subscribtion_updater # Create scheduler … -
JsonResponse is not outputing the data in the correct structure
I have the following view function which takes the daily stock prices, and convert them to weekly prices. When I return JsonResponse it does not output the values in the correct form. def weeklyPrices(request, ticker): prices = DailyCandles.objects.filter(symbol=ticker.upper()).all().values() weekly = pd.DataFrame(list(prices)) logic = {'open' : 'first', 'high' : 'max', 'low' : 'min', 'close' : 'last', 'volume': 'sum'} weekly['date'] = pd.to_datetime(weekly['date']) weekly.set_index('date', inplace=True) weekly.sort_index() weekly = weekly.resample('W').apply(logic) weekly.index = weekly.index - pd.tseries.frequencies.to_offset('6D') weekly.reset_index(drop=True, inplace=True) return JsonResponse(weekly.to_dict(), safe=False) The output: open 0 "134.19" 1 "137.0" 2 "136.63" high 0 "137.73" 1 "138.4" 2 "137.74" The expected output is where all the values (open, high, low, close) in row 0 are places together, rather then being placed separately. -
can't connect local Django to postgresql container duo to credentials
I'm working on a Django locally and want to connect it to postgres container, I can connect to postgres using pgadmin but not Django here is my code : Compose file : db: image: postgres:latest ports: - 5432:5432 # volumes: # - ~/apps/postgres:/var/lib/postgresql/data environment: POSTGRES_PASSWORD: ${DATABASE_PASSWORD} POSTGRES_USER: ${DATABASE_USER} POSTGRES_DB: ${DATABASE_NAME} .env file: DATABASE_NAME="postgres" DATABASE_USER="postgres" DATABASE_PASSWORD="password" DATABASE_HOST="localhost" DATABASE_PORT="5432" settings.py file: import os from dotenv import load_dotenv load_dotenv() DATABASES = { 'default': { "ENGINE": "django.db.backends.postgresql", "NAME": os.getenv("DATABASE_NAME"), "USER": os.getenv("DATABASE_USER"), "PASSWORD": os.getenv("DATABASE_PASSWORD"), "HOST": os.getenv("DATABASE_HOST"), "PORT": os.getenv("DATABASE_PORT"), } } -
javascript debug statements not showing up on console
So I am working on a Django mock website similar to restoplus, where restaurants can fill in their name, image, details, menus, sides, toppings, pick their brand colours (primary colours and secondary colours) and it will generate a standard landing page for that restaurant using the brand colours and details and menus. Now the problem is I am trying to update the price in real time using js depending on what the user selects. But it's not working. Also the quantity + - buttons are also not working. Now for that I have tried to use debug statements but even when I click on the buttons or select a menuitem option, neither the price gets updated not the quantity, and the console is clear, nothing appears on the console. Why is this? Can anyone help me out here? Thanks! My models.py: from django.db import models from django.contrib.auth.models import User from django.utils.text import slugify class Restaurant(models.Model): name = models.CharField(max_length=100) description = models.TextField() image = models.ImageField(upload_to='restaurant_images/') banner_image = models.ImageField(upload_to='restaurant_images/', null=True) primary_color = models.CharField(max_length=7) # Hex color code secondary_color = models.CharField(max_length=7) # Hex color code favicon = models.FileField(upload_to='restaurant_favicons/', null=True, blank=True) slug = models.SlugField(unique=True, max_length=100, null=True) def save(self, *args, **kwargs): if not self.slug: self.slug … -
Can one inherit a ModelSerializer and Merge Models
I am trying to inherit djoser's UserCreatePasswordRetypeSerializer Djoser Modelserializer's model is User. The child Serializer that I am implementing represents a different model, Customer. So could one do: class CustomerSerializer(UserCreatePasswordRetypeSerializer): class Meta: model=Customer fields = ('customer_name',)+UserCreatePasswordRetypeSerializer.Meta.fields When I do this django is complaining because Customer model does not have the model fields that User has. this is the customer model but this model does exactly represent this model. class Customer(models.Model): customer_name = models.CharField(max_length=255) user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='user') Would passing User as a parent class solve this issue? class Customer(User): customer_name = models.CharField(max_length=255) would this work with inherited ModelSerializers. As Djoser is an app I can not change the UserCreatePasswordRetypeSerializer to fit my needs. I can either inherit is or this is the second approach i was thinking. create something like, class CustomerSerializer(serializers.ModelSerializer): user=UserCreatePasswordRetypeSerializer class Meta: fields = ('customer_name','user') since this is a nested serializer I will have to write create method myself. the issue is how can I call the create of the UserCreatePasswordRetypeSerializer in the create method that I implement because I need to use the create method of UserCreatePasswordRetypeSerializer since it handles sending emails and all the other features in the serializer. So I can not basically just pop … -
Unable to form ORM queryset in Django
I am required to include a field present in a parent table to a grandchild table. I have to form a queryset to achieve the mentioned to return list of records for my mobile application. Refer below my models to have a clear picture. #models.py class Client(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) contact = models.CharField(max_length=10, unique=True) email = models.EmailField(null=True) address = models.TextField() modified_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'clients' ordering = ['id'] verbose_name = 'Client' verbose_name_plural = 'Clients' def __str__(self): return str(self.id) + ". " + self.name class Rent(models.Model): id = models.AutoField(primary_key=True) address = models.TextField() rent_amount = models.IntegerField() deposit_amount = models.IntegerField() rent_date = models.DateField() document = models.TextField(null=True) remarks = models.TextField(null=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) client_id = models.IntegerField() class Meta: db_table = 'rent' verbose_name = 'Rent' verbose_name_plural = 'Rents' def __str__(self): return self.id def get_client_name(self): client = Client.objects.get(pk=self.client_id) return client.name class RentSchedule(models.Model): id = models.AutoField(primary_key=True) rent_due_date = models.DateField() paid_amount = models.IntegerField(default=0) remaining_amount = models.IntegerField() payment_status = models.IntegerField(choices=[(0, 'Unpaid'), (1, 'Paid')], default=0) created_at = models.DateTimeField(auto_now_add=True) rent_id = models.IntegerField() class Meta: db_table = 'rent_schedule' verbose_name = 'Rent Schedule' verbose_name_plural = 'Rent Schedule' def __str__(self): return self.id def get_client_name(self): rent = Rent.objects.get(pk=self.rent_id) client = Client.objects.get(pk=rent.client_id) return client.name … -
Azure Deployment - Server Error (500). Environmental Variables Error?
my azure environmental variables OPENAI_API_KEY = os.getenv('OPENAI_API_KEY') This doesn't seem to be working for azure deployment? What other steps do I need to make to ensure my azure deployed website can access my openai api key? I have created a vector database driven website using django. I am able to run the webapp and perform searches using the api key on local host. I am able to do this while connected to the azure database. However, when I access my website through the public domain, I can't seem to perform searches. I've added the api key to the azure environmental variables already. It says Server Error 500 when I try to perform searches. Is there anything else I need to do? What could be causing server error 500? -
How do I reference the author name column from the Author table in my InsertBook function?
(https://i.sstatic.net/EiBqboZP.png) In the browser, I'm trying to add a new book to my books table but I keep receiving a Value error from django where for example I can't assign "'Virginia Woolf'": "Book.author" must be a "Author" instance. After I enter all the fields to add a new book and then click the Insert button in the browser, I receive the Value error. Below is the structure of my sql table as well as related python scripts for reference: --Create the books table CREATE TABLE books ( book_id SERIAL PRIMARY KEY, title VARCHAR(200) NOT NULL, author_id INTEGER REFERENCES authors(author_id), genre VARCHAR(50), price DECIMAL(10, 2), publisher VARCHAR(100), --Adding the column for the ISBN to populate the table with an extra instance isbn VARCHAR(20) ); --Create the videos table CREATE TABLE videos ( video_id SERIAL PRIMARY KEY, title VARCHAR(200) NOT NULL, genre VARCHAR(50), price DECIMAL(10, 2), publisher VARCHAR(100), release_date DATE ); views.py: from django.shortcuts import render from bookstore.models import Author, Book from django.contrib import messages from bookstore.forms import Authorforms, Bookforms def index(request): return render(request, 'index.html') def author(request): allauthor=Author.objects.all() return render(request, 'author_list.html', {'authors': allauthor}) def Insertauthor(request): if request.method=="POST": if request.POST.get('author_id') and request.POST.get('name') and request.POST.get('birthdate') and request.POST.get('nationality'): saverecord=Author() saverecord.author_id=request.POST.get('author_id') saverecord.name=request.POST.get('name') saverecord.birthdate=request.POST.get('birthdate') saverecord.nationality=request.POST.get('nationality') saverecord.save() messages.success(request,'author … -
Django Logout request returning forbidden 403 CSRF related
from rest_framework import views, status from rest_framework.response import Response from django.contrib.auth import authenticate, login,logout from rest_framework.permissions import AllowAny, IsAuthenticated from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse class LoginView(views.APIView): permission_classes=[AllowAny] def post(self, request): username = request.data.get('username') password = request.data.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return Response({'message': 'Logged in successfully'}, status=status.HTTP_200_OK) return Response({'message': 'Invalid credentials'}, status=status.HTTP_400_BAD_REQUEST) class LogoutView(views.APIView): def post(self, request): logout(request) return Response({'message': 'Logged out successfully'}, status=status.HTTP_200_OK) @csrf_exempt def logoutView(request): print(request.COOKIES) logout(request) return JsonResponse({'message': 'Logged out successfully'}, status=status.HTTP_200_OK) class UserInfoView(views.APIView): permission_classes=[IsAuthenticated] def get(self, request): user = request.user return Response({'username': user.username}, status=status.HTTP_200_OK) When sending request to login or userinfoview it works fine with csrf tokens. however the class LogoutView returns forbidden 403. The logoutView FUNCTION works fine ONLY when csrf_exmpt is applied. when printing request.cookies its returning: {'csrftoken': 'DdQZJC56QBSAcDqXVlrXz4mMeVWitpNV', 'sessionid': 'poul3qidl8xw4k5bp2rwazbxo76eq9sq'} which is what it returns in all the other classes as well. i tried to csrf exmpt the class because thats what i ultimitly want to use instead of the function for the cleaner looking code but couldnt figure out how to exmpt the class. moreover, i dont want to exmpt the csrf to begin with unless its the only solution. -
Why do I get the email but not the ID of the user in Django when using users_data = validated_data.pop(‘users’, [])?
I am working on a Django project and encountering an issue related to extracting user data in a serializer's create method. In the code, users_data contains email addresses of users, but I need to associate users with the task using their IDs instead. However, when I replace User.objects.get(email=user_data) with User.objects.get(id=user_data), I encounter an error. How can I modify my serializer's create method to correctly associate users with their IDs instead of emails? Any insights or suggestions would be greatly appreciated. Thank you! Here is a snippet of my code. Payload: { "id": null, "title": "Task Title", "description": "Task Description", "due_to": "2024-06-28T22:00:00.000Z", "created": null, "updated": null, "priority": "LOW", "category": "TECHNICAL_TASK", "status": "TO_DO", "subtasks": [ { "task_id": null, "description": "Subtask 1", "is_done": false } ], "users": [ 1 ] } class BaseTaskSerializer(serializers.ModelSerializer): """Serializes a task object""" subtasks = SubtaskSerializer(many=True, required=False) class Meta: model = Task fields = ['id', 'title', 'description', 'due_to', 'created', 'updated', 'priority', 'category', 'status', 'subtasks', 'users'] read_only_fields = ['created', 'updated'] def create(self, validated_data): #print('self: ', self) users_data = validated_data.pop('users', []) subtasks_data = validated_data.pop('subtasks', []) task = Task.objects.create(**validated_data) print(users_data) #print('validated_data', validated_data) #print('users_data', users_data) for user_data in users_data: #print(user_data) #print('users_dataaa: ', users_data) #user = User.objects.get(id=user_data) user = User.objects.get(email=user_data) task.users.add(user) for subtask_data in …