Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django form isn't inserting values from views.py file
I'm trying to insert values into a Django Database using both HTML and a generated value from views.py This is my views.py def NewPassword(request): if request.method == "POST": if request.POST.get('app_name') and request.POST.get('url') and request.POST.get('username') and request.POST.get('email') and request.POST.get('Category'): form = PasswordsForm() form.app_name = request.POST.get('app_name') form.url = request.POST.get('url') form.username = request.POST.get('username') form.email = request.POST.get('email') form.category = request.POST.get('Category') print(form.app_name,form.url,form.username,form.email,form.category) new_password = GeneratePassword() new_password = HashPassword(new_password) form.password = new_password if form.is_valid(): print("Form saved") form.save() return redirect('/') else: form = PasswordsForm() form.app_name = request.POST.get('app_name') form.url = request.POST.get('url') form.username = request.POST.get('username') form.email = request.POST.get('email') form.category = request.POST.get('category') form.password = request.POST.get('password') print(form.app_name,form.url,form.username,form.email,form.category,form.password) if form.is_valid(): print("Form saved") form.save() return redirect('/') if form.is_valid() != True: print("Invalid Form") else: form = PasswordsForm() form = PasswordsForm() return render(request,'manager/create.html',{'form':form}) I get the Invalid Form error because the form fails the if form.is_valid() != True I don't think it's a form error because it's fully generated by Django. It is failing the is_valid condition but all the specific values have been added to the form. This is the models.py file TECH = 'TECH' NONE = 'NONE' BIZ = 'BIZ' EMAIL = 'EMAIL' ENT = 'ENT' FIN = 'FIN' GAMES = 'GAMES' NEWS = 'NEWS' OTHER = 'OTHER' SHOP = 'SHOP' SOCIAL = … -
New object not added to queryset in Django
Here is the model class Student(models.Model): """Student info""" id = models.CharField( max_length=7,primary_key=True) name = models.CharField(_('name'),max_length=8, default=""); # help_text will locate after the field address = models.CharField(_('address'),max_length=30,blank=True,default="") #blank true means the GENDER_CHOICES = [("M", _("male")),("F",_("female"))] student_number = models.CharField(max_length=10,blank=True) gender = models.CharField(_("gender"),max_length=6, choices = GENDER_CHOICES, default="M"); I user shell to create two users as below: But the queryset number didn't increase although I created two users. #I hate Django. Q = Q -
Google App Engine is consistently returning 400 response to non-custom domain
My use case is a Django app running in an app-engine service and I am using cloud tasks to execute async work in the background. Django creates task -> task posts back to Django to execute long-running task That post back is consistently encountering a 400 response from the server. After looking through the logs it appears that it is posting back a relative url with the host being the default google given domain i.e. sample-development-app.uc.r.appspot.com. When I navigate to that location in the browser I also encounter a 400 response. However, I have a custom domain set up and working on this application i.e. app.development.sample.com. When I navigate to this location in a browser I get the expected webpage. I have tried mapping both urls with a dispatch.yaml to the same default service, but that didn't change the result. My working assumption is that the task postback is encountering the same issue I am seeing in the browser. This is my first project on gcp app engine, so I am thinking I am missing something in a menu someplace to allow it to accept multiple urls, one of them being the default google supplied one. Thanks for reading this … -
django app on heroku keeps logging me as the same user regardless of what credentials I use
I've tried from authenticating from different devices but to no avail. Any suggestions as to why this is happening and how to fix it? -
render_to_string returning in a class based view
I have a django form that is made through a CreateView and ajax. The form is created fine through render_to_string however when i try to post it, the render_to_string line returns a NoReverseMatch error. Found this super confusing as im trying to store the render to string in a dictionary and return it as a JsonResponse: class ProjectFileCreateView(LoginRequiredMixin, CreateView): model = MyModel form_class = MyForm def get(self, request, *args, **kwargs): """Handle GET requests: instantiate a blank JSON version of the form.""" data, context = dict(), dict() form = MyForm() context = {'form': form, 'slug': self.kwargs['slug']} data["html_form"] = render_to_string("app/includes/partial_create.html", context, request=request) return JsonResponse(data) def post(self, request, *args, **kwargs): """ Handle POST requests: instantiate a form instance with the passed POST variables and then check if it's valid. """ data = dict() context = dict() form = MyForm(request.POST) if form.is_valid(): form.save() data["form_is_valid"] = True context = {'files': MyModel.objects.filter(project__slug=self.kwargs['project_slug']), 'project_slug': self.kwargs['project_slug']} data["html_form_list"] = render_to_string("project/file_list.html", context) else: data["form_is_valid"] = False data["html_form"] = render_to_string("project/includes/partial_create_file.html", {'form': form}, request=self.request) return JsonResponse(data) I comment out the the render_to_string and no error is thrown, however no object is created either. The full traceback is: Traceback (most recent call last): File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\asgiref\sync.py", line 472, in thread_handler raise exc_info[1] File "C:\Users\liam.obrien\AppData\Local\pypoetry\Cache\virtualenvs\tdd-framework-FOYpVOaj-py3.10\lib\site-packages\django\core\handlers\exception.py", … -
Django: use update_or_create having the foreign key value but not a foreign key object instance
I have a data from a raw sql query which has records that look like this: "product_id": 12345 "date": 2022-12-25 "qty": 10 this is to go into a table with model "ProductMovement". Its unique key is product_id and date. product_movement has product_id as a foreign key to the Product model. ProductMovement.objects.update_or_create() requires me to provide an instance of the Product model, not merely the unique key. This is inconvenient. I guess I can use raw sql (backend is postgresql) but I wonder if there is another way. Can I add something to the model manager that intercepts the key value and replaces it with the instance, so at least I can hide this complexity from this part of the code? (I have never worked with model manager overrides). -
Pytest-django - testing creation and passing a required User object
Apologies if this has already been answered elsewhere. I cannot find an answer which I can retrofit into my situation. I'm new to django so I feel the problem is me not getting a fundamental grasp of a presumably basic concept here... Using DRF and pytest-django, i'm trying to be diligent and write tests along the way before it becomes too time consuming to manually test. I can see it snowballing pretty quickly. The issue I face is when I try to test the creation of a Catalogue, I can't get it to pass an User instance to the mandatory field 'created_by'. The logic works fine when I test manually, but writing the test itself is causing me headaches. Many thanks in advance! The error is: TypeError: Cannot encode None for key 'created_by' as POST data. Did you mean to pass an empty string or omit the value? Code provided. # core/models.py from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField(unique=True) # workshop/models.py from django.conf import settings from django.db import models class CatalogueItem(models.Model): TYPE_GOODS = 'GOODS' TYPE_SERVICES = 'SERVICES' TYPE_GOODS_AND_SERVICES = 'GOODS_AND_SERVICES' TYPE_CHOICES = [ (TYPE_GOODS, 'Goods'), (TYPE_SERVICES, 'Services'), (TYPE_GOODS_AND_SERVICES, 'Goods & Services') ] catalogue = models.ForeignKey( Catalogue, on_delete=models.CASCADE, related_name='catalogueitems') … -
Can Flask or Django handle concurrent tasks?
What I'm trying to accomplish: I have a sensor that is constantly reading in data. I need to print this data to a UI whenever data appears. While the aforementioned task is taking place, the user should be able to write data to the sensor. Ideally, both these tasks would / could happen at the same time. Currently, I have the program written using flask; but if django would be better suited (or a third party) I would be willing to make the switch. Note: this website will never be deployed so no need to worry about that. Only user will be me, running program from my laptop. I have spent a lot of time researching flask async functions and coroutines; however I have not seen any clear indications if something like this would be possible. Not looking for a line by line solution. Rather, a way (async, threading etc) to set up the code such that the aforementioned tasks are possible. All help is appreciated, thanks. -
PyGraphViz isnt running with Django error when django is installed
Django is running into an issue where when I try to run the PyGraphViz manage.py script it errors when it tries to import django.core.management Traceback (most recent call last): File "/home/zoctavous/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 259, in fetch_command app_name = commands[subcommand] KeyError: 'graph_models' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./manage.py", line 21, in <module> main() File "./manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/zoctavous/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/zoctavous/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/zoctavous/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 266, in fetch_command settings.INSTALLED_APPS File "/home/zoctavous/.local/lib/python3.8/site-packages/django/conf/__init__.py", line 92, in __getattr__ self._setup(name) File "/home/zoctavous/.local/lib/python3.8/site-packages/django/conf/__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) File "/home/zoctavous/.local/lib/python3.8/site-packages/django/conf/__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in … -
Deploy django channels to dcoker and use nginx has a proxy server
Im trying to deploy django channels using docker, and im using the daphne protocol to serve the application. when i run that its starts successfully but i'm unable to connect with the websocket. i can connect with the application in other routes but cannot connect with the websocket the websocket is served in HTTPS://EXAMPLE.COM/WS/SOCK this is my asgi.py application = ProtocolTypeRouter({ 'http': django_asgi_app, 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter(websocket_urlpatterns) ))}) Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 WORKDIR /myproject ADD . /myroject RUN pip install -r /myprjoect/requirements.txt EXPOSE 8000 CMD ["daphne", "-b", "0.0.0.0", "-p", "8000", "myproject.asgi:application"] nginx.conf location / { proxy_set_header Host $http_host; proxy_set_header X-Forward-Proto https; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://localhost:8443/; } #path to proxy my WebSocket requests location /ws/ { proxy_pass http://localhost:8443; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection “upgrade”; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } and im using the docker-compose to up the application anf its configuration is version: "3.8" services: myservice: image: myimage container_name: my_container ports: - 8443:8000 -
How to get many2many queryset of a model while creating it (while save() is running)
I have a model "Team" for soccer team and a model "Contest" for soccer match. For a Contest model creation, the name is automatically assigned. Then, while save() I want to modify the name of contest to something related to the teams that compete. So in my Contest model I have a ManyToMany field 'teams' related to my 'Team' model. While save(), I used super().save(*args, **kwargs) before get my item so it exists. Then I want get a queryset by self.objects.teams.all() but each time the queryset is empty : <QuerySet []>. Yet, the object exists. Feel like Django has not yet related the teams or something. How can I do that ? Contest model : class Contest(models.Model): name = models.CharField(max_length=16, primary_key=True, unique=True, default="InactiveContest", blank=True) # Ex: PSGvMNC_09/2017 id = models.IntegerField(default=1) teams = models.ManyToManyField(Team, verbose_name="opposants") date = models.DateTimeField(blank=True) winner = models.ForeignKey(Team, verbose_name='gagnant', related_name='winner', on_delete=models.SET_NULL, blank=True, null=True) loser = models.ForeignKey(Team, verbose_name='perdant', related_name='loser', on_delete=models.SET_NULL, blank=True, null=True) active = models.BooleanField(default=False) def save(self, *args, **kwargs): if self._state.adding: self.active = False # Django's id imitation last_id = Contest.objects.all().aggregate(Max('id')).get('id__max') if last_id is not None: self.id = last_id + 1 super().save(*args, **kwargs) # Now I can get it teams = self.teams.all() if not teams: raise ValueError("Not teams.") # … -
Django model method paramter with default value from related
I need a model method with parameter with default value: class MyModel(modelsModel): parameter1 = models.DecimalField(max_digits=8,decimal_places=6, default=0) def my_method(self, parameter = parameter1) return parameter so if use print("{} - {}".format(object.my_method(),object.my_method(12.6)) it's ok But i need it more nested: class MySubModel(modelsModel): parameter1 = models.DecimalField(max_digits=8,decimal_places=6, default=0) class MyModel(modelsModel): submodel = models.ForeignKey(MySubModel, on_delete = models.RESTRICT) def my_method(self, parameter = submodel.parameter1) return parameter And this raises error: AttributeError: 'ForeignKey' object has no attribute 'parameter' Ideas? -
Updating database data from websocket
I would like to update database data from a websocket. Specifically, when a user connects to a websocket, I would like to update a field in one of my models with the timestamp of when the user connected. However, with the logic I have implemented, I am getting this error: Exception inside application: __init__() takes 1 positional argument but 2 were given Traceback (most recent call last): File "C:\Users\15512\anaconda3\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\security\websocket.py", line 37, in __call__ return await self.application(scope, receive, send) File "C:\Users\15512\Desktop\django-project\peerplatform\signup\middleware.py", line 47, in __call__ return await super().__call__(scope, receive, send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\routing.py", line 150, in __call__ return await application( File "C:\Users\15512\anaconda3\lib\site-packages\channels\consumer.py", line 94, in app return await consumer(scope, receive, send) File "C:\Users\15512\anaconda3\lib\site-packages\channels\consumer.py", line 58, in __call__ await await_many_dispatch( File "C:\Users\15512\anaconda3\lib\site-packages\channels\utils.py", line 51, in … -
Set and call a variable in HTML (potentially including javascript) in django
I have a HTML code in Django, if certain conditions are met I want to set the colour of a div container. As can be seen in between the script tags, if one condition is met the colour should be set to success, if another is met the colour should be set to danger, then later on in the code in the div class description where I have put (colour) is where this variable should be called. Any advice would be greatly appreciated -
500 internal server error while using Django and React
I faced some problem using react and django. When I made a http request to django server, I got 500 Internal Server Error. My code looks like. urls.py from usercontrol.views import * urlpatterns = [ path('admin/', admin.site.urls), path('auth/', UserView.as_view(), name="something") ] usercontrol/views.py from http.client import HTTPResponse from django.shortcuts import render from rest_framework.views import APIView from . models import * from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated, AllowAny # Create your views here. class UserView(APIView): permission_classes = [AllowAny] def get(self, request): if request.user.is_authenticated: print ("HELO") return HTTPResponse("Hello") def post(self, request): return HTTPResponse("Hello") React Code axios.get("http://localhost:8000/auth/") .then((res) => { console.log(res); }) .catch((err) => {}); Why do I get 500 Internal Server Error? Please help me to fix this error. -
Modelformset extra field pk is rendered as next instance in Django
I don't get why my extra fields in Modelformset are rendered with next instance pk, when form where I have already saved data is showing relevant related model instance pk. Is this something why Django suggests to render pk field explicitly in the templates, so user to choose right related model pk? looks to me unbelievable, so please help me here... # My views.py from django.forms import modelformset_factory from .models import PreImplement # Pre Implement View def pre_implement_view(request, pk): moc = get_object_or_404(Moc, pk=pk) print(moc.pk) PreImplementFormSet = modelformset_factory(PreImplement, fields=('__all__'), can_delete=True, can_delete_extra=False) formset = PreImplementFormSet(queryset=PreImplement.objects.filter(moc_id=moc.pk), initial=[ {'action_item': 'go'}, {'action_item': 'nogo'}, {'action_item': 'na'}, ]) formset.extra=3 queryset=PreImplement.objects.filter(moc_id=moc.pk) print('babr', queryset) if request.method == 'POST': formset = PreImplementFormSet(request.POST, initial=[{'action_item': 'babrusito'}, {'action_item': 'go'}, {'action_item': 'nogo'}, {'action_item': 'na'}, ]) if formset.is_valid(): formset.save() return redirect('index') return render(request, 'moc/moc_content_pre_implement.html', context={'moc': moc, 'formset': formset}) This is continuation of my previous SO post struggles: Populate model instance with another model data during instance creation Here is snapshot from my template: -
Issues with looping through an object in django channels
Am Trying to loop through an a model object in django, I think this the error is coming from consumer.py file this file in particular, I keep getting this error for message in messages: TypeError: 'Messages' object is not iterable and i think the error comes from this code in particular def messages_to_json(self, messages): result = [] for message in messages: result.append(self.messages_to_json(message)) return result My models.py class Messages(models.Model): sender = models.ForeignKey(User, related_name='messages', on_delete=models.CASCADE) msg = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.sender.username def last_30_messages(self): return Messages.objects.order_by('-timestamp').all()[:20] My consumer.py from django.contrib.auth import get_user_model import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import Messages User = get_user_model() class ChatConsumer(WebsocketConsumer): def fetch_messages(self, data): messages = Messages.last_30_messages() content = { 'messages': self.messages_to_json(messages) } self.send_chat_message(content) def new_messages(self, data): sender = data['from'] author_user = User.objects.filter(username=sender)[0] message = Messages.objects.create(sender=author_user, msg=data['message']) content = { 'command': 'new_messages', 'message': self.messages_to_json(message) } return self.send_chat_message(content) def messages_to_json(self, messages): result = [] for message in messages: result.append(self.messages_to_json(message)) return result def message_to_json(self, message): return { 'sender': message.sender.username, 'msg': message.msg, 'timestamp': str(message.timestamp) } command = { 'fetch_messages': fetch_messages, 'new_messages': new_messages } def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["room_link"] self.room_group_name = "chat_%s" % self.room_name async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( … -
How do I add custom user model fields to the Wagtail user settings page?
I am building a wagtail site. I've followed the instructions found in the docs and my additional fields show up in the edit and create user forms, found at [site url]/admin/users/[user id]. However, I want them to also show up in the account settings page accessed from the bottom left. This page seems to describe what I want to do, but I don't understand the instructions it gives. I have an app named user, and my settings point the AUTH_USER_MODEL to the model User within it. My models.py in this app is as follows from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): id = models.AutoField(primary_key=True) bio = models.CharField(blank=True, null=True, max_length=2048) nickname = models.CharField(blank=True, null=True, max_length=64) def __str__(self): """String representation of this user""" return self.get_full_name() and my forms.py is from django import forms from django.utils.translation import gettext_lazy as _ from wagtail.users.forms import UserEditForm, UserCreationForm class CustomUserEditForm(UserEditForm): nickname = forms.CharField(required=False, label=_("Nickname")) bio = forms.CharField(required=False, label=_("Bio")) class CustomUserCreationForm(UserCreationForm): nickname = forms.CharField(required=False, label=_("Nickname")) bio = forms.CharField(required=False, label=_("Bio")) From the docs it sounds like I would want to add something like this to that same forms.py: class CustomSettingsForm(forms.ModelForm): nickname = forms.CharField(required=False, label=_("Nickname")) bio = forms.CharField(required=False, label=_("Bio")) class Meta: model = django.contrib.auth.get_user_model() fields = … -
Add column Heroku database
Goodnight. I have a project done in Python and Django and today I added one more Model Table and added a column manually and it worked in the development environment. But when deploying to Heroku , Heroku cannot find this manually created column and returns this error "column does not exist" . How do I manually add a column to the Heroku database? -
Django Error: Reverse for 'delete_ingredient' not found. 'delete_ingredient' is not a valid view function or pattern name
I'd appreciate whatever help you can give to get me past this block. Thanks! The code breaks when I modify the code that used to work to add Delete functionality. When I run the code without the modified urls.py I get the error. The error is: > NoReverseMatch at /ingredients/ Reverse for 'delete_ingredient' not found. 'delete' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ingredients/ Django Version: 4.1.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'delete_ingredient' not found. 'delete' is not a valid view function or pattern name. Exception Location: C:\Users\Dropbox\Python Projects\Django Projects\djangodelights\djangodelights_env\lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefix Raised during: inventory.views.IngredientsView Python Executable: C:\Users\Dropbox\Python Projects\Django Projects\djangodelights\djangodelights_env\Scripts\python.exe Python Version: 3.9.5 Python Path: ['C:\\Users\\Python Projects\\Django ' 'Projects\\bwa-django-final-project-main\\bwa-django-final-project', 'C:\\Users\\Python Projects\\Django ' 'Projects\\djangodelights\\djangodelights_env\\Scripts\\python39.zip', 'd:\\users\\miniconda3\\DLLs', 'd:\\users\\miniconda3\\lib', 'd:\\users\\miniconda3', 'C:\\Users\\Python Projects\\Django ' 'Projects\\djangodelights\\djangodelights_env', 'C:\\Users\\Python Projects\\Django ' 'Projects\\djangodelights\\djangodelights_env\\lib\\site-packages'] Server time: Wed, 19 Oct 2022 19:44:34 +0000 Error during template rendering In template C:\Users\Dropbox\Python Projects\Django Projects\bwa-django-final-project-main\bwa-django-final-project\inventory\templates\inventory\ingredients_list.html, error at line 30 Reverse for 'delete_ingredient' not found. 'delete' is not a valid view function or pattern name. 20 </thead> 21 <tbody> 22 {% for ingredient in object_list %} 23 <tr> 24 <td> 25 <a href="{% url "update_ingredient" ingredient.id %}">{{ ingredient.name }}</a> 26 </td> 27 <td>{{ ingredient.quantity … -
AppConfig.__init__() missing 1 required positional argument: 'app_module'
Just running my first app but facing this issue. **AppConfig.__init__() missing 1 required positional argument: 'app_module'** Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1.2 Exception Type: TypeError Exception Value: AppConfig.__init__() missing 1 required positional argument: 'app_module' Exception Location: \studybud\env\lib\site-packages\django\template\context.py, line 254, in bind_template Raised during: base.views.home views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'home.html') def room(request): return render(request, 'room.html') Settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / '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', 'base.apps.BaseConfig' ], }, }, ] urls.py from django.urls import path from . import views urlpatterns = [ path ('',views.home, name="home"), path ('room/',views.room, name="room"), ] -
Django mail attachments blank except for 1st email sent, when looping through recipients
I have a newsletter being sent out using Django forms, with multiple files that can be attached. I'm looping through the list of recipients (if they are verified, and agreed to receive the newsletter, etc.) It all works fine, emails are received to these users, including 1 or more attached files. The problem is only the first user gets file\s with content, others get the file/s, but they are empty/blank (Zero bytes). Is it linked to some temp files or the need to cache these files first? so they're available for the loop to handle? (note: the file name, number of files, etc. received to all recipients is all correct - they are just empty, except the first email) How can I resolve that? Thanks forms.py class NewsletterForm(forms.Form): message = forms.CharField(widget = forms.Textarea, max_length = 8000) attach = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False) views.py def newsletter(request): users = User.objects.all() receipient_list = [] for user in users: if user.profile.newsletter_agree == True and user.profile.verified_member == True: receipient_list.append(user.email) if request.method == 'POST': form = NewsletterForm(request.POST, request.FILES) if form.is_valid(): mail_subject = 'Some newsletter subject' message = form.cleaned_data['message'], files = request.FILES.getlist('attach') for contact_name in receipient_list: try: email = EmailMessage(mail_subject, message, 'email@email.com', to=[contact_name]) email.encoding = 'utf-8' for f … -
502 gateway on reverse proxy after adding python module pandas
I'm configured with a reverse proxy using nginx to 2 backend servers with different applications that are both python / django running on apache. They direct users to the correct application and everything was working fine until I installed a new module in python. Specifically the pandas module. Now, when loading the application site with the pandas module loaded, it gives me a 502. If I comment out the "import pandas" line from views, it loads fine. No idea what could be causing this. Anyone know? -
Docker on Virtual Box
I installed Docker on Virtual Box because my computer is 32-bit and Docker only ran on 64-bit systems. Now, how can I use Docker on my editor and windows terminal? -
django-main-thread error when running manage.py runserver
I've made some changes to my code while trying to deploy my django app on digital ocean, and now when I try to test my code in my local server, I get this error: (my_chaburah) ~/Desktop/Code/my_chaburah (main) $ python3 manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 24, in <module> import psycopg2 as Database File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/psycopg2/__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: dlopen(/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so, 0x0002): Library not loaded: '/opt/homebrew/opt/postgresql/lib/libpq.5.dylib' Referenced from: '/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so' Reason: tried: '/opt/homebrew/opt/postgresql/lib/libpq.5.dylib' (no such file), '/usr/local/lib/libpq.5.dylib' (no such file), '/usr/lib/libpq.5.dylib' (no such file), '/opt/homebrew/Cellar/postgresql@14/14.5_5/lib/libpq.5.dylib' (no such file), '/usr/local/lib/libpq.5.dylib' (no such file), '/usr/lib/libpq.5.dylib' (no such file) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.9/3.9.15/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 980, in _bootstrap_inner self.run() File "/opt/homebrew/Cellar/python@3.9/3.9.15/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/apps/config.py", line 304, in …