Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ckeditor styles not applying with my tailwind website
from django.db import models from ckeditor.fields import RichTextField class Project(models.Model): category = models.ForeignKey(ProjectCategory, on_delete=models.CASCADE) client = models.CharField(max_length=100) title = models.CharField(max_length=100) description = RichTextField(null=True) pdf = models.FileField(null=True, blank=True) def __str__(self): return self.title I am using tailwind css in my frontend and i am displaying the project description {{project.description}} but the styles i have added why i filled the description with ckeditor didn't apply when i displayed the description in my tailwind frontend how to fix that?? -
Why HTML Registration Form Data is not Received in django
I have below configurations of demo\urls.py, user\urls.py, views.py & HTML Form. Still when I press the submit button of HTML Form it says File Not Found. Taking help from ChatGPT which provided two Solutions as mentioned in attached file, even then I am getting Error. What to do demo\urls.py urlpatterns = [ path('admin/', admin.site.urls), path('user', views.register), ] user\urls.py urlpatterns = [ path('register', views.register), ] views.py def register(request): if request.method == 'POST': name = request.POST.get("name") email = request.POST.get("email") password = request.POST.get("password") created_at = request.POST.get("created_at") updated_at = request.POST.get("updated_at") I have following code in HTML Form ``` {% csrf_token %} ``` <label for="name">Name:</label><br> ``` <input name="name" type="text" id="name" name="name"><br> ``` <label for="email">Email:</label><br> ``` <input name="email" type="email" id="email" name="email"><br> ``` <label for="password">Password:</label><br> ``` <input name="password" type="password" id="password" name="password"><br> ``` <script> ``` // Generate current datetime for Hidden fields ``` var current_datetime = new Date().toISOString(); ``` document.getElementById('current_datetime').value = current_datetime; ``` </script> ``` <!-- Hidden fields for created_at and updated_at --> ``` <input type="hidden" name="created_at" value="{{ current_datetime }}"> ``` <input type="hidden" name="updated_at" value="{{ current_datetime }}"> ``` <button type="submit">Register</button> ```</form> ```</body> ```</html> When I press the submit button of HTML Form it says File Not Found. What is the Error & how to fix it I had … -
nginx for development server or connect manage.py runserver from local network
I have development environment (on mac) and access from the android in the same local network. For example my Mac IP is 192.168.0.5,then connecting from android http://192.168.0.5/ Now I have two choices uwsgi and python manage.py runserver When using uwsgi, I need to restart uwsgi for reflecting the code change. When using python manage.py runserver, It doesn't connected from the android. Is there a way to solve this? -
Error with PgBouncer on Heroku with Django and Docker
I'm currently running into database connection issues with my Django & Postgres app hosted on Heroku. Before upgrading my database plan, I wanted to try solving the issue with pgbouncer. According to this article by Heroku, the Procfile would need to be updated from something like web: gunicorn hellodjango.wsgi to web: bin/start-pgbouncer-stunnel gunicorn hellodjango.wsgi after provisioning the pgbouncer buildpack. The thing is, I don't use a Procfile but a heroku.yml. Currently, my yml file has this: run: web: command: - gunicorn --bind 0.0.0.0:$PORT --workers 1 --threads 8 --timeout 0 my_app.asgi:application -k uvicorn.workers.UvicornWorker I tried updating the web command to this: bin/start-pgbouncer-stunnel gunicorn --bind 0.0.0.0:$PORT --workers 1 --threads 8 --timeout 0 my_app.asgi:application -k uvicorn.workers.UvicornWorker but that gives me this error: bin/start-pgbouncer-stunnel: not found I tried this answer as well, but get an pgbouncer: unrecognized service error. Any ideas on how to solve this? -
Django doesnt update the translation
I am trying to add Translation to russian from english I tried clearing the cache, deleting locale folder, changing the translation. it all doesnt work #: core/templates/core/layout.html:59 core/templates/core/layout.html:112 msgid "Home" msgstr "Главная" But it displays "Начало" instead of "Главная". my settings.py: LANGUAGE_CODE = 'en' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = ( ("en", ('English')), ("ru", ('Russian')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale/'), ) -
Django test suite throws error on field that's not loaded: "could not convert string to float"
The following simple test throws the errors ValueError: could not convert string to float: '' The above exception was the direct cause of the following exception: ValueError: Field 'amount' expected a number but got ''. from django.test import TestCase from .models import Customer class TestSetup(TestCase): def setUp(self): self.testCustomer = Customer(firstname='Ron', street_name='Somestreet', street_suffix='Dr', street_number='1', phone='111-111-1111', city='Somecity', zipcode='87000') The field 'amount' does exist, but in a model that isn't loaded for any tests: class Appointment(models.Model): amount = models.FloatField(blank=True, default=0.0) But just in case it's instantiating that model in the process of creating the test database, I migrated "default=0.0" to "default='0.0' " (Single quotes around the value). Same error. I'm initiating the test with python manage.py test from the project directory. -
Django form is invalid and not submitting?
I have four main parts: The BaseJournal form, The JournalTemplate form, a model Journal and amy view which handles it. Here is the Journal Model: class Journal(models.Model): MOOD_CHOICES = [ ('happy', 'happy.png'), ('angry', 'angry.png'), ('neutral', 'neutral.png'), ('sad', 'sad.png'), ] user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) date = models.DateField(auto_now_add=True, editable=False) title = models.CharField(blank=False, max_length=50, default="default title") mood = models.CharField(max_length=20, choices=MOOD_CHOICES, default='neutral') custom_fields = JSONField(default=dict) field_order = JSONField(default=list) @property def attached_files(self): return AttachedFile.objects.filter(journal=self) Here is BaseJournal form: class BaseJournalForm(forms.ModelForm): def __init__(self, user=None, **kwargs): super().__init__(**kwargs) self.fields['mood'].label = '' files = MultipleFileField(required=False) class Meta: model = Journal fields = ['title', 'files', 'mood'] widgets = { "mood": forms.HiddenInput(), "files": MultipleFileInput(), } Here is my Journal Template form: class JournalEntryForm(BaseJournalForm): template = forms.ModelChoiceField( queryset=JournalTemplate.objects.all(), empty_label='No Template', # Set the placeholder text required=False, widget=forms.Select(attrs={'class': 'form-control'}) ) num_questions = forms.IntegerField(label='Number of Questions', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0) num_feelings = forms.IntegerField(label='Number of Feelings', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0) num_subheadings = forms.IntegerField(label='Number of Subheadings', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0) num_events = forms.IntegerField(label='Number of Events', required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}), min_value=0) template_name = forms.CharField(label='Template Name', required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = Journal fields = BaseJournalForm.Meta.fields + ['template', 'num_questions', 'num_feelings', 'num_subheadings', 'num_events', 'template_name'] Here is my view which handles the form: def create_journal_entry(request): templates = JournalTemplate.objects.all() … -
Django's update_or_create failing although kwargs is specified
I have the following Django model: class Itens(models.Model): id = models.AutoField(primary_key=True) itempr_id = models.IntegerField(unique=True) # This is NOT a relationship cod_item = models.CharField(max_length=16, unique=True) # Other fields... As you can see, both itempr_id and cod_item are unique, so I specified update_and_create to take this into account: class CreateItensSerializer(serializers.ModelSerializer): class Meta: model = Itens fields = '__all__' def create(self, validated_data): item, created = Itens.objects.update_or_create( itempr_id=validated_data.get('itempr_id'), cod_item=validated_data.get('cod_item'), defaults=validated_data ) return item I call and save the serializer like this: serializer = CreateItensSerializer(data=itens, many=True) if serializer.is_valid(): serializer.save() However, whenever there is a duplicate, I get the following error: {'itempr_id': [ErrorDetail(string='itens with this itempr id already exists.', code='unique')], 'cod_item': [ErrorDetail(string='itens with this cod item already exists.', code='unique')]} I do not expect any uniqueness violation problems since the fields were already specified to be unique in the function call How can I fix this? EDIT: just to make it clear, this works if the DB's table is empty, there's no problem in the itens argument in serializer = CreateItensSerializer(data=itens, many=True) -
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 …