Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form in template
I was trying to build a form that make the user able to upload a picture from the website to Media\Images folder. i try this but it dosent work models.py from django.db import models # Create your models here. class imgUpscalling(models.Model): Image = models.ImageField(upload_to='images/') forms.py from django import forms from .models import imgUpscalling class ImageForm(forms.ModelForm): class Meta: model = imgUpscalling fields = ('Image',) views.py def img_upscaler(request): context = {'from': ImageForm()} return render(request, "upsc_main.html",context) template.html <h1>Image Upscaler & Enhanced Resolution</h1> <h2>Select the Image</h2> <form method = "post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> can you notify me with the mistakes i did in the code? because the form is not shown in the template. thanks a lot in advance -
How do I properly set PYTHONPATH when invoking the Django Python shell?
I'm using Python 3.9.9 for a Django 3 project. I would like to invoke my Python shell, via "python3 manage.py shell", so I have set these variables ... $ echo $PYTHONSTARTUP /home/myuser/cbapp/shell_startup.py $ echo $PYTHONPATH/myuser /home/myuser/cbapp/ My startup script is very simple ... $ cat /home/myuser/cbapp/shell_startup.py from cbapp.services import * from cbapp.models import * However, when I change to my project directory, activate my virtual environment, and attempt to invoke the shell, I get these errors complaining about not being able to find Django ... $ cd /home/myuser/cbapp $ ./venv/bin/activate $ python3 manage.py shell Traceback (most recent call last): File "/home/myuser/cbapp/manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/myuser/cbapp/manage.py", line 21, in <module> main() File "/home/myuser/cbapp/manage.py", line 12, in main 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? However, Django has already been installed in my virtual environment ... $ ls /home/myuser/cbapp/venv/lib/python3.9/site-packages/django/ apps conf core dispatch http __main__.py __pycache__ template test utils bin contrib db forms __init__.py middleware shortcuts.py … -
Sending Audio file from Django to Vue
I'm trying to send gtts generated audio file from Django to Vue via HttpResponse. Django's views.py: f = open('path/of/mp3/file', 'rb') response = HttpResponse() response.write(f.read()) response['Content-Type'] = 'audio/mp3' response['Content-Length'] = os.path.getsize('path/of/mp3/file') return response and when vue receives the response data, it is like the below: data: '��D�\x00\x11C\x19�\x01F(\x00\x00\x04 �&N�""""���ޓ�������\x7F���B\x10���w�����…���_�F��1B��H���\x16LAME3.100�����������������������' # and so on I guess it is because the bytes have been converted to string over the transfer and I have to convert it back to the audio file. But no matter whether using blob or other suggested methods, I could not convert it to an mp3 file to be played in javascript. How could I achieve this? -
how to fix django login problems
I was working on django project but I could not login into my django app after successful registration(confirmed from admin side). I have added phone number field to registration page, help me fix the login code, i am new to programming help me out please my code looks like this: This is my view.py ````def register_view(request): """Registration view.""" if request.method == 'GET': # executed to render the registration page register_form = UserCreationForm() return render(request, 'netflix/register.html', locals()) else: # executed on registration form submission register_form = UserCreationForm(request.POST) if register_form.is_valid(): User.objects.create( first_name=request.POST.get('firstname'), last_name=request.POST.get('lastname'), email=request.POST.get('email'), phone=request.POST.get('phone'), username=request.POST.get('email'), password=make_password(request.POST.get('password')) ) return HttpResponseRedirect('/login') return render(request, 'netflix/register.html', locals()) def login_view(request): #Login view. if request.method == 'GET': # executed to render the login page login_form = LoginForm() return render(request, 'netflix/login.html', locals()) else: # get user credentials input username = request.POST['email'] password = request.POST['password'] # If the email provided by user exists and match the # password he provided, then we authenticate him. user = authenticate(username=username, password=password) if user is not None: # if the credentials are good, we login the user login(request, user) # then we redirect him to home page return HttpResponseRedirect('/logged_in') # if the credentials are wrong, we redirect him to login and let him … -
How to check Fullcalendar V5 Refetch Events Success / Failure
I was fetching events from the server dynamically for fullcalendar var calendar = new FullCalendar.Calendar(document.getElementById('calendar'), { themeSystem: "bootstrap5", businessHours: false, initialView: "dayGridMonth", editable: true, headerToolbar: { left: "title", center: "dayGridMonth,timeGridWeek,timeGridDay", right: "today prev,next", }, events: { url: '/api/lesson_plans/', method: 'GET', success: function () { eventsLoadSuccess = true; }, failure: function () { eventsLoadSuccess = false; notyf.error('There was an error while fetching plans.'); }, textColor: 'black' }, dateClick: function(plan) { var clickedDate = plan.date; var today = new Date(); // Today's date if (clickedDate >= today) { $('#addPlanModal input[name="start"]').val(moment(clickedDate.toISOString()).format('YYYY-MM-DD HH:mm:ss')); $('#addPlanModal').modal('show'); } }, eventClick: function (plan) { $.ajax({ method: 'GET', data: { plan_id: plan.event.id }, success: function(data) { if (data.form_html) { $('#ediPlanFormContainer').empty(); $('#ediPlanFormContainer').html(data.form_html); $('#editPlanForm #plan_id').val(plan.event.id); initDatePicker(["id_edit_start", "id_edit_end"]); $('#editPlanmodal').modal('show'); } else { notyf.error('Error While Fetching Plan Edit Form.'); console.error('No form HTML found in the response.'); } }, error: function(xhr, textStatus, errorThrown) { console.error('Error:', textStatus, errorThrown); } }); }, eventDrop: function(plan) { updateEvent(plan.event); }, }); calendar.render(); It works properly but on reload events I wanted to check if the reload was successful or not but the refetchevents function doesn't return anything so I was trying to implement my own way but I am stuck now I need some help. $('#reload_plans').click(function () { if … -
I have telegram api to get messages. I want to show all messages on a django web page
Using the code below I am able to get all messages AND THE parts of message ( youtube url ) that need to be shown on web page. It is now required to show this data on a django based web page. Question is where do I start. For data that is coming from telegram, how can it be shown directly on the web page. ? from telethon import TelegramClient, events, sync from telethon.tl.functions.messages import (GetHistoryRequest) from telethon.tl.types import MessageMediaWebPage, WebPage, WebPageEmpty client = TelegramClient(session_name, api_id, api_hash) client.start() channel_entity=client.get_entity(channel_username) posts = client(GetHistoryRequest( peer=channel_entity, limit=100, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0)) for message in client.iter_messages(chat, reverse=True): if type(message.media) == type(None): continue if not type(message.media) == MessageMediaWebPage: continue if type(message.media.webpage) == WebPageEmpty: continue if hasattr(message.media.webpage, 'display_url'): print('+++ display_url ', message.media.webpage.display_url) Can I call a for loop inside the views. Another concern is, every time the page loads it will query data from telegram. And this can take long time. Is their a way to cache data that comes from an api so that subsequent reads are coming from the cache. -
Problems with saving and editing cards, changed/added models and stopped saving/editing cards
Here's what the terminal gives out [03/Oct/2023 16:15:52] "GET /create/?csrfmiddlewaretoken=xgcCZx4x2RjaTeFT5Sn6OBqC3k9VZUBO69tG4zJMiNuVwne9NTX1LXpdRJqn03AZ&original_name=222&author=1&case_category=3&defendant=%D0%9F%D0%B5%D1%82%D1%80%D0%BE%D0%B2&article=200&sides_case=3&preliminary_hearing=20.09.2023 HTTP/1.1" 200 8459 Model class BusinessCard(models.Model): '''7. Модель карточки по делу''' original_name = models.CharField( unique=True, max_length=100, verbose_name='номер дела' ) author = models.ForeignKey( User, models.SET_NULL, blank=True, null=True, related_name='cards', verbose_name='Автор карточки' ) case_category = models.ForeignKey( Category, blank=True, null=True, on_delete=models.SET_NULL, related_name='cards', verbose_name='Категория дела' ) defendant = models.CharField( max_length=150, verbose_name='подсудимый' ) under_arrest = models.BooleanField( verbose_name='под стражей' ) article = models.PositiveSmallIntegerField( verbose_name='Статья УК РФ' ) pub_date = models.DateTimeField( auto_now_add=True, verbose_name='Дата создания/изменения карточки' ) sides_case = models.ManyToManyField( SidesCase, verbose_name='Поля сторон по делу' ) preliminary_hearing = models.DateField( verbose_name='Дата предварительного слушания/(с/з)' ) class Meta: ordering = ('pub_date',) verbose_name = 'Карточка на дело' verbose_name_plural = 'карточка на дело' def __str__(self): return self.original_name views @login_required def card_create(request): '''Шаблон создание карточки''' template = 'create_card.html' form = CardForm(request.POST or None) if form.is_valid(): card = form.save(commit=False) card.author = request.user card.save() form = CardForm() return redirect('business_card:profile', request.user) return render(request, template, {'form': form}) @login_required def card_edit(request, post_id): '''Шаблон редактирования карточки''' card = get_object_or_404( BusinessCard.objects.select_related( 'case_category', 'author'), id=post_id ) if request.user != card.author: return redirect('business_card:business_card_detail', card.pk) form = CardForm(request.POST or None, instance=card) if form.is_valid(): form.save() return redirect('business_card:business_card_detail', card.pk) form = CardForm(instance=card) context = { 'form': form, 'is_edit': True, 'card': card, } return render(request, 'create_card.html', context) forms … -
The most recent rows in for each type/agent in Django
I have a table with lots of data. This table is written by some scripts. It works like a "check in", where each agent is checking in in some period of time. It looks like below. id agent status timestamp 1 tom ok 2023-03-16 12:27:03 2 jeff degraded 2023-08-31 00:01:13 100 tom ok 2023-10-03 12:00:00 101 jeff ok 2023-10-03 11:59:00 I'd like to pick the most fresh line per each agent. So in above example I'd like to get row 100 and 101. I tried many different ways but still not getting what I want. I use MySQL, so distinct is not for me this time. On one hand there is a way to make distinct values per agent, like below: AgentCheckin.objects.all().values('agent').distinct() But it's just a name of an agent. I need to get whole query set with all the information. I think this kind of use case should be somehow common in multiple web apps, but looking here is SO, it's not that common with ultimate answer. -
i am getting "OperationalError at /admin/login/" no such table: auth_user"post docker container deployment
I have created a Django project locally(on a EC2 instance),it was running successfully without any issues. I was getting this error at first, but, then i fixed it using "python manage.py migrate". i containerized it and then pushed the same on the docker hub. i pulled the same image on the another ec2 instance and executed the docker run command. The page got hosted on the current ec2 instance, then, I entered the username and password, then, i got this error. -
How to convert large queryset into dataframes in optimized way?
A django queryset of more than 5 lakhs records when converting into dataframes is getting into OutOfMemory issue. query_data is returning around 6 lakh rows but pandas is unable to process this much data and got stuck. How can we optimize or prevent this. query_data = MyObjects.objects.filter().values() df = pd.DataFrame.from_records(query_data) -
I have python django backend for webscarpping project. As input i give the website name and it scrapes data. But it takes too long time. How to scale?
In my project for 10 websites on 20000 records. It takes too much time to scrape. I have introduced multi-threading for the same. But still i see lot of time consumption. Is there a way i can scale my servers and make it faster ? Currently using multi-threading. But want to know how to scale servers and resolve issue. -
My Fullstack app is having issues after being deployed with Digital Ocean
So I developed fullstack application which has Django for backend and React for frontend. I am using Digital Ocean as host for my Django project and Railway for my React project. Locally everything works perfectlly but once I deployed it, thats where it started giving some errors. I am new to DevOps and deploying projects in general so bear with me. I checked my deploy loggs and everything seems to be in order, my url is also correct, which points to my digital ocean server app and works fine I tested it with postman. To give you an example of the issue , user creates a message and then after its done it redirects him to the home page. Instead of seeing the message on home dashboard, its basically empty. Then when I navigate away and come back to home page message is there, but then when I do navigate away and come back again to home page message is gone. So I have this really weird error which I really dont understand why is it occouring. So I am turning to stackoverflow community for help. Could it be because of plan package that I have on digital ocean? Like … -
Django database function to extract week from date (if week starts on Saturday)
loads_of_dedicated_customers = Load.objects.filter(customer__is_dedicated=True).exclude(load_status='Cancelled').values('customer__name').annotate(year=ExtractYear('drop_date'), week=ExtractWeek('drop_date').annotate( loads_count=Count('id'), sum_revenue = Sum('billable_amount'), sum_miles = Sum('total_miles'), rate_per_mile = ExpressionWrapper(F('sum_revenue') / NullIf(F('sum_miles'), 0), output_field=DecimalField(max_digits=7, decimal_places=2)), ) I have this query that groups by year and week. However, I need the results by week where the week starts on Saturday. Is there a simple way to do this or should I create a week columns in the table and save it there? Thanks! -
Can't edit anything in Django CMS due to cross-origin error
About three months ago, I upgraded our old Django and CMS application to the (then) latest LTS versions (4.2.3 for Django, 3.11.3 for django-cms). After the upgrade, I got the following error when I tried to edit anything from the CMS toolbar or the CMS plugins after a successful login: SecurityError: Blocked a frame with origin "http://localhost:8000" from accessing a cross-origin frame. A short Google search later I was able to fix the issue by setting the CSRF_TRUSTED_ORIGINS in settings.py (depending on the environment). This worked like a charm until a few weeks ago, when suddenly the same error appeared again. This happens on all our environments - including local - despite the fact that nothing new was deployed since the beginning of July '23. First, I tried everything in this guide: https://noumenal.es/notes/til/django/csrf-trusted-origins/ Our staging and production django app is behind a proxy, so I verified that HttpRequest.is_secure() returns True and the X-Forwarded-Proto header is set to https in the production environment. But this happens also on my local machine, where there is no HTTPS. I also verified that the CSRF cookie value and the CSRF token param in requests are, in fact, the same. Then I tried to install … -
How to enable flow.run_local_server() for HTTPs in Django?
My code was working accurate on localhost. But not when I try to host in DigitalOcean Droplet. from __future__ import print_function from googleapiclient.discovery import build from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload from google_auth_oauthlib.flow import InstalledAppFlow from google.oauth2.credentials import Credentials from google.auth.exceptions import RefreshError from google.auth.transport.requests import Request from django.conf import settings from django.shortcuts import redirect import argparse import base64 import io, os import shutil import requests from pebble import concurrent class Drive: SCOPES = ['https://www.googleapis.com/auth/drive'] extensions = {"csv": "text/csv", "mpeg": "video/mpeg"} def __init__(self): self.creds = self.load_credentials() if self.creds is not None: self.service = build('drive', 'v3', credentials=self.creds) else: self.service = None @concurrent.process(timeout=45) def create_process(self): creds = None token_path = 'token.json' if os.path.exists(token_path): creds = Credentials.from_authorized_user_file(token_path, scopes=self.SCOPES) if not creds or not creds.valid: flow = InstalledAppFlow.from_client_secrets_file( settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, self.SCOPES) creds = flow.run_local_server(host="somedomain.com",port=443) with open('token.json', 'w') as token_file: token_file.write(creds.to_json()) # Attempt to refresh the token try: print("refresh") creds.refresh(Request()) except Exception as e: print("Error refreshing token:", str(e)) flow = InstalledAppFlow.from_client_secrets_file( settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, self.SCOPES) creds = flow.run_local_server(host="somedomain.com",port=443) with open('token.json', 'w') as token_file: token_file.write(creds.to_json()) return creds def load_credentials(self): try: process = self.create_process() creds = process.result() # Wait for the process to complete except TimeoutError: creds = None print("Task was canceled due to a timeout.") return creds What I figured … -
Remove duplicate variant in queryset in django
class ProductEntry(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_entries") price = models.DecimalField(max_digits=8, decimal_places=0) quantity = models.PositiveIntegerField(default=0) image = models.ForeignKey(Image, on_delete=models.PROTECT, related_name="product_entries", blank=True, null=True) variants = models.ManyToManyField(Variant) inventory_management = models.BooleanField(default=True) def get_variants(self): print(self.variants.values()) get_variants return bottom resut: <QuerySet [{'id': 3, 'name': 'Red', 'image_id': None, 'color': '#C80000FF', 'category': 'C'}, {'id': 1, 'name': 'Black', 'image_id': None, 'color': '#1F1F1FFF', 'category': 'C'}]> <QuerySet [{'id': 2, 'name': 'Purple', 'image_id': None, 'color': '#2D1952FF', 'category': 'C'}]> <QuerySet [{'id': 3, 'name': 'Red', 'image_id': None, 'color': '#C80000FF', 'category': 'C'}]> <QuerySet [{'id': 4, 'name': 'Green', 'image_id': None, 'color': '#009812FF', 'category': 'C'}]> As a result, red color has been repeated twice, I want to delete one of them self.variants.values().distinct("name") -
Django project not running after I have updated the python version of the system
I had created a django project a couple of months ago. Now I wanted to do a new project and updated the python version of my system and the privious project is not working. This project was created by using virtualenv. I am new at django and don't understand what is the problem. I thought that virtual environment is supposed to create an isolated environment for a project with all the necessary dependencies. Please help me with this and thank you in advance. It shows this error. enter image description here 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? -
Scheduled task on Django with Windows Server
I have a Django project that must be run on Windows Server machine. I can't install any additional software such as RabbitMQ or Docker. Only pip modules are available. As far as I know Celery can't work on windows. Is there a way to implement scheduled tasks in my Django project working in such an environment? -
Hand user instance to ModelForm in Admin
I want to access the currently logged in user, show the username, but make it unchangeable: models.py: class Comment(models.Model): desc = models.TextField(max_length=512) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=CASCADE) class Meta: abstract = True class Status(Comment): icon = TextField(blank=True) admin.py: class StatusAdminForm(forms.ModelForm): image_file = forms.ImageField(required=False, label="Icon") def __init__(self, *args, user, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean_image_file(self): cleaned_data = super().clean() ... return cleaned_data def clean(self): cleaned_data = super().clean() cleaned_data["user"] == self.user if "image_file" in self.changed_data: self.instance.icon = self.cleaned_data["image"] return cleaned_data class StatusAdmin(admin.ModelAdmin): list_display = ("get_icon", "created", "updated", "user") def get_form(self, request, *args, **kwargs): form = StatusAdminForm(request.POST, request.FILES, user = request.user) return form def get_icon(self, obj): return format_html("""<img src="{obj.icon}" """>) so what I want is to show the user as readonly field in the StatusAdminForm. But I get the error: form = ModelForm(request.POST, request.FILES, instance=obj) TypeError: 'StatusAdminForm' object is not callable. -
Duplicate entry error in ManyToManyField in Django model
Duplicate entry error in ManyToManyField in django model. We are using unique_together option in Meta class but that not associated with this field. This is my model:- class Staff(models.Model): name = models.CharField(max_length=50) shortname = models.CharField(max_length=50) email = models.CharField(max_length=50) phone = models.CharField(max_length=15) merchant = models.ForeignKey(Merchant, on_delete=models.CASCADE, related_name='merchant_staff') stores = models.ManyToManyField(Location, null=True, blank=True) pin = models.PositiveIntegerField(validators=[MinValueValidator(1000), MaxValueValidator(9999)]) is_active = models.BooleanField(default=True) class Meta: unique_together = (('pin', 'merchant'), ('shortname', 'merchant'),) this is my error:- duplicate key value violates unique constraint "merchants_staff__staff_id_locatio_2fb867d4_uniq" -
Not able to display validation error messages properly
I am using messages class offered by Django to display error message on top of the form with a red background as you can see below, <div class="w3-row w3-container" style="width: auto; margin-left: 5%; margin-top: 2%; margin-right: 5%;"> <div class="w3-half" style="width: 60%;"> <p> Sign Up </p> </div> <div class="w3-half w3-center w3-border w3-round w3-border-black" style="width: 40%;"> <div class="w3-card-4 w3-border w3-border-black w3-pale-blue" > <h4> Registration Form</h4> </div> <form method="post" action=""> {% if messages %} <ul class="messages w3-red"> {% for message in messages %} <li> {{ message }} </li> {% endfor %} </ul> {% endif %} {% csrf_token %} {{form.as_p}} <input type="submit" class="w3-button w3-black w3-round w3-hover-red" value="Register" style="margin-left: 25px;"> </form> <p> Already signed up? Please <a href="{% url 'user_login' %}" > Login </a> </p> </div> </div> In the below views.py I am doing some validations, the problem I am facing is the messages are not getting displayed on top of the form with red background. Instead they are getting displayed above each of the input field with no background color form = MyUserCreationForm() user = User() if request.method == "POST": form = MyUserCreationForm(request.POST) if form.is_valid(): #user = form.save(commit=False) user.first_name = request.POST.get('first_name') user.last_name = request.POST.get('last_name') user.username = request.POST.get('username').lower() user.email = request.POST.get('email').lower() password1 = request.POST.get('password1') password2 … -
403 Forbidden Error when sending POST request in React+Django project
I am trying to make a website and I am in the process of integrating the React frontend into the Django backend. I am trying to send a post request from my frontend into the backend. If I run my frontend and backend separate on ports 3000 and 8000, I dont get an error, my request goes trough. But with them running on the same port (7000), I get the 403 forbidden error. Here is part my frontend: const handleSubmit = async (formData) => { try { const response = await axios.post('http://127.0.0.1:7000/backend/api/create_message/', formData); console.log('Message sent successfully:', response.data); } catch (error) { console.error('Error sending message:', error); } }; Here is my views.py: @api_view(['POST', 'GET']) def create_message(request): if request.method == 'POST': serializer = MessageSerializer(data=request.data) if serializer.is_valid(): serializer.save() # Send mail name = request.POST.get('name') phone = request.POST.get('phone') email = request.POST.get('email') message = request.POST.get('message') subject = "Contact Form" content = f"Name: {name} \n" \ f"Phone: {phone}\n" \ f"Email: {email}\n" \ f"Message: {message}" from_mail = settings.EMAIL_HOST_USER recipient_list = ['email'] send_mail(subject, content, from_mail, recipient_list, fail_silently=False) messages.success(request, "Message successfully sent", extra_tags='success') form = MessageForm() context = {'form': form} template = '../templates/lpadj/message_form.html' return render(request, template, context) messages.warning(request, "Message not sent", extra_tags='warning') form = MessageForm() context = {'form': form} … -
Secure_ssl_redirect not working in django
I am trying to redirect my django application which was running previously in http:// to https:// In settings.py file. I added SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER =( 'HTTP_X_FORWARDED_PROTO','https') ``` Still it didn't redirect or show any error.i tried without secure_proxy_ssl_heade, it didn't work -
IIS server django.core.exceptions.ImproperlyConfigured
I am trying to deploy my django project on windows IIS server using wfastcgi. This project contains multiple apps and post completion of all the steps mentioned when i try to open the url it gives me following error. Thanks in Advance!! File "C:\Python38\Lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "C:\Python38\Lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "C:\Python38\Lib\site-packages\wfastcgi.py", line 605, in get_wsgi_handler handler = handler() File "C:\Python38\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "C:\Python38\lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python38\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Python38\lib\site-packages\django\apps\config.py", line 222, in create return app_config_class(app_name, app_module) File "C:\Python38\lib\site-packages\django\apps\config.py", line 47, in init self.path = self._path_from_module(app_module) File "C:\Python38\lib\site-packages\django\apps\config.py", line 86, in _path_from_module raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: The app module <module 'OnboardingApp' (namespace)> has multiple filesystem locations (['D:\RPA\CoreRPA_Webapp\OnboardingApp', 'D:\RPA\CoreRPA_Webapp\.\OnboardingApp']); you must configure this app with an AppConfig subclass with a 'path' class attribute. -
Creating forms in Django with multiple Many-to-Many fields in Models
I have these three models with two many to many fields in BlogPost models like class Category(models.Model): name = models.CharField(max_length=150) def __str__(self) -> str: return self.name class Tag(models.Model): name = models.CharField(max_length=150) def __str__(self) -> str: return self.name class BlogPost(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User , on_delete=models.CASCADE) categories = models.ManyToManyField(Category) tags = models.ManyToManyField(Tag) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title and form on client side as follow {% extends 'blog_project/base.html' %} {% load widget_tweaks %} {% block content %} <div class='login-container'> <h2 class='login-heading'> Create New Post </h2> <form class='login-form' method='post'> {% csrf_token %} {% for field in form.visible_fields %} <div class="form-group pb-3"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {{ field|add_class:'form-control' }} {% for error in field.errors %} <span class="help-block">{{ error }}</span> {% endfor %} </div> {% endfor %} <div class='form-group'> <button type = 'submit'>Post</button> <a href="{% url 'blog:blog_list' %}">Go Back</a> </div> </form> </div> {% endblock%} it allows me to select from the existing categories but not allows to add other categories. I want to create a form in django that allows a user to select from the categories on client side as well as create new categories or tags and save them to the …