Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
App using Django runs server only once after cloning
I cloned a private GitHub repository that was created using Django into visual studio code and set it up the following way: Open project in visual studio code, there open the project's terminal Create a virtual environment using python -m venv .\venv Active that virtual environment using venv\scripts\activate Import all packages from requirements.txt individually. Since pip freeze -r requirements.txt was giving me an error, I installed each package using pip install packageName Check all models migrated to database with python manage.py makemigrations followed by python manage.py migrate Start server using python manage.py runserver At this point I clicked the local host link and it runs well but after I close the server and try to open it again I first get the error ModuleNotFoundError: No module named 'pymysql'. Then when I do pip install pymysql I get the errors: ModuleNotFoundError: No module named 'rest_framework' OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' After I try and fix the first one by using pip to install rest_framework I only get the same error three times consecutively: Winerror [10061]: No connection could be made because the target machine actively refused it. At this point, I … -
How to solve "FileNotFoundError: [Errno 2] No such file or directory: '/code/static" when deploying a django app to heroku?
I was reading William S. Vincent's book Django for Professionals book, and I tried to deploy a django app to heroku, but static folder location fails while deploying this app, i am using Docker and whitenoise package for handling the static files, here important information in files. settings.py import dj_database_url import socket from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Este cambio es para el despliegue en heroku, ya que hay problemas con los archivos estáticos # para más información vea: https://devcenter.heroku.com/articles/django-assets #BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # El entorno, producción vs desarrollo ENVIRONMENT = os.environ.get('ENVIRONMENT', default='production') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! # por defecto 0, ya que el proyecto estará pronto en producción DEBUG = int(os.environ.get('DEBUG', default=0)) ALLOWED_HOSTS = ['aplicacion-de-ventas.herokuapp.com', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.sites', # 3rd party 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.github', 'allauth.socialaccount.providers.google', 'debug_toolbar', # local apps 'pages.apps.PagesConfig', 'ventas.apps.VentasConfig', 'perfiles.apps.PerfilesConfig', ] MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', … -
docker-compose not creating app for django backend
I am not sure why im not able to serve my django app that i am building with Docker and React. So far I am only at the django level (backend) and its not working. I have the following structure: project (main folder) | |__ docker-compose.yml |__ .env (where i store all the custom database name, user and password) > backend > university | |__ Dockerfile |__ requirements.txt |__ manage.py > frontend I havent connected the front end yet. here my configuration of the Dockerfile of the backend FROM python:3.8 ENV PYTHONUNBUFFERED 1 WORKDIR /app/backend/ COPY requirements.txt /app/backend/ RUN pip install -r requirements.txt COPY . /app/backend and the docker-compose of the main project version: '3.7' services: web: build: ./back_end/university restart: unless-stopped command: python /app/backend/manage.py runserver 0.0.0.0:8000 volumes: - .:/app/backend ports: - 8000:8000 depends_on: - db db: image: postgres:11 restart: always environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '${DB_NAME}', 'USER': '${DB_USER}', 'PASSWORD': '${DB_PASSWORD}', 'HOST': 'db', 'PORT': 5432 } } so when i run docker-compose up -d --build it does build everything but im not able to serve runserver and see the regular django app on port 8000 … -
Static Files Not Loading Django
I am following a tutorial, and I copied the repo, Add for some reason, the static files will not load. This is my folder structure involves having my templates file in my main app and my static files are outside this folder. In the main folder (Django-ecommerce) sitting where my main app is. P.S I have tried moving my static folder into my main app folder but it still does not work. here is my settings.py import os ENVIRONMENT = os.getenv('ENVIRONMENT', 'development') DEBUG = False BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '-05sgp9!deq=q1nltm@^^2cc+v29i(tyybv3v2t77qi66czazj' ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'crispy_forms', 'django_countries', 'core' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware' ] ROOT_URLCONF = 'demo.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ 'templates' ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # static files (CSS, JS, Image) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, '/static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root') DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, … -
Why am I having this Heroku deploying problem?
I have a Django app to be deployed using Heroku, but something went wrong: Processing /tmp/build/80754af9/asgiref_1594338739818/work ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/tmp/build/80754af9/asgiref_1594338739818/work' Below, my requirements.txt file: asgiref==3.2.10 astroid==2.4.2 certifi==2020.6.20 colorama==0.4.3 dj-database-url==0.5.0 Django==3.0.3 django-heroku==0.3.1 django-widget-tweaks==1.4.5 gunicorn==20.0.4 isort==4.3.21 lazy-object-proxy==1.4.3 mccabe==0.6.1 olefile==0.46 pillow==7.2.0 psycopg2==2.8.5 pylint==2.5.3 python-decouple==3.3 pytz==2020.1 six==1.15.0 sqlparse==0.3.1 toml==0.10.1 whitenoise==5.2.0 wincertstore==0.2 wrapt==1.11.2 I've connected Heroku to a Github repository. Do you have any idea what's happening ? -
I'm trying to build an app using Django framework
localhost showing 'TemplateDoesNotExist' especially when i add path('', include('proapp2.urls')), to the settings.py of the project folder. but as soon as i remove path('', include('proapp2.urls')), the Django homepage start showing. -
Django: annotate ranking from related objects
the models: class Competition(TimeStampedModel): name = models.CharField(max_length=255) class Playlist(TimeStampedModel): competition = models.OneToOneField(Competition, on_delete=models.CASCADE, related_name='playlist') class Entry(TimeStampedModel): title = models.CharField(max_length=255) by = models.CharField(max_length=255) class Vote(TimeStampedModel): entry = models.ForeignKey(Entry, on_delete=models.CASCADE, related_name="votes") score = models.IntegerField(validators=[validate_vote_value]) class PlaylistEntry(TimeStampedModel): playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE, related_name='entries') entry = models.ForeignKey(Entry, on_delete=models.CASCADE, related_name='playlistentries') A Competition has one playlist. A Competition playlist has many PlaylistEntry. A PlaylistEntry is one Entry. One Entry can have multiple Vote. What I was able to achieve: Votes for entries counted. What I need to achieve: Ranking for each Playlist. The code I am using now: def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx["compos"] = Playlist.objects \ .filter(competition__hidden_in_results=False) \ .prefetch_related( Prefetch( "entries", PlaylistEntry.objects .select_related("entry") .annotate(score=Sum("entry__votes__score")) .annotate(rank=Window(expression=Rank(), order_by=F('score').desc())) .annotate(overall_rank=Window(expression=Rank(), order_by=F('score').desc())) .all(), to_attr="compo_entries" )) \ .select_related("competition") \ .order_by("competition__results_play_order") return ctx This gives me Sum of votes for each Entry as I want. It also gives me a ranking as a total in all PlayList. I would need a ranking per Playlist Current output: Playlist Item 1 Rank Overall Score 113. 113. 196 124. 124. 178 Playlist Item 2 Rank Overall Score 56. 56. 336 62. 62. 323 What I would like: Playlist Item 1 Rank Overall Score 1. 113. 196 2. 124. 178 Playlist Item 2 Rank Overall … -
widget attrs with self.helper.layout
I'm trying to use in form this forms: class RequestCreateForm(forms.ModelForm): class Meta: model = Request fields = [ 'supplier', 'status', 'requester', 'Procurement', 'comments', ] widgets = { 'supplier': forms.Select(attrs={ 'class': 'form-group col-md-4 mb-0', }), 'Procurement': forms.Select(attrs={ 'class': 'form-group col-md-4 mb-0', }), 'status': forms.Select(attrs={ 'class': 'form-group col-md-4 mb-0', }), 'comments': forms.TextInput(attrs={ 'class': 'form-group col-md-4 mb-0', 'placeholder': 'Enter comment to be print with PO'}), } def __init__(self, *args, **kwargs): super(RequestCreateForm, self).__init__(*args, **kwargs) self.fields['comments', 'Procurement'].required = False self.fields['requester','status'].widget.attrs['readonly'] = True self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Row( Column('supplier', ), Column('status', ), ), Row( Column('Procurement', ), Column('comments', ), ), ) DetailRequestFormSet = inlineformset_factory( Request, RequestDetails, fields=('item', 'typeItem', 'skuinterne', 'skusupplier', 'uomm', 'qty', 'PU', ), extra=3, can_order=True ) but it seems that my template: {% extends "base.html" %} {% load crispy_forms_tags %} {% load tailwind_filters %} {% block content %} <div class="container mx-auto flex flex-wrap"> <div class="w-full mb-6 py-6 flex justify-between items-center border-b border-gray-200"> <div><h3 class="text-2xl text-gray-800">New Request</h3></div> <div><a class="hover:text-blue-500" href="{% url 'items:item_list' %}">Go back to request</a></div> </div> </div> <form method="post"> {% csrf_token %} {% crispy request %} {% for form in requestdetails %} <div class="link-formset"> {% crispy form %} </div> {% endfor %} </form> {% endblock content %} my views: def requestcreateview(request): … -
How can I create unique javascript variable names in a django template for loop?
I am using a django template to loop through hp_tracker objects. Each hp_tracker has its own js code which is used for changing the value via ajax. I'm almost certain I should have this code in the .js file but I was having trouble finding a way to uniquely select each hp_tracker without access to the django template variables in the .js file. So...I moved the js to the html template itself. I am aware this undoubtedly has massive security implications, and I'm open to discussing those as well. Anyway, on to my question. My js fails because I have global variables(!) declared that are not unique. They are being used to control some counters and a setTimeout and I don't see how to now use them to do what I want to do. So the for loop tries to re-declare the same variable over and over. Throughout the rest of the script I'm using JQuery which is perfectly happy to use the django variable {{ hp_tracker.id }}, but javascript is not because "-" characters, which are in the object IDs are not allowed in variable names. What the heck should I do here to fix this hot mess. Is … -
Django as socket.io client
I'm trying to setup a system composed by two servers. One remote express.js api with a socket.io server and a local django one as a socket.io client. For my purpose I want to exchange data frequently between the systems. The problem is that I can't figure out how to integrate a socket.io client with django. I can do it in plain python thanks to the python-socketio package with no problems but integrating it with the framework is tricky. Basically the socket.io client scripts needs to run at django startup and terminate with the server. From what I have understand celery isn't a solution in my case. The socket needs to have access to django database and models system Does anyone have a clean way to implement this? -
Django post operation "violates not-null constraint"
My forms.py: class ReviewForm(ModelForm): class Meta: model = Review fields = ['review_text'] My models.py: class Review(models.Model): reviewer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') review_text = models.TextField(max_length=100000) created_time = models.DateTimeField() def __str__(self): return self.question_text def was_published_recently(self): return self.created_time >= timezone.now() - datetime.timedelta(days=1) My views.py: class IndexView(generic.ListView): template_name = 'review/index.html' context_object_name = 'reviews' def get_queryset(self): return Review.objects.order_by('-created_time')[:5] def create(request): if request.method == 'POST': form = ReviewForm(request.POST) if user_form.is_valid(): form.save() return redirect('review:index') else: pass form = ReviewForm() context = { 'form': form, } return render(request,'review/create.html', context) When I create a post, the error message says I'm violating the non-null constraint for "created_time." The message show 1 for id, dfkjdslafd for review_text, and null for created_time and null for reviewer_id. The data is not saved in the database. When I add the following to the forms.py fields = ['id', 'review_text', 'created_time', 'reviewer_id'] The whole app doesn't run, saying 'django.core.exceptions.FieldError: Unknown field(s) (reviewer_id) specified for Review' in the terminal. I am new to django from rails. Finding simple CRUD much more cumbersome with django -- I must be doing something wrong. I'd appreciate any help. -
GroupConcat works in Django 2.x. In Django 3.1 throws "Cannot resolve expression type, unknown output_field"
I have this query to PostgreSQL working in Django 2.2.x and Python 3.5: qs = Things.objects.filter( id__in=distinct_ids ).values('thing_id').annotate( thing_names_concat=Coalesce(GroupConcat('name', '|'), Value('')), subthings_count=Coalesce(Count('subthing',), Value(0)), friends_count=Coalesce(Count('subthing__friends', distinct=True), Value(0)), friend_ids=ArrayAgg('subthing__friends__id'), ) return qs which references: class GroupConcat(Aggregate): function = 'GROUP_CONCAT' template = '%(function)s(%(expressions)s)' def __init__(self, expression, delimiter, **extra): output_field = extra.pop('output_field', CharField()) delimiter = Value(delimiter) super(GroupConcat, self).__init__( expression, delimiter, output_field=output_field, **extra) def as_postgresql(self, compiler, connection): self.function = 'STRING_AGG' return super(GroupConcat, self).as_sql(compiler, connection) Under Django 3.1 & python 3.8, I get this error on the GroupConcat: django.core.exceptions.FieldError: Cannot resolve expression type, unknown output_field Here's a full stack trace: File "/usr/local/lib/python3.8/dist-packages/rest_framework/test.py", line 288, in get response = super().get(path, data=data, **extra) File "/usr/local/lib/python3.8/dist-packages/rest_framework/test.py", line 205, in get return self.generic('GET', path, **r) File "/usr/local/lib/python3.8/dist-packages/rest_framework/test.py", line 233, in generic return super().generic( File "/usr/local/lib/python3.8/dist-packages/django/test/client.py", line 470, in generic return self.request(**r) File "/usr/local/lib/python3.8/dist-packages/rest_framework/test.py", line 285, in request return super().request(**kwargs) File "/usr/local/lib/python3.8/dist-packages/rest_framework/test.py", line 237, in request request = super().request(**kwargs) File "/usr/local/lib/python3.8/dist-packages/django/test/client.py", line 716, in request self.check_exception(response) File "/usr/local/lib/python3.8/dist-packages/django/test/client.py", line 577, in check_exception raise exc_value File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.8/dist-packages/django/views/decorators/vary.py", line 20, in inner_func response = func(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return … -
ascending=True not working in django-mptt
Hi good day I'm currently following Django-MPTT documentation and I have a problem using ascending=True. Here's my code: views.py def show_genres(request): Try01 = Genre.objects.filter(name="Rock") context = {'genres': Genre.objects.all(), 'sample_ancestor': Try01.get_ancestors(ascending=True, include_self=True)} return render(request, "sampletemp/startup.html", context) when I'm using ascending=True an error occurs saying: Exception Value: get_queryset_ancestors() got an unexpected keyword argument 'ascending' How can I fix it. Thank you in advance! -
Django Admin OneToMany relationship with search field
I'm using Django 3.1.5. If I have a OneToMany relationship, into Django Admin I will have a select with all possible related models. Is there a way to have this select with a search or it's necessary to implement this from scratch? -
Context with filtering for daterange is not working
I am having a view that is working and properly returning results as long as I am not filtering for dates. As soon as I start to add a filter e.g. booking_time__range = (start_date, end_date) no results are returned in my template. I have no tried to find the error by myself for several days, now I need the wisdom of the crowd. My Model: from django.db import models from django.utils import timezone from users.models import Account from organization.models import Organization, Office class Booking(models.Model): LOCATION_OPTIONS = ( ('H', 'Home Office'), ('O', 'Office'), ('N', 'Not indicated'), ) account = models.ForeignKey(Account, on_delete=models.CASCADE) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) office = models.ForeignKey(Office, on_delete=models.CASCADE) booking_time = models.DateTimeField(default=timezone.now) location = models.CharField(max_length=1, choices=LOCATION_OPTIONS) class Meta: unique_together = ('account', 'booking_time',) My View: def overview_view(request): context = {} if request.method == 'GET': start_date = None end_date = None if request.is_ajax(): booking_times = request.GET.get('day') start_date = datetime.strptime(booking_times, "%Y-%m-%d") end_date = start_date + timedelta(days=4) start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.utc) end_date = end_date.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.utc) context['bookings']=Booking.objects.filter( Q(organization_id=request.user.organization_id), Q(booking_time__range = (start_date, end_date)) context['office'] = Office.objects.filter(organization_id__exact=request.user.organization_id) return render(request, 'overview/overview.html', context) return render(request, 'overview/overview.html', context) Both start_date and end_date are datetime.datetime format. As soon as I remove Q(booking_time__range = (start_date, end_date) results … -
Ajax For HTML Generated From Javascript
i have html being generated from javascript to create a list of items. I also need to call a jquery ajax call on each of those items but since it isn't in the html from the page ready i think that might be why the ajax isn't called. when i click the submit button it tries to refresh the page so this shows that the prevent default isn't being run. What am i doing wrong here? Javascript that generates html: buildCollectionList() function buildCollectionList(){ var url = 'http://localhost:8000/api/collection_items_list/' fetch(url) .then((resp) => resp.json()) .then(function(data){ for (var x in data){ var wrapper = document.getElementById(`collection_scroll${data[x].post}`) var product = wrapper.getAttribute('name') //console.log(product) wrapper.innerHTML = '' /*fetch(url) .then((resp) => resp.json()) .then(function(data){ console.log('Data:', data)*/ var list = data for (var i in list){ if ((list[i].saved == true) && (list[i].post == product)){ var item = ` <div class="collection_save_container"> <div class="collection_save_name">${list[i].parent_collection_name}</div> <form class="collection_save_form" action="" method="POST" id="${list[i].collection}" name="${list[i].post}"> <button type="submit" class="collection_save_btn saved" id="save_btn ${list[i].collection} ${list[i].post}"><div class="saved_text ${list[i].collection}">Saved</div></button> </form> </div> </div> ` wrapper.innerHTML += item } else if (list[i].post == product){ var item = ` <div class="collection_save_container"> <div class="collection_save_name">${list[i].parent_collection_name}</div> <form class="collection_save_form" action="" method="POST" id="${list[i].collection}" name="${list[i].post}"> <button type="submit" class="collection_save_btn" id="save_btn ${list[i].collection} ${list[i].post}"><div class="saved_text ${list[i].collection}">Save</div></button> </form> </div> </div> ` wrapper.innerHTML += item } } … -
AttributeError at /login/ 'UserProfile' object has no attribute 'find'
So I am getting this error every time I have created an account and try to login with that account. I am following this tutorial but with my custom template from w3layouts. When I run the code of the guy whose tutorial I am following, I receive the same error on his end. Below Is the ERROR I keep getting. File "C:\Django-E-Commerce\user\views.py", line 37, in login_form request.session[translation.LANGUAGE_SESSION_KEY] = userprofile.language.code AttributeError: 'NoneType' object has no attribute 'code' And here is the code I have on my Views.py @login_required(login_url='/login') # Check login def index(request): category = Category.objects.all() current_user = request.user # Access User Session information profile = UserProfile.objects.get(user_id=current_user.id) context = {'category': category, 'profile':profile} return render(request,'user_profile.html',context) def login_form(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) current_user =request.user userprofile=UserProfile.objects.get(user_id=current_user.id) request.session['userimage'] = userprofile.image.url #*** Multi Langugae request.session[translation.LANGUAGE_SESSION_KEY] = userprofile.language.code # request.session['currency'] = userprofile.currency.code translation.activate(userprofile.language.code) # Redirect to a success page. return HttpResponseRedirect('/'+userprofile.language.code) else: messages.warning(request,"Login Error !! Username or Password is incorrect") return HttpResponseRedirect('/login') # Return an 'invalid login' error message. category = Category.objects.all() context = {'category': category } return render(request, 'login_form.html',context) And Last bUT nOT LEAST. Here is my login.html … -
How to have both author and participants in a model
Currently I have a post model in my models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author") participants = models.ManyToManyField(User) quiet_tag = models.BooleanField("Quiet") camera_tag = models.BooleanField("Camera On") def __str__(self): return self.title def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.pk}) I want to be able to have the functionaliy where a participant can request to join an author's post if the author accepts their request. Currently my model class is adding every single user to the post. Any idea would help a lot! thanks! -
How to resolve django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS error. DUPLICATED, but none of the answers worked for me
I am new to Django and I am getting this error when I try to run python3 poppulate_first_app.py file (using Kali Linux and venv with django 3.1.7). Error... Traceback (most recent call last): File "/home/hadi/Documents/first_django_project/poppulate_first_app.py", line 4, in <module> from first_app.models import * File "/home/hadi/Documents/first_django_project/first_app/models.py", line 6, in <module> class Topic(models.Model): File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/apps/registry.py", line 135, in check_apps_ready settings.INSTALLED_APPS File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 63, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I tried to run it on Windows too, but the same error, also I recreate the projcet in case I miss with settings or something, also I tried most of the answers posted here but none of them worked for me. I do not know why. so depressing! Here is my poppulate_first_app.py code: import django import random from faker import Faker from first_app.models import * import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') django.setup() # FAKE POP SCRIPT fake_gen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = … -
Heroku background services writing to database
I need a web service that continuously pulls data from a remote server, stores it and makes it accessible to other clients. My idea was to use (1) a Heroku web service with Django for web access and (2) a Heroku clock scheduler to run a run a script repetitively in the background. However, while the script runs fine, i am stuck with how to write back the data to the Django data model. Trying to create instances of my Django data models causes an exception (app has not been loaded yet), probably because both services run independently. So, what would be the best setup for my problem? It seems like a very common task so i am probably missing something obvious. Thanks! -
How to Serilize a Model when it has Foriegn Key Relation with default User Model in Django
Models.py I have Model named Message it has Foriegn Key Realation with default User Model Django .i want to serilize this model. from django.db import models from django.contrib.auth.models import User from django.conf import settings class Message(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,) content=models.CharField(max_length=100) timestamp=models.DateTimeField(auto_now_add=True) def __str__(self): return self.author.username views.py from classes.models import ClassRoom,Student from classes import views from django.http import HttpResponse, JsonResponse from django.contrib.auth.models import User from chat.models import Message from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render from django.core import serializers @login_required def course_chat_room(request,id): course = ClassRoom.objects.get(id=id) return render(request, 'chat/room.html',{'course':course}) def getMessages(request,id): serials = serializers.serialize('json', Message.objects.all().order_by("-id")) return JsonResponse(serials, safe=False) urls.py here is my urls of this app from django.urls import path from . import views app_name = 'chat' urlpatterns = [ path('room/<int:id>/', views.course_chat_room,name='course_chat_room'), path('room/<int:id>/ajax/', views.getMessages,name='getMessages'), ] Result when i run this i got the result like this below.i get the author id =10,11,9 etc i want the username instead .how to do this .i know about one technique i.e use_natural_foriegn key but i did not impelemt it in user model in this,because i dont know to to write manager for default user model .The data of message model is saved in database i retrived it in json format … -
Class Based Multi Environment Django Settings
In an effort to avoid from .local_settings import * and based on that post, I created a class-based settings file. The idea is to have a Common class which is inherited from Dev or Prod class as such: ./my_project/settings.py: import sys settings_module = sys.modules[__name__] class Common: SETTING1 = 'set' SETTING2 = 'set again' def __init__(self): for each in dir(self): if each.isupper(): setattr(settings_module, each, getattr(self, each)) class Dev(Common): SETTING1 = 'set_dev' class Prod(Common): SETTING1 = 'set_prod' #initialize the chosen class Prod() Is it a good idea? Django imports the settings as a module and discourages any other use. It seems to be working. -
How to hand it over to python shell from within a python script? [closed]
I want a python script to setup some context and variables and then give me the python shell and enable me interactive execution of python commands. I have seen this pattern in Django shell. My question is, what is the correct way of implementing such a feature? -
Django: Making a new copy of an mp3 file with a new name in a new folder
I want to copy the latest uploaded mp3 file from the object list in my first model (which uses the default media folder) to a new folder called ‘latest’ and I also want to rename the new copy ‘latest.mp3’. This is so that I have a known filename to be able to process the latest uploaded file using Javascript. I wish to also keep the original, unaltered, uploaded file in the object list of my first model. The below is what I have so far but it doesn’t work: I don’t get any traceback error from the server or from the browser. However, the copy isn’t made in the ‘latest/’ folder. I believe I am doing more than one thing wrong and I am not sure if I should be using CreateView for the SoundFileCopy view. I am also not sure when the process in SoundFileCopy view is triggered: I am assuming it happens when I ask the browser to load the template ‘process.html’. I am using Django 3.1.7 If anyone can help me by letting me know what I need to put in my models, views and template to get this to work I would be very grateful. Currently … -
Toggle does not display. Django
I am currently following this tutorial but with my own template that I got from w3layouts. I am using it as a practice project to better learn Django. I am currently trying to implement a user login/signup page. When you click on the icon/image that represents the user, you are supposed to be treated with a drop down lift of, My account, my favorites, my cart etc. etc. As I am using a different template from the one in the video, I understand that there may be issues. The following is the Lecturers( guys tutorial I'm following) drop down for user functionality. <li class="header-account dropdown default-dropdown"> {% if user.id is not None %} <div class="dropdown-toggle" role="button" data-toggle="dropdown" aria-expanded="true"> <div class="header-btns-icon"> <img src="{{ request.session.userimage }}" style="height: 40px; border-radius: 30%"> </div> <strong class="text-uppercase">{{ user.first_name }} <i class="fa fa-caret-down"></i></strong> </div> {% else %} <a href="{% url 'login' %}" class="text-uppercase">Login</a> / <a href="{% url 'signup' %}" class="text-uppercase">Sign Up</a> {% endif %} <ul class="custom-menu"> <li><a href="{% url 'user_index' %}"><i class="fa fa-user-o"></i> {% trans "My Account" %}</a></li> <li><a href="#"><i class="fa fa-heart-o"></i> {% trans "My Favorits" %}</a></li> <li><a href="{% url 'user_orders' %}"><i class="fa fa-exchange"></i> {% trans "My Orders " %}</a></li> <li><a href="{% url 'user_comments' %}"><i class="fa fa-check"></i> …