Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access Django session using class-based views? (with Angular) The self.request.session.get('key') returning None
I am currently developing a Django/Angular application. Within the frontend component, several methods are called upon initialization (ngOnInit), and these methods all rely on the same base query (and then they do other things with that data). What i'm trying to do is to create a single method that retrieves the base data used by these other methods. What I'm currently doing here is to query this base data once, store it in the Django session and then access it from the other views as needed (I would appreciate any alternative points of view if you think this aint a good solution). The issue is that I can't access the Django session beyond the view where is being created. Whenever I try to access it from the other views I get 'None'. Here is a simplified version of my Angular code: export class AnalysisComponent { fieldID = 4; constructor(private _service: Service) {} async ngOnInit() { await this.getBaseData(this.fieldID); // I used async/await so the other methods do not execute until this one is over. this.testOne(this.fieldID); this.testTwo(this.fieldID); this.testThree(this.fieldID); } async getBaseData(field_id){ try { const result = await this._service.getBaseData(field_id).toPromise(); } catch (error) { console.error(error); } } testOne(field_id) { this._service.testOneView(field_id).subscribe( (data: any) => { … -
How to search through multiple tables using Postgres Full Text Search and GIN index in Django
models.py from django.contrib.postgres.indexes import GinIndex from django.db import models from django.contrib.postgres.search import SearchVectorField class FilmTag(models.Model): name = models.CharField(max_length=255) class Film(models.Model): film_id = models.AutoField(primary_key=True) title = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) tags = models.ManyToManyField(FilmTag, null=True, blank=True) vector_column = SearchVectorField(null=True) # new field def __str__(self): return ', '.join(['film_id=' + str(self.film_id), 'title=' + self.title, 'description=' + self.description]) class Meta: indexes = (GinIndex(fields=["vector_column"]),) # add index 0002_migration # Generated by Django 5.0.4 on 2024-04-03 19:41 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("app", "0002_film_vector_column_film_app_film_vector__2213d6_gin"), ] operations = [ migrations.RunSQL( sql=''' CREATE TRIGGER vector_column_trigger BEFORE INSERT OR UPDATE OF title, description, vector_column ON app_film FOR EACH ROW EXECUTE PROCEDURE tsvector_update_trigger( vector_column, 'pg_catalog.english', title, description ); UPDATE app_film SET vector_column = NULL; ''', reverse_sql=''' DROP TRIGGER IF EXISTS vector_column_trigger ON film; ''' ), ] I'd like to enhance my film search functionality by incorporating tags using Postgres Full Text Search. How can I go about implementing this? Currently, the search is limited to the film's text and description. -
How to pass request object for dynamic form in django-formtools form wizzard?
Probably there is someone who's tried to make multistep form wizzard, but the goal is to make them dynamic. By dynamic i mean that after submiting one form, this form remains in its position and data from this form is sent in ajax and if it's valid a server sent html with second form. Seems to be easy, but i'm really strugling how to render csrf_token in dynamic forms. So, i have main.html like: <div class="col-xxl-6" id="testId"> {{ wizard.form }} </div> and partial htmls with forms, like first_form.html: {% load static %} <form action="{% url 'app:url' %}" method="post" novalidate> {% csrf_token %} {{ wizard.management_form }} {{ first_form.field }} </form> and the second_form.html is the same, let's say so, obviously, i have to pass a request and it's completely possible to do that with render_to_string if form is supposed to be sent with AJAX. But in case with regular rendering (without AJAX) render_to_string is not the appropriate way. Another best place i find: __init__ in my form i looked at the render() method in class RenderableMixin, which is parent for forms.Form and wanted to do something like this: class MyForm: template_name = "app/templates/forms/first_form.html" def __init__(self, request=None, *args, **kwargs): self.request = request … -
How to upload files with Django and Python
I want to let the user upload some excel files, and first im trying to save them in the media/uploaded/int:projectid (that i want to create if its not created already). But when i try to upload it, in the /admin it says: Error in field "template_file": This field is required. Error in field "title": This field is required. this is my views.py: @csrf_protect @login_required(login_url='login') def uploadTemplate(request, proyecto_id): proyecto = get_object_or_404(Project, id=proyecto_id) if request.method == 'POST': form = UploadTemplateForm(request.POST, request.FILES) if form.is_valid(): template_file = request.FILES.get('template_file') if template_file: try: create_project_folder(proyecto) # Crear la carpeta del proyecto si no existe handle_uploaded_file(template_file, proyecto) messages.success(request, 'File uploaded successfully.') return redirect('success') except Exception as e: messages.error(request, f'Error handling the file: {e}') else: messages.error(request, 'No file provided in the form.') else: for field, errors in form.errors.items(): for error in errors: messages.error(request, f'Error in field "{field}": {error}') else: form = UploadTemplateForm() return render(request, 'uploadFileBox.html', {'form': form, 'project': proyecto}) def create_project_folder(proyecto): base_folder = 'media/uploaded' project_folder = os.path.join(base_folder, str(proyecto.id)) if not os.path.exists(project_folder): os.makedirs(project_folder) def handle_uploaded_file(f, proyecto): try: base_folder = 'media/uploaded' project_folder = os.path.join(base_folder, str(proyecto.id)) file_path = os.path.join(project_folder, f.name) with open(file_path, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) print("Archivo guardado correctamente.") except Exception as e: print("Error al manejar el archivo:", … -
django channels took to long to shut down and was killed error in backend
I used django channels in this project and created a consumer in the following code: class WSConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["room_name"] self.stid=self.scope["url_route"]["kwargs"]["stid"] self.types=self.scope["url_route"]["kwargs"]["types"] self.room_group_name = f"station_{self.room_name}" if (self.types=="student"): try: workclass=WorkClass.objects.get(workclass_id=self.room_name) st=Station.objects.get(id=self.stid) if st in workclass.stations.all(): st.state=True st.save() async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() else: self.disconnect(10) except WorkClass.DoesNotExist: self.disconnect(10) elif(self.types=="teacher"): async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() except WorkClass.DoesNotExist: raise StopConsumer() else: raise StopConsumer() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) if(self.types=="student"): st=Station.objects.get(id=self.stid) st.state=False st.save() async_to_sync(self.channel_layer.group_send)( self.room_group_name, {"type":"list_stations","message":self.room_name,"roles":"stations"} ) async def websocket_disconnect(self, message): await self.channel_layer.group_send( self.room_group_name, {"type":"list_stations","message":self.room_name,"role":"stations"} ) await super().websocket_disconnect(message) def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] role=text_data_json['roles'] types=text_data_json['type'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, {"type":types,"message":message,"role":role} ) # Receive message from room group #list of method... in settings i used this configuration: INSTALLED_APPS = [ 'daphne', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #apps ] ASGI_APPLICATION = "backend.asgi.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } The problem is that after some time in the server terminal it shows the error "took to long to shut down and was killed", this time is variable. In the meantime, I run it on the front-end by accessing through the IP address on another computer No matter how much I googled and … -
Is nodejs better than django for real time backend system development
Is nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will helpIs nodejs better than django for real time backend system development a comprehensive guide will help -
django Channels / django restframework Pending task
I have a django channels projeto to handle a websocket connections, but some http request are blocking the app, and im receiving this error: Application instance <Task pending name='Task-3739' coro=<ProtocolTypeRouter.call() running at /usr/local/lib/python3.10/site-packages/channels/routing.py:62> wait_for=<Future pending cb=[shield.._outer_done_callback() at /usr/local/lib/python3.10/asyncio/tasks.py:864, Task.task_wakeup()]>> for connection <WebRequest at 0x7efc603c8250 method=POST uri=/charger_api/heartbeat/ clientproto=HTTP/1.1> took too long to shut down and was killed. the entire comsumer are async and the rest part of django app is sync this is my Comsumer class ChargerSessionConsumer(AsyncJsonWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.client_id = None self.group_name = None async def connect(self): self.client_id = self.scope["url_route"]["kwargs"]["client_id"] await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.group_name, self.channel_name) raise StopConsumer() I try to raise to raise the stodComsumer ocording the documentation but the error percists -
App Runner Django Deployment Error Python Version3.11
I'm trying to deploy my Django backend to AppRunner. My apprunner.yml is this; version: 1.0 runtime: python311 build: commands: build: - pip3 install pipenv - pipenv install post-build: - python3 manage.py test env: - name: DEBUG value: "on" - name: SECRET_KEY value: "django-insecure-a=0f%a$+p$cyb)xobnaa42@gypz3q&f-!n&03&_t$t#_bn2+h4" - name: ALLOWED_HOSTS value: "*" run: runtime-version: 3.11 pre-run: - pip3 install pipenv - pipenv install command: pipenv run gunicorn django_apprunner.wsgi --log-file - network: port: 8000 env: 8000 env: - name: DEBUG value: "on" - name: SECRET_KEY value: "django-insecure-a=0f%a$+p$cyb)xobnaa42@gypz3q&f-!n&03&_t$t#_bn2+h4" - name: ALLOWED_HOSTS value: "*" In the Application Log File this error comes; raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I tried to deploy my Django Backend via AppRunner but I got this error. -
How do I display the main category?
I need the main category to be displayed once, and below it its characteristics {% load static %} <div class="characteristics"> <h2>Характеристики</h2> {% for values in specs %} {{ values.category.gl_category }} <br> {% endfor %} {% for char in specs %} <div class="uk-grid-small s-char-2" uk-grid> <div class="uk-width-expand" uk-leader="media: @m">{{ char.category }}</div> <div>{{ char.description }}</div> </div> {% endfor %} </div> That's what's going on, and that's what it takes. -
is_domain_same() causing the attribute error "'list' object has no attribute 'lower'"
i am trying to deploy the website ,first i deploy it on railway and it works properly, but when i buy a custom domain for it from godaddy and try to open the website using this damain it gives an error that 'list' object has no attribute 'lower'here you can see the error in picture,, Note: This function assumes that the given host is lowercased and has already had the port, if any, stripped off. Return True for a valid host, False otherwise. """ return any( pattern == "*" or is_same_domain(host, pattern) for pattern in allowed_hosts ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … ) def parse_accept_header(header): return [MediaType(token) for token in header.split(",") if token.strip()] Local vars /opt/venv/lib/python3.11/site-packages/django/utils/http.py, line 235, in is_same_domain Any pattern beginning with a period matches a domain and all of its subdomains. (e.g. .example.com matches example.com and foo.example.com). Anything else is an exact string match. """ if not pattern: return False pattern = pattern.lower() ^^^^^^^^^^^^^ … return ( pattern[0] == "." and (host.endswith(pattern) or host == pattern[1:]) or pattern == host ) is any one know about this problem and its solution, ALLOWED_HOSTS = ['xyz.railway.app','127.0.0.1'],these are the allowed hosts and is_domain_same() causing the error 'list' object has no attribute 'lower' -
Django & Digital Ocean deployment ENGINE error
I have a Django app deployed in Digital Ocean, and it all works with my database and everything. Now, I have created this script, that I want to use to populate my database from some CSV files I have. Whenever I run the script, I get this error: django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Meaning it cannot find/use my database from the script? My script is: import os import csv import django from datetime import datetime os.environ.setdefault('DEVELOPMENT_MODE', 'False') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SpotOn.settings') os.environ["DATABASE_URL"] = 'postgresql://doadmin:password@route:25060/db_name?sslmode=require' django.setup() from WebshopDashboard.models import Webshop, Product def upload_data_from_csv(csv_filepath, webshop_name, default_date_str): webshop, created = Webshop.objects.get_or_create(name=webshop_name) print(f"{'Created' if created else 'Using existing'} webshop: {webshop_name}") # Convert the default_date_str to a date object default_date = datetime.strptime(default_date_str, '%Y-%m-%d').date() with open(csv_filepath, mode='r', encoding='utf-8') as file: reader = csv.DictReader(file) for row in reader: product_name = row['Name'].strip() price = Product.parse_price(row['Price'].strip()) compare_price = Product.parse_price(row['Compare Price'].strip()) specified_date_str = row.get('Specified Date', '').strip() # If a specified date is provided in the CSV, use it; otherwise, use the default_date specified_date = datetime.strptime(specified_date_str, '%Y-%m-%d').date() if specified_date_str else default_date product, created = Product.objects.update_or_create( name=product_name, webshop_name=webshop, defaults={ 'price': price, 'compare_price': compare_price, 'default_date': specified_date } ) print(f"{'Added' if created else 'Updated'} product: … -
React Components not showing on server
I'm at the very beginning in React and I'm wondering why the components aren't loading.. Beforehand I've used some outdated code, which I'm not sure I got rid of entirely. Repo: https://github.com/04lex/alex-workspace/tree/1da077943681bccba1876165cfd299bf7ee861fd/Internship%20Projects/Full%20Stack%20Web%20App/music_controller I have tried both path and exact_path, 's, etc. I also tried reviewing other questions but I didn't seem to make it work still. homepage.js: import React, { Component } from 'react'; import RoomJoinPage from './RoomJoinPage'; import CreateRoomPage from './CreateRoomPage'; import { BrowserRouter as Router, Routes, Route }from 'react-router-dom'; export default class HomePage extends Component { constructor(props) { super(props); } render() { return ( <Router> <Routes> <Route path='/' element={<p>This is the homepage</p>} /> <Route path='/join' element={<RoomJoinPage/>} /> <Route path='/create' element={<CreateRoomPage/>} /> </Routes> </Router> ); } } App.js: import React, { Component } from "react"; import { render } from "react-dom"; import HomePage from "./homepage"; import RoomJoinPage from "./RoomJoinPage"; import CreateRoomPage from "./CreateRoomPage"; export default class App extends Component { constructor(props) { super(props); } render() { return ( <div> <HomePage /> </div> ); } } const appDiv = document.getElementById("app"); render(<App />, appDiv); I have also added the path in the frontend url's from django.urls import path from .views import index urlpatterns = [ path('', index), path('join', index), path('create', index) … -
Autocomplete dropdown for related-field filtering in Django admin
I'd like to have a nice autocomplete dropdown in my Django admin backend for filtering out results in the project model according to the subject attached to a person. this is my models.py: class Person(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True) class PersonRole(models.Model): project = models.ForeignKey('Project', on_delete=models.CASCADE) class Project(models.Model): person = models.ManyToManyField(Person, through=PersonRole) For now I managed to get a simple list using SimpleListFilter with the following code in admin.py: class PISubjectFilter(admin.SimpleListFilter): title = 'PI Subject' parameter_name = 'subject' def lookups(self, request, model_admin): return Subject.objects.values_list("id", "name").order_by("id") def queryset(self, request, queryset): count = range(1, 100) for x in count: if self.value() == str(x): return queryset.filter( person__personrole__person__subject=x ).distinct() break How can I turn this long list into a autocomplete dropdown? I've almost achieved what I want by specifying a custom template for my form in admin.py with template = "custom_form.html", with something like the below: {% load i18n %} {% load static %} <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <details data-filter-title="{{ title }}" open> <summary> {% blocktranslate with filter_title=title %} By {{ filter_title }} {% endblocktranslate %} </summary> <select id='select_subject' onchange="location = this.value;"> {% for choice in choices %} <option value="{{ choice.query_string|iriencode }}">{{choice.display}}</option> {% endfor %} </select> </details> … -
Using FormSet to editing a array of same form in django
My requirement to enable user to add description and remark against multiple files uploaded earlier.I am using formset to display a set of partial field data from a model 'medical_doc'. I am new to django and am not able to implement it properly. form.py class Files_uploadedForm(forms.Form) doc_name=forms.CharField(max_length=100) doc_type=forms.CharField(max_length=5) description=forms.CharField(max_length=100) remarks=forms.CharField(max_length=100) Files_uploadedFormSet=formset_factory(Files_uploadedForm) view.py if request.method='POST' med_qrset=medical_doc.objects.values('doc_name','doc_type','description','remarks') .filter(doc_id=doc_id) formset=Files_uploadedFormSet(queryset=med_qrset) context = {'formset'=formset} return render(request,"upload_doc.html") upload_doc.html ... {% for form in formset %} form.as_p {% endfor %} Please excuse the syntax errors.My issue here is to know it this method of initialising formset is correct. Because I get a error saying that BaseFormSet.init() got an unexpected keyword argument 'queryset'. Please help. -
Django post request is good in postman but not from frontend with the same payload
Django api interface and postman is working fine in posting the payload, however with the exact same payload posted from my frontend it doesn't work even while disabling cors. -This is my mode: `class Activity(models.Model): cid = models.CharField(max_length=10) percent = models.IntegerField() name = models.CharField(max_length=255)` -this is my view: class ActivityViewSet(viewsets.ModelViewSet): queryset = Activity.objects.all() serializer_class = ActivitySerializer def get_queryset(self): queryset = self.queryset # Start with the base queryset # Get the cid from the query parameters cid = self.request.query_params.get('cid') # If cid is provided in the query parameters, filter the queryset if cid: queryset = queryset.filter(cid=cid) return queryset -this is my url: `router.register(r'activities', ActivityViewSet)` And this is my frontend code: \` const postOutcomesAsync = async () =\> { function getCSRFToken() { const csrfCookie = document.cookie.match(/csrftoken=(\[\\w-\]+)/); if (csrfCookie) { return csrfCookie\[1\]; } return null; } const csrfToken = getCSRFToken(); axios.post('http://127.0.0.1:8000/activities/', inputValues[2], { headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken } }); console.log('All activities posted successfully'); } \` The backend log shows OPTIONS 200 ok and no posting at all. Network tab shows post request failed but OPTIONS 200 ok. Axios shows network error 500. -
Vue 3 mutation is not reflected on Django backend
In my blog app, I want to like, dislikes and share posts using Vue 3 composition API. I provided Mutation class in schema.py and UpdatePostCounts Vue component. But for some odd reason the mutation is not showing on the Django backend database in Django Admin interface. How can I resolve this? Also how can I embed the likes, dislikes, and shares as I use SocialMedia.vue buttons? Schema.py: import graphene from django.contrib.auth import get_user_model from graphene_django import DjangoObjectType from blog import models class UserType(DjangoObjectType): class Meta: model = get_user_model() class AuthorType(DjangoObjectType): class Meta: model = models.Profile class TagType(DjangoObjectType): class Meta: model = models.Tag class PostType(DjangoObjectType): class Meta: model = models.Post class Query(graphene.ObjectType): all_posts = graphene.List(PostType) author_by_username = graphene.Field(AuthorType, username=graphene.String()) post_by_slug = graphene.Field(PostType, slug=graphene.String()) posts_by_author = graphene.List(PostType, username=graphene.String()) posts_by_tag = graphene.List(PostType, tag=graphene.String()) def resolve_all_posts(root, info): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .all() ) def resolve_author_by_username(root, info, username): return models.Profile.objects.select_related("user").get( user__username=username ) def resolve_post_by_slug(root, info, slug): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .get(slug=slug) ) def resolve_posts_by_author(root, info, username): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .filter(author__user__username=username) ) def resolve_posts_by_tag(root, info, tag): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .filter(tags__name__iexact=tag) ) class Mutation(graphene.ObjectType): like_post = graphene.Field(PostType, id=graphene.ID()) dislike_post = graphene.Field(PostType, id=graphene.ID()) share_post = graphene.Field(PostType, id=graphene.ID()) def resolve_like_post(self, info, id): post = models.Post.objects.get(pk=id) post.likes += … -
Image Creation via nested serializer field
MODELS: class Product(models.Model): uuid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) slug = AutoSlugField(populate_from = 'name', unique=True) shop = models.ForeignKey(Shop, on_delete=models.CASCADE) name = models.CharField(max_length=255) description = models.TextField(blank=True, null= True) product_profile_image = VersatileImageField(blank=True, null= True, upload_to= 'images/product_profile') price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): return self.name class Image(models.Model): uuid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) image = VersatileImageField(blank=True, null= True, upload_to='images/') def __str__(self): return f"image of {self.product.name}" SERIALIZERS: class ImageSerializer(DynamicFieldsModelSerializer): class Meta: model = Image fields = ['uuid','image'] class ListCreateProductSerializer(DynamicFieldsModelSerializer): images = ImageSerializer(many= True, required=False, source='image_set') class Meta: model = Product fields = ['uuid', 'name', 'description', 'price', 'product_profile_image', 'quantity', 'images'] def create(self, validated_data): images = validated_data.pop('images', []) product = Product.objects.create(**validated_data) for image in images: Image.objects.create(product=product, image=image) return product VIEWS: class ListCreateProductView(ListCreateAPIView): serializer_class = ListCreateProductSerializer permission_classes = [ShopPermission] def get_queryset(self): shop_uuid = self.kwargs.get('shop_uuid') shop = get_object_or_404(Shop, uuid=shop_uuid) products = Product.objects.filter(shop=shop) if not products: raise NotFound(detail="This shop does not have any products") return products def perform_create(self, serializer): shop_uuid= self.kwargs.get('shop_uuid') shop = get_object_or_404(Shop, uuid=shop_uuid) product = serializer.save(shop=shop) return product When I upload images in POSTMAN, no new images are being created or associated with the new product instance. Please Help I tried this # images = serializers.ListField(child=serializers.ImageField(), required=False, write_only= True) that worked, but … -
Ways to intercept error responses in Django and DRF
The problem: Django errors are values to details keys. Django Rest Framework (DRF) errors are values to detail keys. Therefore, having an application that raises both Django and DRF exceptions is inconsistent by default. I want a way to change the response errors so that they look like this: { "message": ..., "code": ... } Are there ways to handle both Django and DRF exceptions at the same time and respond with a custom response body? I have tried: custom exception handler in DRF, but this only handles DRF exceptions custom error messages when defining models email = models.EmailField(error_messages={"required": {"message": "", "code": 123}}) but Django can't handle a dictionary as a message Adding a DRF validator to my serializer: email = serializers.EmailField( validators=[ UniqueValidator( queryset=models.User.objects.all(), message={ "message": "a user with this email already exists", "code": status.EMAIL_EXISTS, }, ) ], ) but this does not override the response body, but instead it embeds the message as an error message to the {"details": {"message": {<embedded dictionary>}}} The only thing I believe would work, is to try-except all exceptions inside my Views, but I would like to know if there is a prettier way than placing all my Views inside try blocks. -
How to add a duplicate column to a table?
I am retrieving data from the database using Django ORM: ws = Ws.objects.all() ws = ws.filter(*q_objects, **filter_kwargs) ws = ws.order_by(*sort_list) ws = ws.annotate(created_unix=UnixTimestamp(F('created')), date_unix=UnixTimestamp(F('date'))))) total_sum = ws.aggregate(total=Sum('ts_time', output_field=DecimalField()))['total'])['total'] LIST_FIELDS[1], LIST_FIELDS[2] = 'created_unix', 'date_unix' return JsonResponse({'table_data': list(ws.values_list(*LIST_FIELDS)), 'summ_time': total_sum}, safe=False) ``` I need to add a new column to LIST_FIELDS, one that is True for every pair of rows that have multiple fields matching or False For example: For LIST_FIELDS[0] and LIST_FIELDS[2] LIST_FIELDS[0] LIST_FIELDS[1] LIST_FIELDS[2] LIST_FIELDS[3] 1 1 3 True 1 1 2 True 2 1 1 False 1 1 2 True 1 1 3 True I try ask GPT4, but T9 is stubbornly giving me match=Case( When(field1=F('field2'), then=Value(True)), default=Value(False), output_field=BooleanField() ) ) But it's like comparing field1 == field2 IN ONE row And I need True, if row1[field1] == row2[field1] and row1[field2] == row2[field2] -
I want to create a Django Apllication for a french compnay but using 'iso-8859-1' encoding not UTF-8 how i can do that?
I have added these 2 lines in settings file of the Django App: FILE_CHARSET = 'iso-8859-1' DEFAULT_CHARSET = 'iso-8859-1' and in html page that i want to render it I specified the encoding but i always got error UnicodeEncodeError: 'latin-1' codec can't encode character '\u2019' in position 9348: ordinal not in range(256) because of the name 'système' in the line English: système load is very high of my html template how i can resolve it? -
while working on vs code using django framework faced error
used python manage.py instead got this error. C:\Users\AppData\Local\Programs\Python\Python312\python.exe: can't open file 'C:\ i was expecting to get a file db.sqlt.3 file and a link to a host site. What to do and how to fix this -
Unable to Save UserModel Data to Database Using Django Form
Problem: I'm encountering issues with my Django registration form where user data isn't being saved to the database. Details: I have implemented a Django registration form. My Django project includes a registration view and template. JavaScript modals are utilized for displaying the registration template. The UserModel is employed to handle user data. Despite inputting data into the registration form, user information isn't being saved to the database. Code: Base Page which contains modals: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="{% static 'styles.css' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> <!-- JavaScript for modals --> <script> // Function to show login modal // Function to show login modal function showLoginModal() { document.getElementById('login-modal').style.display = 'block'; document.getElementById('logout-modal').style.display = 'none'; // Hide logout modal document.getElementById('main-content').style.filter = 'blur(5px)'; } // Function to show logout modal function showLogoutModal() { document.getElementById('logout-modal').style.display = 'block'; document.getElementById('login-modal').style.display = 'none'; // Hide logout modal document.getElementById('main-content').style.filter = 'blur(5px)'; } // Function to show register modal function showRegisterModal() { document.getElementById('register-modal').style.display = 'block'; document.getElementById('main-content').style.filter = 'blur(5px)'; } // Function to hide modals function hideModals() { document.getElementById('login-modal').style.display = 'none'; document.getElementById('register-modal').style.display = 'none'; document.getElementById('logout-modal').style.display = 'none'; document.getElementById('main-content').style.filter = 'none'; // Remove … -
IntegrityError at /createad/ (1048, "Column 'user_id' cannot be null") in Django
I'm making a comic book resale site in django. There is an Ad model that allows you to create an ad for the sale. It has a user (Django User) foreign key. models.py class Ad(models.Model): ad_id = models.AutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=50, null=False, blank=False) description = models.TextField(null=True, blank=True) forms.py class AdForm(forms.ModelForm): class Meta: model = Ad fields = ('title', 'description', 'publisher', 'author', 'pub_year', 'pub_type', 'price') views.py def create_ad(request): if request.method == 'POST': form = AdForm(request.POST) if form.is_valid(): form.save(commit=False) current_user = request.user form.user = current_user form.save() else: form = AdForm() return render(request, 'create_ad.html', {'form': form}) When I try to save the ad I get the following error: **IntegrityError at /createad/ (1048, "Column 'user_id' cannot be null")** I tried inserting via request.user and request.user.id, but it doesn't help. Please help me to solve this problem. -
Trouble Integrating `django-simple-history` with `django-modeltranslation` in Abstract Model
I'm working on a Django project where I'm trying to create an abstract model that provides subclassed models with history tracking using the django-simple-history package. Additionally, I need to integrate django-modeltranslation for translating certain fields. However, I'm encountering issues with the integration. Here's my BaseModel code: from uuid import uuid4 from django.db import models from simple_history.models import HistoricalRecords class BaseModel(models.Model): class Meta: abstract = True history = HistoricalRecords(inherit=True) id = models.UUIDField(primary_key=True, default=uuid4, editable=False) created_at = models.DateTimeField(null=True, blank=True, auto_now_add=True) updated_at = models.DateTimeField(null=True, blank=True, auto_now=True) Now, I have a model TestModel that inherits from BaseModel: models.py class TestModel(BaseModel): text = models.CharField(max_length=100) un = models.IntegerField() new_text = models.CharField(max_length=100) And for translating fields in TestModel, I have the following translation setup: translation.py from modeltranslation.translator import register, TranslationOptions from test_app.models import TestDeleteModel @register(TestModel) class TestModelTranslationOptions(TranslationOptions): fields = ( 'text', 'new_text', ) However, the issue arises when django-simple-history doesn't recognize the translated fields like text_en, resulting in them not being added to the history model. It seems that this occurs because the translation fields are added after the simple history package registers the model and creates the history model. I attempted to register TestModel again with simple_history after the translation registration to address this: translation.py from … -
How to iterate a dict within a template that contains a key named items?
I have some fairly simple django template and part of it is iterating through some dict ( that originates from some parsed json files ) like: {% for k, v in d.items %} However my dict now contains an item called items, which because for the syntax of a.b django first tries to resolve it as a[b] before trying getattr(a,b) (and calling the result if its callable), will try to iterate through the value under that key instead of the dict. What would be a good way to resolve that? I know already I could write a filter that simply returns list(d.items()) but that seems wrong/wasteful to me. Are there some other possibilities to solve this problem?